Simple Algorithm
Machine Learning · Descent · 24 min

Gradient Boosting

Fitting residuals step by step: the engine behind XGBoost.

Fit a small tree. Look at what it gets wrong. Fit another small tree to those errors, add a fraction of it, and repeat a few hundred times. Friedman showed that this loop is gradient descent in a space of functions, so it can minimize almost any differentiable loss, and the result, gradient-boosted trees, is still the method to beat on most tabular data.

What you’ll learn

  • Derive gradient boosting as steepest descent in function space, and show that for squared loss the negative gradient is the residual.
  • Write the algorithm with per-leaf optimal values for squared, absolute, Huber, quantile and log loss.
  • Explain how the learning rate, the number of trees, the tree size and subsampling interact, and tune them with early stopping.
  • Recognize what gradient-boosted trees do well and badly: interactions, monotone transformations, missing values, extrapolation.

Fitting the residuals

Start with regression and the squared loss. The best constant prediction is the mean, F0=yˉF_0=\bar y. Its residuals ri=yi−F0r_i=y_i-F_0 say what is still unexplained, so fit a small regression tree h1h_1 to the pairs (xi,ri)(\mathbf x_i,r_i) and add a fraction of it:

F1(x)=F0+ν h1(x),0<ν≤1.F_1(\mathbf x)=F_0+\nu\,h_1(\mathbf x),\qquad0<\nu\le1.

Then compute the residuals of F1F_1, fit h2h_2 to them, add νh2\nu h_2, and so on. After MM rounds the model is FM=F0+ν∑m=1MhmF_M=F_0+\nu\sum_{m=1}^Mh_m: a sum of small trees, each correcting what the previous ones left over. The fraction ν\nu is the learning rate, also called shrinkage.

Predict before you look

Three training points have targets 1, 2 and 6. Boosting starts from their mean and fits a stump that puts the first two points in one leaf and the third in another, each leaf predicting its mean residual. With learning rate ν=0.5\nu=0.5, what is the new prediction for the third point?

Show the answer

4.5

F0=3F_0=3, and the residuals are −2,−1,3-2,-1,3. The leaves predict −1.5-1.5 and 33, so F1=3+0.5⋅3=4.5F_1=3+0.5\cdot3=4.5 for the third point and 3−0.75=2.253-0.75=2.25 for the first two. The new residuals, −1.25,−0.25,1.5-1.25,-0.25,1.5, are smaller but not zero: each round removes only a fraction ν\nu of what the tree captures.

Boosting is gradient descent in function space

Why residuals? Take any differentiable loss ℓ(y,F)\ell(y,F). The training loss ∑iℓ(yi,F(xi))\sum_i\ell\big(y_i,F(\mathbf x_i)\big) depends on FF only through its nn values F(x1),…,F(xn)F(\mathbf x_1),\dots,F(\mathbf x_n). Treat those values as parameters and take a gradient-descent step: move each F(xi)F(\mathbf x_i) along the negative gradient

ri=−∂ℓ(yi,F)∂F∣F=Fm−1(xi).r_i=-\frac{\partial\ell(y_i,F)}{\partial F}\Big|_{F=F_{m-1}(\mathbf x_i)}.

For squared loss ℓ=12(y−F)2\ell=\tfrac12(y-F)^2 this is exactly the residual yi−Fm−1(xi)y_i-F_{m-1}(\mathbf x_i). But a step defined only at the training points says nothing about new inputs. So fit a regression tree to the pseudo-residuals rir_i: the least-squares fit is the small tree closest to the descent direction, and it is defined everywhere. Then take a step along it. This is gradient boosting (Friedman, 2001):

text
GRADIENT_BOOST(data (x_i, y_i), loss l, rounds M, learning rate nu, leaves J)
  F_0(x) = argmin_c  sum_i l(y_i, c)                       # best constant
  for m = 1..M:
      r_i = -dl(y_i, F)/dF  at F = F_{m-1}(x_i)            # pseudo-residuals
      fit a regression tree with J leaves R_1..R_J to (x_i, r_i) by least squares
      for each leaf j:                                      # per-leaf line search
          gamma_j = argmin_g  sum over x_i in R_j of l(y_i, F_{m-1}(x_i) + g)
      F_m(x) = F_{m-1}(x) + nu * gamma_j    for x in leaf R_j
  return F_M

Friedman's "TreeBoost". The tree's structure comes from a least-squares fit to the pseudo-residuals; its leaf values are then re-optimized for the actual loss, one line search per leaf, because the tree's regions are disjoint.

DerivationPseudo-residuals for squared loss and log loss
  1. ℓ=12(y−F)2⟹ri=yi−F(xi),γj=mean⁡{ri:xi∈Rj}\ell=\tfrac12(y-F)^2\quad\Longrightarrow\quad r_i=y_i-F(\mathbf x_i),\qquad\gamma_j=\operatorname{mean}\{r_i:\mathbf x_i\in R_j\}

    Squared loss: the negative gradient is the residual, and the best value for a leaf is the mean residual of its points.

  2. ℓ=−yln⁡p−(1−y)ln⁡(1−p)=ln⁡(1+eF)−yF⟹ri=yi−pi\ell=-y\ln p-(1-y)\ln(1-p)=\ln\big(1+e^F\big)-yF\quad\Longrightarrow\quad r_i=y_i-p_i

    Log loss for labels y∈{0,1}y\in\{0,1\}, with FF the log-odds and p=σ(F)=1/(1+e−F)p=\sigma(F)=1/(1+e^{-F}). Writing the loss in terms of FF makes the derivative immediate:

  3. γj≈∑xi∈Rj(yi−pi)∑xi∈Rjpi(1−pi)\gamma_j\approx\frac{\sum_{\mathbf x_i\in R_j}(y_i-p_i)}{\sum_{\mathbf x_i\in R_j}p_i(1-p_i)}

    The leaf value has no closed form for log loss. One Newton step from g=0g=0 uses the second derivative ∂2ℓ/∂F2=p(1−p)\partial^2\ell/\partial F^2=p(1-p):

Loss ℓ(y,F)\ell(y,F)Pseudo-residual rir_iLeaf value γj\gamma_j
Squared, 12(y−F)2\tfrac12(y-F)^2y−Fy-F, the residualmean of the residuals in the leaf
Absolute, ∣y−F∣\abs{y-F}sign⁡(y−F)\sign(y-F)median of the residuals in the leaf
Huber, threshold δ\deltay−Fy-F, clipped to [−δ,δ][-\delta,\delta]median r~j\tilde r_j plus the mean of the clipped deviations ri−r~jr_i-\tilde r_j
Quantile (pinball) at level τ\tauτ\tau if y>Fy>F, else τ−1\tau-1the τ\tau-quantile of the residuals in the leaf
Log loss, y∈{0,1}y\in\{0,1\}y−py-pone Newton step: ∑(yi−pi)/∑pi(1−pi)\sum(y_i-p_i)/\sum p_i(1-p_i)
Only the pseudo-residuals and the leaf values depend on the loss; the trees are always grown by least squares. Absolute, Huber and quantile losses cap each point's pull, so a single outlier cannot dominate a round. Multiclass log loss boosts one tree per class per round on the softmax probabilities.
Check your understanding

You boost with the absolute loss. One training target is off from the current prediction by 1,000, the others by about 1. How much does the outlier pull on the next tree?

  1. A thousand times as much as a typical point
  2. Nothing: absolute loss ignores points with large residuals
  3. About a million times as much, since the loss is squared internally
  4. The same as any other point: its pseudo-residual is ±1\pm1
Show the answer

D. The same as any other point: its pseudo-residual is ±1\pm1

The negative gradient of ∣y−F∣\abs{y-F} is sign⁡(y−F)\sign(y-F), so every point's pseudo-residual is +1+1 or −1-1 however far off it is, and the leaf values are medians, which resist outliers. With squared loss, the same point would contribute a residual of 1,000 and drag its leaf's mean toward itself.

How many trees, and how big a step

With least-squares trees and squared loss, the training error never rises from one round to the next, so it is useless for deciding when to stop. The validation error traces the familiar U: it falls while the trees capture structure and rises once they start fitting noise. The number of trees MM is therefore the main regularization parameter, chosen by early stopping: watch the loss on a validation set (or by cross-validation) and keep the round where it was lowest.

The learning rate ν\nu interacts with MM. Smaller steps need proportionally more trees, and empirically smaller values of ν\nu give equal or better test error (Friedman, 2001). The standard recipe from The Elements of Statistical Learning is to fix ν\nu small, below 0.1, and choose MM by early stopping.

Tree size, interactions and subsampling

The size of each tree controls which functions the sum can build. A tree with JJ leaves has J−1J-1 splits, and the prediction along any root-to-leaf path depends jointly on the features split on along it, so one tree can express an interaction among at most J−1J-1 features. Stumps (J=2J=2) produce an additive model F(x)=∑jgj(xj)F(\mathbf x)=\sum_jg_j(x_j) with no interactions at all. The Elements of Statistical Learning reports that 4≤J≤84\le J\le8 works well in boosting, with results fairly insensitive to the exact choice in that range.

Predict before you look

A boosted model uses trees with J=6J=6 leaves. At most how many different features can interact within a single tree?

Show the answer

5 features

Six leaves means five splits. If they all lie on one root-to-leaf path, a chain-shaped tree, that leaf's value depends on five features jointly. Interactions among more features can only come from sums of trees, which are additive across trees.

Think first Inputs x1,x2x_1,x_2 are independent and uniform on [−1,1][-1,1], and the target is y=x1x2y=x_1x_2. Can boosting stumps for many rounds learn it?

No. A sum of stumps is g1(x1)+g2(x2)g_1(x_1)+g_2(x_2), and the best additive approximation of x1x2x_1x_2 is the zero function: E[x1x2∣x1]=x1E[x2]=0\E[x_1x_2\mid x_1]=x_1\E[x_2]=0, and likewise given x2x_2, so x1x2x_1x_2 is orthogonal to every additive function. Stumps explain none of its variance. Trees of depth 2, which split on x1x_1 and then on x2x_2, capture it easily. The XOR problem that defeats boosted stumps in AdaBoost & the Exponential Loss is the same phenomenon.

Two kinds of randomness help. Stochastic gradient boosting (Friedman, 2002) fits each tree on a random fraction η\eta of the training rows, drawn without replacement, which makes training faster and often more accurate, the extra randomness acting like the averaging in bagging; η=12\eta=\tfrac12 is a typical value, smaller for large datasets. Column subsampling, borrowed from random forests, lets each tree (or each split) see only a random subset of the features; Chen & Guestrin (2016) report users' experience that it prevents overfitting even more than row subsampling. The remaining regularizers act inside each tree: a minimum number of examples per leaf, and an L2L_2 penalty on the leaf values, the λ\lambda of XGBoost's objective (XGBoost, LightGBM & CatBoost).

Gradient boosting in practice

python
from sklearn.ensemble import HistGradientBoostingRegressor

model = HistGradientBoostingRegressor(
    loss="squared_error",     # or "absolute_error", "quantile" (with quantile=0.9), ...
    learning_rate=0.05,       # shrinkage nu
    max_iter=2000,            # upper bound on the number of trees M
    max_leaf_nodes=16,        # tree size J
    min_samples_leaf=20,
    l2_regularization=1.0,    # L2 penalty on the leaf values
    early_stopping=True,      # hold out validation_fraction of the training data
    validation_fraction=0.1,
    n_iter_no_change=50,      # stop after 50 rounds without improvement
)
model.fit(X_train, y_train)
print(model.n_iter_)          # the number of trees actually kept

scikit-learn's histogram-based implementation, modeled on LightGBM, buckets each feature into at most 255 bins before training. The early-stopping split is carved out of the training data, so the test set stays untouched.

HyperparameterWhat it controlsCommon starting point
Number of trees MMhow far the descent goes: the main regularizerearly stopping on validation data
Learning rate ν\nustep size; smaller needs more trees0.01–0.1
Tree size (leaves JJ or depth)interaction order and the bias of each step4–64 leaves (depth 2–6)
Row subsample η\etarandomness and speed0.5–1
Column subsampledecorrelates trees, speeds up wide data0.5–1
Minimum leaf size, L2L_2 leaf penaltynoise in individual leaf valuestens of examples; λ\lambda around 1
Losswhat "error" means: mean, median, quantile, probabilitychosen by the task, not tuned
Typical ranges, not rules. Tune JJ and the subsampling rates by cross-validation at a fixed small ν\nu, letting early stopping set MM.

Why trees? Splits depend only on the order of a feature's values, so any monotone transformation of a feature (logarithms, ranks, unit changes) leaves the model unchanged, and no scaling is needed. Numeric and categorical features mix freely, implementations route missing values to a learned side of each split, and interactions are found automatically up to order J−1J-1.

The weaknesses follow from the same piecewise-constant structure. A tree ensemble is flat beyond the range of its training data, so it cannot extrapolate a trend. Its predictions are step functions, which are poor at smooth relationships in few dimensions and give no useful input gradients. And on data with strong structure across many raw inputs, such as images, audio or text, learned representations win (Trees vs Deep Learning on Tabular Data).

Key takeaways

  • Gradient boosting fits each new tree, by least squares, to the pseudo-residuals −∂ℓ/∂F-\partial\ell/\partial F and adds it with a small learning rate ν\nu: gradient descent on the training loss in function space.
  • For squared loss the pseudo-residuals are the residuals; for log loss with y∈{0,1}y\in\{0,1\} they are y−py-p. Leaf values are re-optimized per leaf: means, medians, quantiles or a Newton step ∑(y−p)/∑p(1−p)\sum(y-p)/\sum p(1-p).
  • The number of trees is the main regularization parameter, chosen by early stopping on validation data; a smaller ν\nu needs proportionally more trees and usually generalizes at least as well.
  • A tree with JJ leaves expresses interactions of order up to J−1J-1; stumps give an additive model. Row subsampling (stochastic gradient boosting) speeds training and adds regularization.
  • Boosted trees ignore monotone rescaling of features and handle mixed types and interactions, but they are piecewise constant and cannot extrapolate beyond the training range.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

In gradient boosting for binary classification with log loss, labels y∈{0,1}y\in\{0,1\} and FF the log-odds, what are the pseudo-residuals?

  1. yi−F(xi)y_i-F(\mathbf x_i), the gap between label and score
  2. yi−piy_i-p_i, the gap between label and predicted probability
  3. sign⁡(yi−pi)\sign(y_i-p_i)
  4. pi(1−pi)p_i(1-p_i)
Show the answer

B. yi−piy_i-p_i, the gap between label and predicted probability

Write the loss as ln⁡(1+eF)−yF\ln(1+e^F)-yF; its derivative in FF is σ(F)−y=p−y\sigma(F)-y=p-y, so the negative gradient is y−py-p. The second derivative, p(1−p)p(1-p), enters the Newton step for the leaf values.

Question 2

You lower the learning rate from ν=0.1\nu=0.1 to ν=0.01\nu=0.01 and keep everything else fixed. What should you expect?

  1. The same model after the same number of trees
  2. Roughly ten times as many trees to reach the best validation error, which is usually as good or slightly better
  3. Ten times fewer trees, since each one is more accurate
  4. Guaranteed overfitting, because the trees are fitted more precisely
Show the answer

B. Roughly ten times as many trees to reach the best validation error, which is usually as good or slightly better

Each tree's contribution is scaled by ν\nu, so progress per round slows roughly in proportion. Empirically, smaller ν\nu with correspondingly more trees gives equal or better test error (Friedman, 2001; Hastie, Tibshirani & Friedman, 2009). In this lesson's simulation with depth-3 trees, ν=1\nu=1 bottoms out clearly worse (0.135), while every ν≤0.3\nu\le0.3 reaches about the same minimum, near 0.11, only later. The recipe: a small ν\nu, and early stopping to choose the number of trees.

Question 3

A treatment helps only patients who are both over 65 and diabetic. You boost stumps (one split per tree) for thousands of rounds. Why may the model miss the effect?

  1. A sum of stumps is an additive model ∑jgj(xj)\sum_jg_j(x_j), which cannot represent an interaction between two features
  2. Stumps cannot split on binary features
  3. Boosting needs a learning rate of 1 to capture interactions
  4. It cannot miss it: enough stumps can approximate any function of the features
Show the answer

A. A sum of stumps is an additive model ∑jgj(xj)\sum_jg_j(x_j), which cannot represent an interaction between two features

Each stump depends on one feature, so the sum depends on the features additively. "Old and diabetic" is a product-like interaction; trees with JJ leaves can express interactions of order up to J−1J-1, so even 3- or 4-leaf trees can capture it.

Question 4

A gradient-boosted model predicts house prices from floor area. The largest house in the training data has 400 m². What does it predict for a 900 m² house, all else equal?

  1. A price extrapolated along the trend of the largest houses
  2. An error, because the input is out of range
  3. Roughly the same as for the largest training houses: tree ensembles are constant beyond the training range
  4. A price of zero
Show the answer

C. Roughly the same as for the largest training houses: tree ensembles are constant beyond the training range

Every tree assigns the 900 m² house to the same leaf as the largest training houses, so the sum of trees cannot keep rising. Trees interpolate within the data and flatten outside it; for trends, add a linear term or model the target relative to a baseline.

Go deeper

Further reading

  • J. H. Friedman, "Greedy function approximation: a gradient boosting machine," Annals of Statistics 29(5), 1189–1232 (2001).
  • J. H. Friedman, "Stochastic gradient boosting," Computational Statistics & Data Analysis 38(4), 367–378 (2002).
  • T. Hastie, R. Tibshirani & J. Friedman, The Elements of Statistical Learning, 2nd ed. (Springer, 2009), chapter 10.
  • T. Chen & C. Guestrin, "XGBoost: a scalable tree boosting system," Proceedings of KDD, 785–794 (2016).