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, . Its residuals say what is still unexplained, so fit a small regression tree to the pairs and add a fraction of it:
Then compute the residuals of , fit to them, add , and so on. After rounds the model is : a sum of small trees, each correcting what the previous ones left over. The fraction is the learning rate, also called shrinkage.
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 , what is the new prediction for the third point?
Show the answer
4.5
, and the residuals are . The leaves predict and , so for the third point and for the first two. The new residuals, , are smaller but not zero: each round removes only a fraction of what the tree captures.
Boosting is gradient descent in function space
Why residuals? Take any differentiable loss . The training loss depends on only through its values . Treat those values as parameters and take a gradient-descent step: move each along the negative gradient
For squared loss this is exactly the residual . But a step defined only at the training points says nothing about new inputs. So fit a regression tree to the pseudo-residuals : 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):
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_MFriedman'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.
Squared loss: the negative gradient is the residual, and the best value for a leaf is the mean residual of its points.
Log loss for labels , with the log-odds and . Writing the loss in terms of makes the derivative immediate:
The leaf value has no closed form for log loss. One Newton step from uses the second derivative :
| Loss | Pseudo-residual | Leaf value |
|---|---|---|
| Squared, | , the residual | mean of the residuals in the leaf |
| Absolute, | median of the residuals in the leaf | |
| Huber, threshold | , clipped to | median plus the mean of the clipped deviations |
| Quantile (pinball) at level | if , else | the -quantile of the residuals in the leaf |
| Log loss, | one Newton step: |
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?
- A thousand times as much as a typical point
- Nothing: absolute loss ignores points with large residuals
- About a million times as much, since the loss is squared internally
- The same as any other point: its pseudo-residual is
Show the answer
D. The same as any other point: its pseudo-residual is
The negative gradient of is , so every point's pseudo-residual is or 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 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 interacts with . Smaller steps need proportionally more trees, and empirically smaller values of give equal or better test error (Friedman, 2001). The standard recipe from The Elements of Statistical Learning is to fix small, below 0.1, and choose by early stopping.
Tree size, interactions and subsampling
The size of each tree controls which functions the sum can build. A tree with leaves has 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 features. Stumps () produce an additive model with no interactions at all. The Elements of Statistical Learning reports that works well in boosting, with results fairly insensitive to the exact choice in that range.
A boosted model uses trees with 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 are independent and uniform on , and the target is . Can boosting stumps for many rounds learn it?
No. A sum of stumps is , and the best additive approximation of is the zero function: , and likewise given , so is orthogonal to every additive function. Stumps explain none of its variance. Trees of depth 2, which split on and then on , 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 of the training rows, drawn without replacement, which makes training faster and often more accurate, the extra randomness acting like the averaging in bagging; 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 penalty on the leaf values, the of XGBoost's objective (XGBoost, LightGBM & CatBoost).
Gradient boosting in practice
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 keptscikit-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.
| Hyperparameter | What it controls | Common starting point |
|---|---|---|
| Number of trees | how far the descent goes: the main regularizer | early stopping on validation data |
| Learning rate | step size; smaller needs more trees | 0.01–0.1 |
| Tree size (leaves or depth) | interaction order and the bias of each step | 4–64 leaves (depth 2–6) |
| Row subsample | randomness and speed | 0.5–1 |
| Column subsample | decorrelates trees, speeds up wide data | 0.5–1 |
| Minimum leaf size, leaf penalty | noise in individual leaf values | tens of examples; around 1 |
| Loss | what "error" means: mean, median, quantile, probability | chosen by the task, not tuned |
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 .
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 and adds it with a small learning rate : gradient descent on the training loss in function space.
- For squared loss the pseudo-residuals are the residuals; for log loss with they are . Leaf values are re-optimized per leaf: means, medians, quantiles or a Newton step .
- The number of trees is the main regularization parameter, chosen by early stopping on validation data; a smaller needs proportionally more trees and usually generalizes at least as well.
- A tree with leaves expresses interactions of order up to ; 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.
In gradient boosting for binary classification with log loss, labels and the log-odds, what are the pseudo-residuals?
- , the gap between label and score
- , the gap between label and predicted probability
Show the answer
B. , the gap between label and predicted probability
Write the loss as ; its derivative in is , so the negative gradient is . The second derivative, , enters the Newton step for the leaf values.
You lower the learning rate from to and keep everything else fixed. What should you expect?
- The same model after the same number of trees
- Roughly ten times as many trees to reach the best validation error, which is usually as good or slightly better
- Ten times fewer trees, since each one is more accurate
- 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 , so progress per round slows roughly in proportion. Empirically, smaller 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, bottoms out clearly worse (0.135), while every reaches about the same minimum, near 0.11, only later. The recipe: a small , and early stopping to choose the number of trees.
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?
- A sum of stumps is an additive model , which cannot represent an interaction between two features
- Stumps cannot split on binary features
- Boosting needs a learning rate of 1 to capture interactions
- 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 , 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 leaves can express interactions of order up to , so even 3- or 4-leaf trees can capture it.
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?
- A price extrapolated along the trend of the largest houses
- An error, because the input is out of range
- Roughly the same as for the largest training houses: tree ensembles are constant beyond the training range
- 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
- Gradient Boosting as Functional Gradient Descent · Any differentiable loss, shrinkage and stochastic boosting.
- XGBoost, LightGBM & CatBoost · Second-order splits, histograms and ordered boosting at scale.
- Trees vs Deep Learning on Tabular Data · Why gradient-boosted trees still win so often.
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).