A decision stump is a tree with one question: “is above 4.5?” It is about the weakest useful model there is. On most data it is only a little better than guessing. Can a few hundred of them, each asking one question, add up to a model that is accurate?
Yes, if they are not trained independently. Train the first stump. Look at where it fails. Train the second stump to be good where the first was bad. Look at where the pair still fails, and aim the third there. This is boosting: add simple models one at a time, each focused on what the ensemble so far gets wrong. This lesson works it through twice, with two famous recipes. AdaBoost does it by changing how much each example counts. Gradient boosting does it by changing the target each new tree is fitted to.
The idea, and how it differs from a forest
A weak learner is a model that is only a little better than chance: for a two-class problem, a weighted error below is all that is needed. A decision stump (P3.B3) is the standard example. Boosting combines many weak learners into a strong learner: in theory, one whose error can be made as small as you like. The training-error bound in the Go-deeper box below shows how fast the error on the training data falls. Accuracy on new data is a separate question, as the overfitting sections show.
The recipe has three parts that every boosting method shares.
- Fit a weak learner to the data as it stands.
- Find out where the ensemble so far is wrong, and make the next learner care about those places.
- Add the new learner to the ensemble with a weight, and repeat.
Bagging and random forests (P3.B4) also combine many trees, but in the opposite spirit.
| Bagging, random forest | Boosting | |
|---|---|---|
| How the trees are built | Independently, each on a bootstrap resample | One after another, each depends on the earlier ones |
| Typical tree | Deep: low bias, high variance | Shallow: high bias, low variance |
| What combining does | Averaging cuts variance | Adding cuts bias (mainly) |
| More trees | Usually does not cause overfitting by itself | Can overfit |
The bias and variance on the last rows are from P3.A5. The ideas of boosting came from learning theory, which asked whether a rule only slightly better than guessing could be turned into an accurate one (Schapire, 1990 gave the first answer: yes). AdaBoost, by Freund and Schapire (1995, in full 1997), was the first algorithm of this kind to be widely used.
AdaBoost by hand
AdaBoost (adaptive boosting) is for two classes, labelled and . It keeps one weight per training example. The weights are positive and add up to . They say how much each example counts when a weak learner is fitted and judged. The steps for round are these.
Step 1: fit. Fit a weak learner (here a stump, whose output is or ) that makes the weighted error as small as it can:
That is the total weight of the examples it gets wrong.
Step 2: vote. Give it the vote
A stump with a small error gets a large vote.
Step 3: reweight. Update the weights and renormalise, so they add to again:
A correct example has , so its weight is multiplied by (smaller). A mistake has , so its weight is multiplied by (larger). is the sum of the new weights, which does the renormalising.
After rounds the final classifier is the sign of the weighted vote:
A worked example with ten points
Ten points sit at . The labels are everywhere except at and , where they are . No single stump can get all ten right. A stump here is “predict one class for above a threshold and the other class below”, and the candidates are with either sign. At the start each weight is .
Round 1. The best stump predicts for and for . It gets everything right except , so . Its vote is , and . The update multiplies the weight of by and every other weight by :
- the mistake: ,
- each of the nine correct points: ,
- the sum is , so the new weights are at and elsewhere.
The point now holds half of all the weight, and half is also the weight of the single mistake. That is not an accident, as the box below shows.
Round 2. With these weights, the best stump predicts for and above. It is wrong at , so and , with . It gets right, so that weight shrinks. New weights: at , at each of , and at the other six points. The mistakes of round 2 hold exactly half the weight again.
Round 3. The best stump now predicts for and above. It is wrong at and : , so . The weights after the update are at and at , at and at .
The vote. Add at each point. Here are the three stumps, in the order :
- to : gives , class . Correct.
- : gives , class . Correct, although the first stump was wrong here.
- to : gives , class . Correct.
- : gives , class . Correct.
The ensemble gets all ten right. After round 1 it had one mistake, after round 2 still one, after round 3 none. Each stump alone makes between one and six mistakes. The numbers can be checked by running the cell below. It also prints the weights after each round.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Change the labels in the cell, for example flip the label at , and see how many rounds it takes before the ensemble is right everywhere, or whether it ever is.
What the vote and the weights are doing
- A better stump votes louder. grows as shrinks: gives , gives , gives .
- A stump no better than guessing gets no vote. At the vote is . A stump with gets a negative vote, which means “do the opposite”. In practice the learner is picked to have , or the loop stops. At the vote would be infinite; implementations stop at that point (scikit-learn does).
- The next stump cannot repeat the last one. After the update, the previous stump’s mistakes hold exactly half the weight, so on the new weights it is no better than a coin flip. The next stump must find something different to be good at. That is how the rounds avoid doing the same job twice.
- Hard points gain weight. The point went from to in one round. If a label is simply wrong (noise), AdaBoost keeps raising its weight and bending the ensemble towards it, so it is often reported to be sensitive to label noise and outliers.
Go deeper Why this vote, why this reweighting, and how fast the training error falls
The vote. After the update, the total weight on correct points is and on mistakes , where . The choice is the one that makes as small as possible: setting the derivative to zero gives . At that value , so correct points and mistakes each hold exactly half, and .
Training error. The mistake indicator is at most an exponential: with . Unrolling the weight updates shows that the average of over the training set equals . So the training error of the ensemble is at most . In the example this product is , while the real training error is . Writing gives the bound , so if every stump beats chance by at least , the training error falls exponentially in the number of rounds. This is the sense in which weak learners become a strong learner.
A hidden loss. AdaBoost is exactly a greedy, stage-by-stage minimisation of the exponential loss over sums of weak learners. Friedman, Hastie and Tibshirani showed this in 2000. That view is what led to the next section: if AdaBoost is boosting for one particular loss, other losses should work too.
Gradient boosting: fit the residuals
AdaBoost reweights the examples. Gradient boosting (Friedman, 2001) keeps the examples as they are and changes the target instead. It works for regression and classification with any loss that can be differentiated. We start with the simplest case: regression with squared error.
The model is a running prediction . Start with a constant. The residual of an example is what is still missing, : positive if the model is too low there, negative if too high. Fit a small tree to the residuals and add it, so that the model moves towards the targets. Repeat.
A worked example with six points
Take and . Use stumps, and shrink every tree by before adding it (more on below).
Start. The best constant for squared error is the mean, . The residuals are . The mean squared error (MSE) is .
Round 1. Fit a stump to the residuals. The best cut is between and . Its leaves hold the average residual on each side, on the left and on the right. Add half of it: for and for . The new residuals are and the MSE is .
Round 2. Fit a stump to these. The best cut is the same, with leaf values and . Now on the left and on the right. The residuals are and the MSE is .
Round 3. The leftover is now mostly at the two ends. The best cut moves to between and , with leaf values and . (Cutting between and ties exactly, by symmetry; we take the left cut, as the code does.) Then is at , at and , and at . The MSE is .
The MSE went . Each tree is a crude step function, but each one is aimed at what is left. With the first stump would jump straight to the leaf averages, , and the MSE would be after one round. With it goes only half of the way and leaves half of the residual for the next trees.
Why this is gradient descent
For one example, the squared-error loss of a prediction is . Its derivative with respect to the prediction is so the negative gradient is the residual . That is why fitting the residuals is the same as following the negative gradient.
Gradient descent (P1.F3) updates parameters by . Here the quantities being adjusted are not weights but the model’s predictions on the training points. The loss has a gradient with one entry per example. One could just step against it, , but that only changes the predictions at the training points and says nothing about a new . So instead a tree is fitted to the entries , and the tree is added. The tree is a least-squares approximation of those gradient values, and unlike them it is defined for every . This is gradient descent in function space: the model is a sum of functions, and each step adds one.
The general recipe, for any differentiable loss :
- Start with the constant that has the lowest total loss (the mean, for squared error).
- For : compute the pseudo-residual for every training example. Fit a small tree to the pairs . Set .
- Predict with .
“Pseudo-residual” is the name for the negative gradient when the loss is not squared error, because then it is no longer simply .
Log loss for classification. For a label , let be the log-odds and the predicted probability, with . A short calculation gives : the label minus the predicted probability. The recipe stays the same, only the target of each tree changes. For three examples with and the pseudo-residuals are , which is what a numerical derivative also gives. (This is the of P3.A7 with its sign flipped, because a pseudo-residual is the negative gradient.) The final probability is the sigmoid of . For absolute error the pseudo-residual is only the sign of . Many implementations also recompute the values in the leaves using second derivatives of the loss. The leaves above are the plain-average version.
See it: each new tree fixing the residuals
The widget below runs gradient boosting on made-up data: plus random noise with standard deviation , with training points (dots) and validation points (hollow squares). Press Add a tree to take one round at a time.
Things to try.
- Step through the first rounds at the defaults (depth 2, ). Round 0 is a flat line at the mean, , with training MSE . Look at the orange segments: they are long where the data are far from the line. The pink tree in the middle plot steps up where the residuals are positive and down where they are negative. After one round the blue curve moves towards the points by times the pink step, and the segments shorten.
- Watch the two error curves. Training MSE falls all the way: after one round, after eleven, after a hundred. Validation MSE falls to at round 11 (the dashed green line) and then rises to at round 100. The model is fitting the noise of the 30 training points. Jump to the best validation round takes you to the lowest point.
- Set the learning rate to 1 (depth 2). Each tree is added at full size, so the curve gets to the data much faster: the lowest validation error is at round 5, and by round 100 the training MSE is and the validation MSE is .
- Set the learning rate to 0.1. The curve creeps. The lowest validation error is at round 46 (and the validation MSE at round 100 is , not so far above its best).
- Depth 1 against 2 and 3. A stump cannot make a sharp wiggle, so it needs more rounds and overfits more slowly. Depth 3 fits the noise within a few rounds.
- Tiny learning rate. With depth 1 and the lowest validation error is at round 100, the end of the slider, so the curve has not finished falling. A small needs many more rounds.
The knobs, and overfitting
A boosted model has three main settings. They interact, so they are best chosen on a validation set (P3.A4).
The learning rate, (also called shrinkage). Every tree is multiplied by between and before it is added. A small makes each step careful, so no single tree can do much damage, but more rounds are needed. It plays the same role as the learning rate of gradient descent (P1.F3), and it is a regularizer, in the same family as the penalties of P3.A6. Here is what changes in the widget’s data, for depth-2 trees:
| best round | validation MSE there | validation MSE at round 100 | |
|---|---|---|---|
| 1.0 | 5 | 0.303 | 0.420 |
| 0.3 | 11 | 0.295 | 0.414 |
| 0.1 | 46 | 0.300 | 0.347 |
On this one small data set the best validation errors are about equal. What changes is how many rounds it takes to get there, and how far the error climbs when one carries on. Friedman (2001) proposed shrinkage as a form of regularization and reported that small values of gave better results than in his experiments, at the cost of more trees. Treat that as a common rule of thumb, not as a law.
The number of rounds, . More rounds mean lower training error always, and not lower validation error always. The standard defence is early stopping: hold out a validation set, track the validation loss after every round, and stop when it has not improved for some number of rounds (the “patience”). Then use the model from the best round. Two cautions. The best round was picked by looking at the validation set, so its error is a little optimistic; report the final number on a separate test set (P3.A4). And the validation curve is noisy, so a patience of one round would stop too early.
The tree depth. Depth sets how complicated each tree is. A stump uses one feature, so a sum of stumps is a sum of functions of single features, with no interactions between features. A depth- tree can model interactions among up to features. The widget’s data have a single input, so there is nothing to interact, and deeper trees only fit the noise sooner: the lowest validation MSE is for depth 1 (, round 55), for depth 2 and for depth 3. With many features the picture is different, and depths of a few levels are common. Boosting wants weak learners, so trees are kept shallow.
Subsampling. In stochastic gradient boosting (Friedman, 2002) each tree is fitted to a random fraction of the training rows, for example half, drawn fresh every round. It adds a little randomness in the spirit of bagging, makes each round cheaper, and is often found to help. Many libraries can also sample the features for every tree.
Boosting works on bias and variance (P3.A5) in a particular order. A stump has high bias, so early rounds mainly cut bias. Later rounds fit noise, so variance takes over. Shrinkage, early stopping, shallow trees and subsampling all hold back the variance.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
The first two lines check the six-point example. The table repeats the widget’s numbers. Edit the loops to try depth or other learning rates.
Boosting in practice
Hand-written trees like the ones above are slow and unregularized. In practice one uses a library. Three are used very widely, all built on gradient-boosted trees.
- XGBoost (Chen and Guestrin, 2016) adds a regularization term to the objective (a penalty on the number of leaves and on the size of the leaf values), uses both first and second derivatives of the loss, handles missing values, and is engineered to be fast.
- LightGBM (Ke et al., 2017) bins the feature values into histograms to find splits quickly, and grows each tree leaf-wise (best-first), one leaf at a time, always splitting the leaf that gains the most (“leaf-wise” growth), instead of level by level.
- CatBoost (Prokhorenkova et al., 2018) handles categorical features directly, and uses an ordering trick (“ordered boosting”) meant to avoid the model’s training predictions leaking the very labels they are fitted to.
- scikit-learn has
AdaBoostClassifier,GradientBoostingRegressorandGradientBoostingClassifier, which follow this lesson closely, andHistGradientBoostingClassifierandHistGradientBoostingRegressor, which use histogram-binned features like LightGBM, and are much faster on large data. They also accept missing values.
On many tables of data (rows are examples, columns are features of mixed types), gradient-boosted trees are often reported to match or beat other methods, including neural networks, especially on medium-sized data sets (Grinsztajn et al., 2022 compared them on a set of benchmarks). That makes them a common first thing to try for tabular data. It is an observation, not a guarantee: results depend on the data, and for images, audio and text, neural networks are the usual choice.
The three blocks below were run locally with scikit-learn 1.8. They cannot run in the browser, which has only NumPy. The first reproduces the AdaBoost example and the second the gradient boosting numbers of the widget.
import numpy as np
from sklearn.ensemble import AdaBoostClassifier
x = np.arange(1, 11).reshape(-1, 1)
y = np.array([1, 1, 1, 1, 1, -1,
1, 1, 1, -1])
ada = AdaBoostClassifier(
n_estimators=3, random_state=0)
ada.fit(x, y)
print("errors",
np.round(ada.estimator_errors_, 4))
print("alphas",
np.round(ada.estimator_weights_ / 2, 4))
print("train accuracy", ada.score(x, y))
errors [0.1 0.1667 0.2 ]
alphas [1.0986 0.8047 0.6931]
train accuracy 1.0
scikit-learn’s estimator_weights_ is , twice the of this lesson (it uses the multi-class form of the rule), so the code halves it. The sign of the vote is unchanged.
# xt, yt, xv, yv: the widget's data
# (the cell above makes them)
from sklearn.ensemble import GradientBoostingRegressor
g = GradientBoostingRegressor(
n_estimators=100, learning_rate=0.3,
max_depth=2, criterion="squared_error",
random_state=0)
g.fit(xt[:, None], yt)
tr = g.staged_predict(xt[:, None])
va = g.staged_predict(xv[:, None])
for m, (a, b) in enumerate(zip(tr, va), 1):
if m in (1, 11, 100):
print(m, round(((yt - a) ** 2).mean(), 4),
round(((yv - b) ** 2).mean(), 4))
1 0.3887 0.6611
11 0.07 0.295
100 0.0001 0.4135
These are the widget’s numbers at rounds 1, 11 and 100. The third block lets the library do the early stopping on a made-up two-moons data set of 2000 points ( held out as a test set).
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split
from sklearn.ensemble import HistGradientBoostingClassifier
X, y = make_moons(n_samples=2000, noise=0.3,
random_state=0)
Xtr, Xte, ytr, yte = train_test_split(
X, y, test_size=0.25, random_state=0)
clf = HistGradientBoostingClassifier(
learning_rate=0.1, max_iter=500,
early_stopping=True,
validation_fraction=0.1,
n_iter_no_change=10, random_state=0)
clf.fit(Xtr, ytr)
print("trees used:", clf.n_iter_)
print("train accuracy:",
round(clf.score(Xtr, ytr), 3))
print("test accuracy:",
round(clf.score(Xte, yte), 3))
trees used: 76
train accuracy: 0.976
test accuracy: 0.892
Of the 500 allowed trees, 76 were used: training stopped when the score on a 10% validation split had not improved for 10 rounds. Without early stopping, the same model with all 500 trees had training accuracy and test accuracy on this data set. That is a small gap from one data set, so read it as an illustration of the pattern, not a measurement of how large the effect is. (In scikit-learn, early_stopping="auto" turns early stopping on only for more than 10,000 samples, so for small data you have to ask for it.)
Common misunderstandings
Intuition
Think of a student revising for an exam by taking practice tests. After each test, the student does not re-read the whole book. They look at the questions they got wrong and study exactly those topics, then test again. Each round of study is small and focused. Over many rounds the weak spots are covered, one after another. Boosting is that loop. In AdaBoost the wrong questions are marked as more important. In gradient boosting the size of the miss is the new thing to learn. The analogy breaks at one point: a student who studies the questions they got wrong because the exam paper had a printing error learns the wrong answer. A boosted model that is fitted to noisy labels does the same.
Math
AdaBoost, labels , weights summing to :
Gradient boosting, with loss and learning rate :
Here is a tree fitted to the pairs . Squared error gives . Log loss with the log-odds gives . Exponential loss gives . AdaBoost is a greedy, stage-wise minimisation of this loss, with a weighted classifier as each step and an exact line search for .
Code
# gradient boosting for squared error, in outline (the runnable cell has the full version)
F = np.full(n, y.mean()) # F_0: the mean
for m in range(M):
r = y - F # residuals = negative gradient
tree = fit_small_tree(x, r) # fit the residuals
F = F + nu * tree.predict(x) # a small step in function spaceCheck your understanding
In AdaBoost, a stump has weighted error . What is its vote ?
The ratio , and half of its natural logarithm is . The value is the ratio turned upside down, and is the ratio itself, both without the half-logarithm. The value is the error, not the vote.
After AdaBoost has updated and renormalised the weights following a round, how much total weight do that stump's mistakes hold (when )?
Mistakes are multiplied by and correct points by , and with this both groups end up with before renormalising, so each holds half. The weight is not left at , because the update raises it. It is not zero: a mistake is made more important, not removed. The ratio is a different quantity, the odds of an error.
In gradient boosting with squared error, what is each new tree fitted to?
The negative gradient of squared error with respect to the prediction is the residual , so the new tree learns what is still missing. Reweighting the original targets describes AdaBoost, not gradient boosting. Fitting the previous tree's predictions would only copy it. The residuals change every round, because the ensemble changes.
You lower the learning rate from to and keep the tree depth. What is the typical effect?
Each tree is scaled by , so the model approaches the data more slowly: in this lesson the best round for depth-2 trees moves from 5 to 46. Depth is a separate setting that does not change. Training error reaches zero more slowly, not faster. A small slows overfitting down, but it does not remove it.
Which statement describes boosting rather than bagging?
Sequential fitting to the remaining error with weak, shallow trees is boosting. Independent deep trees on resamples that are averaged is bagging. Training trees independently on random feature subsets is the extra trick of random forests. The claim that more trees never raise the validation error describes a forest, and does not hold for boosting.
Exercises
- Four examples start with weights each. A stump gets exactly one of them wrong. Find , and the new weights after the update.
Show answer
, . Before renormalising, the mistake has and each correct example ; the sum is . After renormalising, the mistake has weight and each of the three correct examples . Again the mistake holds half of the total weight. - What is when ? What is it when , and what does the sign mean?
Show answer
gives : the stump gets no vote, as it is no better than a coin flip. gives : the stump is wrong more often than not, so its vote is reversed, and the reversed stump has . - Let and . Start from the mean and add one stump fitted to the residuals. Find the MSE after the round for and for .
Show answer
and the residuals are . The best stump cuts between and , with leaf values and . With : , residuals , MSE . With : , residuals , MSE . The smaller step leaves more error for later rounds to remove. - For log loss, find the pseudo-residual for and for .
Show answer
For , , so the residual is . For , , so the residual is . The model is confidently wrong in the second case, so its target is large and negative: the next tree is told to pull that prediction down hard. - In the widget, set depth 1 and and press Jump to the best validation round. Where does it land, and what does that say?
Show answer
It lands at round 100, the end of the slider, with validation MSE about . The lowest point is at the edge, which means the validation error was still falling when the rounds ran out, so this model needs more than 100 trees. A very small learning rate trades rounds for caution. - Code: in the second cell, change the depth loop to
for depth in (3,):. What happens to the best validation MSE compared with depths 1 and 2, and why?Show answer
It rises: about for depth 3, against to for depth 1 and for depth 2 (the lowest value in each depth’s three rows). The data have one input, so nothing needs interactions, and a deeper tree only lets each round fit more of the noise. With the best round is 1.
Next: P3.B6 turns to a different idea for classification, the support vector machine, which looks for the widest margin between two classes.