Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 3: Classical Machine LearningClassic Algorithms

Boosting

P3.B545 min●●○ IntermediateReviewed Dec 2, 2026

Why this matters for machine learning

Boosting turns many small, simple models into one accurate model by adding them one at a time, each aimed at the mistakes of the ones before. Gradient-boosted trees are among the most widely used methods for tables of data.

  • Random forests average many independent trees to cut variance. Boosting adds trees in sequence to cut bias. Knowing both tells you which one to reach for. (P3.B4: Bagging and random forests)
  • Gradient boosting is gradient descent in which the thing being adjusted is the model's list of predictions, and each step is a small tree. (P1.F3: Gradient descent)
  • The number of trees is chosen by watching error on a validation set and stopping when it stops improving. (P3.A4: Train, validation and test sets)
  • A learning rate smaller than 1 shrinks every tree before it is added. This is a form of regularization, in the same family as a penalty on the weights. (P3.A6: Regularization: L1 and L2)

Before this: Decision trees, The bias–variance trade-off, Gradient descent

After this lesson you can

  • Explain boosting as adding weak learners one at a time, each trained on what the current ensemble still gets wrong, and say how it differs from bagging
  • Carry out AdaBoost by hand on a small data set, computing the weighted error, the vote, the new weights and the final weighted vote
  • Derive that for squared error the negative gradient is the residual, so each new tree is fitted to the residuals, and say what replaces the residual for log loss
  • Choose the number of rounds, the learning rate and the tree depth, and recognise overfitting from training and validation curves

A decision stump is a tree with one question: “is xx 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 0.50.5 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.

  1. Fit a weak learner to the data as it stands.
  2. Find out where the ensemble so far is wrong, and make the next learner care about those places.
  3. 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 forestBoosting
How the trees are builtIndependently, each on a bootstrap resampleOne after another, each depends on the earlier ones
Typical treeDeep: low bias, high varianceShallow: high bias, low variance
What combining doesAveraging cuts varianceAdding cuts bias (mainly)
More treesUsually does not cause overfitting by itselfCan 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 y=+1y=+1 and y=−1y=-1. It keeps one weight wiw_i per training example. The weights are positive and add up to 11. They say how much each example counts when a weak learner is fitted and judged. The steps for round mm are these.

Step 1: fit. Fit a weak learner hmh_m (here a stump, whose output is +1+1 or −1-1) that makes the weighted error as small as it can:

εm=∑i: hm(xi)≠yiwi.\begin{aligned} \varepsilon_m=\sum_{i:\,h_m(x_i)\ne y_i} w_i . \end{aligned}

That is the total weight of the examples it gets wrong.

Step 2: vote. Give it the vote

αm=12ln⁡1−εmεm.\alpha_m=\tfrac12\ln\frac{1-\varepsilon_m}{\varepsilon_m}.

A stump with a small error gets a large vote.

Step 3: reweight. Update the weights and renormalise, so they add to 11 again:

wi←wi e−αmyihm(xi)Zm.w_i\leftarrow\frac{w_i\,e^{-\alpha_m y_i h_m(x_i)}}{Z_m}.

A correct example has yihm(xi)=+1y_ih_m(x_i)=+1, so its weight is multiplied by e−αme^{-\alpha_m} (smaller). A mistake has yihm(xi)=−1y_ih_m(x_i)=-1, so its weight is multiplied by eαme^{\alpha_m} (larger). ZmZ_m is the sum of the new weights, which does the renormalising.

After MM rounds the final classifier is the sign of the weighted vote:

H(x)=sign⁡(F(x)),F(x)=∑m=1Mαm hm(x).\begin{aligned} H(x)&=\operatorname{sign}\bigl(F(x)\bigr),\\ F(x)&=\sum_{m=1}^{M}\alpha_m\,h_m(x). \end{aligned}

A worked example with ten points

Ten points sit at x=1,2,…,10x=1,2,\dots,10. The labels are +1+1 everywhere except at x=6x=6 and x=10x=10, where they are −1-1. No single stump can get all ten right. A stump here is “predict one class for xx above a threshold tt and the other class below”, and the candidates are t=1.5,2.5,…,9.5t=1.5,2.5,\dots,9.5 with either sign. At the start each weight is 0.10.1.

Round 1. The best stump predicts +1+1 for x≤9.5x\le 9.5 and −1-1 for x=10x=10. It gets everything right except x=6x=6, so ε1=0.1\varepsilon_1=0.1. Its vote is α1=12ln⁡0.90.1=12ln⁡9=1.0986\alpha_1=\tfrac12\ln\frac{0.9}{0.1}=\tfrac12\ln 9=1.0986, and eα1=3e^{\alpha_1}=3. The update multiplies the weight of x=6x=6 by 33 and every other weight by 13\tfrac13:

  • the mistake: 0.1⋅3=0.30.1\cdot 3=0.3,
  • each of the nine correct points: 0.1/3=0.03330.1/3=0.0333,
  • the sum is Z1=0.3+9⋅0.0333=0.6Z_1=0.3+9\cdot0.0333=0.6, so the new weights are 0.50.5 at x=6x=6 and 1/18=0.05561/18=0.0556 elsewhere.

The point x=6x=6 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 +1+1 for x≤5.5x\le5.5 and −1-1 above. It is wrong at x=7,8,9x=7,8,9, so ε2=3⋅118=16=0.1667\varepsilon_2=3\cdot\frac1{18}=\frac16=0.1667 and α2=12ln⁡5=0.8047\alpha_2=\tfrac12\ln5=0.8047, with eα2=5=2.236e^{\alpha_2}=\sqrt5=2.236. It gets x=6x=6 right, so that weight shrinks. New weights: 0.30.3 at x=6x=6, 0.16670.1667 at each of x=7,8,9x=7,8,9, and 0.03330.0333 at the other six points. The mistakes of round 2 hold exactly half the weight again.

Round 3. The best stump now predicts −1-1 for x≤6.5x\le 6.5 and +1+1 above. It is wrong at x=1,…,5x=1,\dots,5 and x=10x=10: ε3=5⋅0.0333+0.0333=0.2\varepsilon_3=5\cdot0.0333+0.0333=0.2, so α3=12ln⁡4=0.6931\alpha_3=\tfrac12\ln4=0.6931. The weights after the update are 0.08330.0833 at x=1,…,5x=1,\dots,5 and at x=10x=10, 0.18750.1875 at x=6x=6 and 0.10420.1042 at x=7,8,9x=7,8,9.

The vote. Add α1h1+α2h2+α3h3\alpha_1h_1+\alpha_2h_2+\alpha_3h_3 at each point. Here h1,h2,h3h_1,h_2,h_3 are the three stumps, in the order (h1,h2,h3)(h_1,h_2,h_3):

  • x=1x=1 to 55: (+,+,−)(+,+,-) gives 1.0986+0.8047−0.6931=1.211.0986+0.8047-0.6931=1.21, class +1+1. Correct.
  • x=6x=6: (+,−,−)(+,-,-) gives 1.0986−0.8047−0.6931=−0.401.0986-0.8047-0.6931=-0.40, class −1-1. Correct, although the first stump was wrong here.
  • x=7x=7 to 99: (+,−,+)(+,-,+) gives 1.0986−0.8047+0.6931=0.991.0986-0.8047+0.6931=0.99, class +1+1. Correct.
  • x=10x=10: (−,−,+)(-,-,+) gives −1.0986−0.8047+0.6931=−1.21-1.0986-0.8047+0.6931=-1.21, class −1-1. 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.

Try it: AdaBoost from scratch on the ten points

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 x=3x=3, 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. α\alpha grows as ε\varepsilon shrinks: ε=0.1\varepsilon=0.1 gives 1.101.10, ε=0.2\varepsilon=0.2 gives 0.690.69, ε=0.4\varepsilon=0.4 gives 0.200.20.
  • A stump no better than guessing gets no vote. At ε=0.5\varepsilon=0.5 the vote is 00. A stump with ε>0.5\varepsilon>0.5 gets a negative vote, which means “do the opposite”. In practice the learner is picked to have ε<0.5\varepsilon<0.5, or the loop stops. At ε=0\varepsilon=0 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 x=6x=6 went from 0.10.1 to 0.50.5 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 (1−ε)e−α/Z(1-\varepsilon)e^{-\alpha}/Z and on mistakes εeα/Z\varepsilon e^{\alpha}/Z, where Z=(1−ε)e−α+εeαZ=(1-\varepsilon)e^{-\alpha}+\varepsilon e^{\alpha}. The choice α=12ln⁡1−εε\alpha=\frac12\ln\frac{1-\varepsilon}{\varepsilon} is the one that makes ZZ as small as possible: setting the derivative −(1−ε)e−α+εeα-(1-\varepsilon)e^{-\alpha}+\varepsilon e^{\alpha} to zero gives e2α=1−εεe^{2\alpha}=\frac{1-\varepsilon}{\varepsilon}. At that value (1−ε)e−α=εeα=ε(1−ε)(1-\varepsilon)e^{-\alpha}=\varepsilon e^{\alpha}=\sqrt{\varepsilon(1-\varepsilon)}, so correct points and mistakes each hold exactly half, and Z=2ε(1−ε)Z=2\sqrt{\varepsilon(1-\varepsilon)}.

Training error. The mistake indicator is at most an exponential: 1[H(xi)≠yi]≤e−yiF(xi)\mathbb{1}[H(x_i)\ne y_i]\le e^{-y_iF(x_i)} with F=∑mαmhmF=\sum_m\alpha_mh_m. Unrolling the weight updates shows that the average of e−yiF(xi)e^{-y_iF(x_i)} over the training set equals ∏mZm\prod_m Z_m. So the training error of the ensemble is at most ∏m2εm(1−εm)\prod_m 2\sqrt{\varepsilon_m(1-\varepsilon_m)}. In the example this product is 0.6⋅0.7454⋅0.8=0.3580.6\cdot0.7454\cdot0.8=0.358, while the real training error is 00. Writing εm=12−γm\varepsilon_m=\frac12-\gamma_m gives the bound exp⁡(−2∑mγm2)\exp(-2\sum_m\gamma_m^2), so if every stump beats chance by at least γ>0\gamma>0, 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 e−yF(x)e^{-yF(x)} 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 F(x)F(x). Start with a constant. The residual of an example is what is still missing, ri=yi−F(xi)r_i=y_i-F(x_i): 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 x=1,…,6x=1,\dots,6 and y=(2,4,3,9,8,10)y=(2,4,3,9,8,10). Use stumps, and shrink every tree by ν=0.5\nu=0.5 before adding it (more on ν\nu below).

Start. The best constant for squared error is the mean, F0=6F_0=6. The residuals are (−4,−2,−3,3,2,4)(-4,-2,-3,3,2,4). The mean squared error (MSE) is 16+4+9+9+4+166=9.667\frac{16+4+9+9+4+16}{6}=9.667.

Round 1. Fit a stump to the residuals. The best cut is between x=3x=3 and x=4x=4. Its leaves hold the average residual on each side, −3-3 on the left and +3+3 on the right. Add half of it: F1=6+0.5⋅(−3)=4.5F_1=6+0.5\cdot(-3)=4.5 for x≤3x\le3 and 6+0.5⋅3=7.56+0.5\cdot3=7.5 for x>3x>3. The new residuals are (−2.5,−0.5,−1.5,1.5,0.5,2.5)(-2.5,-0.5,-1.5,1.5,0.5,2.5) and the MSE is 17.56=2.917\frac{17.5}{6}=2.917.

Round 2. Fit a stump to these. The best cut is the same, with leaf values −1.5-1.5 and +1.5+1.5. Now F2=3.75F_2=3.75 on the left and 8.258.25 on the right. The residuals are (−1.75,0.25,−0.75,0.75,−0.25,1.75)(-1.75,0.25,-0.75,0.75,-0.25,1.75) and the MSE is 7.3756=1.229\frac{7.375}{6}=1.229.

Round 3. The leftover is now mostly at the two ends. The best cut moves to between x=1x=1 and x=2x=2, with leaf values −1.75-1.75 and +0.35+0.35. (Cutting between x=5x=5 and x=6x=6 ties exactly, by symmetry; we take the left cut, as the code does.) Then F3F_3 is 2.8752.875 at x=1x=1, 3.9253.925 at x=2x=2 and x=3x=3, and 8.4258.425 at x=4,5,6x=4,5,6. The MSE is 0.7700.770.

The MSE went 9.667→2.917→1.229→0.7709.667\to2.917\to1.229\to0.770. Each tree is a crude step function, but each one is aimed at what is left. With ν=1\nu=1 the first stump would jump straight to the leaf averages, F1=(3,3,3,9,9,9)F_1=(3,3,3,9,9,9), and the MSE would be 0.6670.667 after one round. With ν=0.5\nu=0.5 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 FF is L=12(y−F)2L=\tfrac12(y-F)^2. Its derivative with respect to the prediction is ∂L∂F=−(y−F),\frac{\partial L}{\partial F}=-(y-F), so the negative gradient is the residual y−Fy-F. That is why fitting the residuals is the same as following the negative gradient.

Gradient descent (P1.F3) updates parameters by θ←θ−η∇L\boldsymbol\theta\leftarrow\boldsymbol\theta-\eta\nabla L. Here the quantities being adjusted are not weights but the model’s predictions F(x1),…,F(xn)F(x_1),\dots,F(x_n) on the training points. The loss L=∑iL(yi,F(xi))\mathcal L=\sum_iL(y_i,F(x_i)) has a gradient with one entry per example. One could just step against it, F(xi)←F(xi)+νriF(x_i)\leftarrow F(x_i)+\nu r_i, but that only changes the predictions at the training points and says nothing about a new xx. So instead a tree is fitted to the entries rir_i, and the tree is added. The tree is a least-squares approximation of those gradient values, and unlike them it is defined for every xx. 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 L(y,F)L(y,F):

  1. Start with the constant F0F_0 that has the lowest total loss (the mean, for squared error).
  2. For m=1,…,Mm=1,\dots,M: compute the pseudo-residual ri=−∂L(yi,F)∂F∣F=Fm−1(xi)r_i=-\dfrac{\partial L(y_i,F)}{\partial F}\Big|_{F=F_{m-1}(x_i)} for every training example. Fit a small tree hmh_m to the pairs (xi,ri)(x_i,r_i). Set Fm=Fm−1+ν hmF_m=F_{m-1}+\nu\,h_m.
  3. Predict with FMF_M.

“Pseudo-residual” is the name for the negative gradient when the loss is not squared error, because then it is no longer simply y−Fy-F.

Log loss for classification. For a label y∈{0,1}y\in\{0,1\}, let FF be the log-odds and p=1/(1+e−F)p=1/(1+e^{-F}) the predicted probability, with L=−[yln⁡p+(1−y)ln⁡(1−p)]L=-[y\ln p+(1-y)\ln(1-p)]. A short calculation gives −∂L/∂F=y−p-\partial L/\partial F=y-p: the label minus the predicted probability. The recipe stays the same, only the target of each tree changes. For three examples with F=(−1,0,2)F=(-1,0,2) and y=(1,0,1)y=(1,0,1) the pseudo-residuals are (0.731,−0.5,0.119)(0.731,-0.5,0.119), which is what a numerical derivative also gives. (This is the p−yp-y of P3.A7 with its sign flipped, because a pseudo-residual is the negative gradient.) The final probability is the sigmoid of FMF_M. For absolute error the pseudo-residual is only the sign of y−Fy-F. 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: y=sin⁡(1.4x)+0.25xy=\sin(1.4x)+0.25x plus random noise with standard deviation 0.40.4, with 3030 training points (dots) and 3030 validation points (hollow squares). Press Add a tree to take one round at a time.

0123456−10123xy
training point validation point ensemble after round m residual
0123456−202xresidual
residual of a training point the next tree, fitted to the residuals

Round 0: the model predicts the mean of the training targets everywhere. The orange segments are the residuals. The pink steps in the middle plot are the tree that round 1 would add.

Tree depth:
round m = 0
training MSE = 0.568
validation MSE = 0.919
lowest validation MSE: round 11 (0.295)

Mean squared error after each round

00.250.50.7510255075100round
training MSE validation MSE best validation round

The data are made up: y = sin(1.4x) + 0.25x plus random noise with standard deviation 0.4, with 30 training and 30 validation points. The model starts at the training mean and adds least-squares trees, each fitted to the current residuals and scaled by ν. Error values above 1 are drawn at the top edge of the error chart.

Gradient boosting for squared error. Top: training points, the ensemble F after m rounds (blue steps), and the residuals y − F as orange segments. Middle: the same residuals as orange dots and, in pink, the small tree that the next round would fit to them. Bottom: training and validation MSE after every round; the black line is the current round and the dashed green line marks the round with the lowest validation MSE. Controls: add a tree, play, reset, jump to the best validation round, the round slider, the learning rate ν and the tree depth.

Things to try.

  • Step through the first rounds at the defaults (depth 2, ν=0.3\nu=0.3). Round 0 is a flat line at the mean, 0.7520.752, with training MSE 0.5680.568. 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 ν=0.3\nu=0.3 times the pink step, and the segments shorten.
  • Watch the two error curves. Training MSE falls all the way: 0.3890.389 after one round, 0.0700.070 after eleven, 0.00010.0001 after a hundred. Validation MSE falls to 0.2950.295 at round 11 (the dashed green line) and then rises to 0.4140.414 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 0.00000.0000 and the validation MSE is 0.4200.420.
  • 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 0.3470.347, 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 ν=0.05\nu=0.05 the lowest validation error is at round 100, the end of the slider, so the curve has not finished falling. A small ν\nu 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, ν\nu (also called shrinkage). Every tree is multiplied by ν\nu between 00 and 11 before it is added. A small ν\nu 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 η\eta 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:

ν\nubest roundvalidation MSE therevalidation MSE at round 100
1.050.3030.420
0.3110.2950.414
0.1460.3000.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 ν\nu gave better results than ν=1\nu=1 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, MM. 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-dd tree can model interactions among up to dd 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 0.2920.292 for depth 1 (ν=0.3\nu=0.3, round 55), 0.2950.295 for depth 2 and 0.3340.334 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.

Try it: gradient boosting from scratch, with the widget's data

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 33 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, GradientBoostingRegressor and GradientBoostingClassifier, which follow this lesson closely, and HistGradientBoostingClassifier and HistGradientBoostingRegressor, 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 ln⁡1−εε\ln\frac{1-\varepsilon}{\varepsilon}, twice the α\alpha 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 (25%25\% 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 0.9990.999 and test accuracy 0.8820.882 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 yi∈{−1,+1}y_i\in\{-1,+1\}, weights wiw_i summing to 11:

εm=∑i: hm(xi)≠yiwi,αm=12ln⁡1−εmεm,wi←wi e−αmyihm(xi)Zm,H(x)=sign⁡∑mαmhm(x).\begin{aligned} \varepsilon_m&=\sum_{i:\,h_m(x_i)\ne y_i}w_i,\\ \alpha_m&=\tfrac12\ln\frac{1-\varepsilon_m}{\varepsilon_m},\\ w_i&\leftarrow\frac{w_i\,e^{-\alpha_my_ih_m(x_i)}}{Z_m},\\ H(x)&=\operatorname{sign}\sum_m\alpha_mh_m(x). \end{aligned}

Gradient boosting, with loss LL and learning rate ν\nu:

F0=arg⁡min⁡c∑iL(yi,c),rim=−∂L(yi,F)∂F∣F=Fm−1(xi),Fm=Fm−1+ν hm.\begin{aligned} F_0&=\arg\min_c\sum_iL(y_i,c),\\ r_{im}&=-\frac{\partial L(y_i,F)}{\partial F}\Big|_{F=F_{m-1}(x_i)},\\ F_m&=F_{m-1}+\nu\,h_m. \end{aligned}

Here hmh_m is a tree fitted to the pairs (xi,rim)(x_i,r_{im}). Squared error 12(y−F)2\tfrac12(y-F)^2 gives r=y−Fr=y-F. Log loss with FF the log-odds gives r=y−pr=y-p. Exponential loss e−yFe^{-yF} gives r=ye−yFr=ye^{-yF}. AdaBoost is a greedy, stage-wise minimisation of this loss, with a weighted classifier as each step and an exact line search for α\alpha.

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 space

Check your understanding

  1. In AdaBoost, a stump has weighted error ε=0.2\varepsilon=0.2. What is its vote α=12ln⁡1−εε\alpha=\tfrac12\ln\frac{1-\varepsilon}{\varepsilon}?

  2. After AdaBoost has updated and renormalised the weights following a round, how much total weight do that stump's mistakes hold (when 0<ε<0.50<\varepsilon<0.5)?

  3. In gradient boosting with squared error, what is each new tree fitted to?

  4. You lower the learning rate ν\nu from 11 to 0.10.1 and keep the tree depth. What is the typical effect?

  5. Which statement describes boosting rather than bagging?

Exercises

  1. Four examples start with weights 0.250.25 each. A stump gets exactly one of them wrong. Find ε\varepsilon, α\alpha and the new weights after the update.
    Show answerε=0.25\varepsilon=0.25, α=12ln⁡3=0.549\alpha=\tfrac12\ln3=0.549. Before renormalising, the mistake has 0.25 eα=0.4330.25\,e^{\alpha}=0.433 and each correct example 0.25 e−α=0.1440.25\,e^{-\alpha}=0.144; the sum is 0.8660.866. After renormalising, the mistake has weight 0.50.5 and each of the three correct examples 0.16670.1667. Again the mistake holds half of the total weight.
  2. What is α\alpha when ε=0.5\varepsilon=0.5? What is it when ε=0.8\varepsilon=0.8, and what does the sign mean?
    Show answerε=0.5\varepsilon=0.5 gives 12ln⁡1=0\tfrac12\ln1=0: the stump gets no vote, as it is no better than a coin flip. ε=0.8\varepsilon=0.8 gives 12ln⁡0.25=−0.693\tfrac12\ln0.25=-0.693: the stump is wrong more often than not, so its vote is reversed, and the reversed stump has ε=0.2\varepsilon=0.2.
  3. Let x=1,2,3,4x=1,2,3,4 and y=(1,3,8,10)y=(1,3,8,10). Start from the mean and add one stump fitted to the residuals. Find the MSE after the round for ν=1\nu=1 and for ν=0.5\nu=0.5.
    Show answerF0=5.5F_0=5.5 and the residuals are (−4.5,−2.5,2.5,4.5)(-4.5,-2.5,2.5,4.5). The best stump cuts between x=2x=2 and x=3x=3, with leaf values −3.5-3.5 and +3.5+3.5. With ν=1\nu=1: F1=(2,2,9,9)F_1=(2,2,9,9), residuals (−1,1,−1,1)(-1,1,-1,1), MSE =1=1. With ν=0.5\nu=0.5: F1=(3.75,3.75,7.25,7.25)F_1=(3.75,3.75,7.25,7.25), residuals (−2.75,−0.75,0.75,2.75)(-2.75,-0.75,0.75,2.75), MSE =7.5625+0.5625+0.5625+7.56254=4.0625=\frac{7.5625+0.5625+0.5625+7.5625}{4}=4.0625. The smaller step leaves more error for later rounds to remove.
  4. For log loss, find the pseudo-residual y−py-p for y=1,F=0y=1,F=0 and for y=0,F=2y=0,F=2.
    Show answerFor F=0F=0, p=0.5p=0.5, so the residual is 1−0.5=0.51-0.5=0.5. For F=2F=2, p=1/(1+e−2)=0.881p=1/(1+e^{-2})=0.881, so the residual is 0−0.881=−0.8810-0.881=-0.881. 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.
  5. In the widget, set depth 1 and ν=0.05\nu=0.05 and press Jump to the best validation round. Where does it land, and what does that say?
    Show answerIt lands at round 100, the end of the slider, with validation MSE about 0.3550.355. 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.
  6. 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 answerIt rises: about 0.330.33 for depth 3, against 0.280.28 to 0.290.29 for depth 1 and 0.300.30 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 ν=1\nu=1 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.

Key takeaways

  • Boosting builds a strong model from many weak learners (models only a little better than guessing) added one after another, each trained to fix what the ensemble so far gets wrong. Bagging (P3.B4) averages independent models to cut variance; boosting adds dependent models to cut bias.
  • AdaBoost keeps a weight on every example. Round m fits a stump to the weighted data, measures its weighted error ε, gives it the vote α = ½ ln((1−ε)/ε), multiplies the weights of the mistakes by e^α and of the correct ones by e^(−α), and renormalises. After the update the mistakes carry exactly half of the total weight. The final model is the sign of the weighted vote.
  • Gradient boosting starts from a constant, then repeats: compute the negative gradient of the loss with respect to each prediction, fit a small tree to it, and add ν times the tree. For squared error the negative gradient is the residual y − F. For log loss with F as the log-odds it is y − p.
  • In the lesson's made-up data (30 training points, noise standard deviation 0.4), depth-2 trees with ν = 0.3 reach their lowest validation MSE, 0.295, at round 11. By round 100 training MSE is 0.0001 and validation MSE has risen to 0.414. Boosting can overfit, while a forest usually does not overfit just because it has more trees.
  • The defences are a small learning rate ν, early stopping on a validation set, shallow trees and subsampling the rows. XGBoost, LightGBM and CatBoost are fast, regularized implementations of gradient-boosted trees, and such trees are often reported to be a strong default for tabular data.
Found a mistake? Tell us