Gradient boosting
Small trees grown one after another correct the errors of their sum: fitting residuals, boosting as gradient descent in function space, losses, shrinkage and subsampling, XGBoost leaf values and gain, LightGBM and CatBoost, early stopping, and stacking on out-of-fold predictions.
Fitting residuals
The topic Bagging and random forests ended with a limit. Averaging trees grown independently lowers the variance but keeps the bias of a single tree, so a forest needs deep trees and can do nothing about an error that all its trees share. Boosting builds the ensemble the other way round. The trees are small and grown one after another, and each new tree is fitted to what the current ensemble still gets wrong.
Start with squared loss and the best constant, . Its errors on the training set are the residuals . Fit a regression tree to the residuals by least squares: it predicts where the model is too low and where too high. Add it with a small factor, the learning rate :
Then fit to the new residuals , and so on. After stages the model is
A toy version of the house-price task: four houses with rooms and prices (in hundreds of thousands). Take stumps, trees with one split, and . Then and the residuals are . The best stump splits between 3 and 4 rooms and predicts on the left and on the right. Half of it moves the model to . Three stages by hand:
import numpy as np
from sklearn.tree import DecisionTreeRegressor
x = np.array([[1.0], [2.0], [3.0], [4.0]])
y = np.array([1.0, 3.0, 4.0, 8.0])
F = np.full(4, y.mean()) # F_0 = 4
for m in range(1, 4):
stump = DecisionTreeRegressor(max_depth=1).fit(x, y - F)
F += 0.5 * stump.predict(x) # eta = 0.5
print(m, F.round(3), round(float(((y - F) ** 2).mean()), 3))1 [3.333 3.333 3.333 6. ] 2.5
2 [2.167 3.722 3.722 6.389] 1.139
3 [1.694 3.25 4.194 6.861] 0.47The training MSE falls from to , and . Each stump alone is a poor model, a single question. Their sum is not: the bias falls with every stage. That is the opposite of bagging, where strong trees are only averaged.
Gradient descent in function space
Why residuals, and what replaces them for another loss? The training loss
depends on the function only through its values . Treat these values as parameters and take a step of gradient descent on them, as in the topic Gradient descent. Each value moves against its own partial derivative:
For the negative gradient is , exactly the residual. So fitting residuals was gradient descent all along.
But this step exists only at the training points, and the model must predict everywhere. Friedman (2001) replaces the vector by the closest function in the base class: a regression tree fitted to the pseudo-residuals by least squares,
Why does this lower the loss? By the first-order Taylor expansion (see Derivatives and Taylor series), adding changes by about . That change is most negative when the vector points along , and the least-squares fit is the tree that points most nearly that way.
The tree chooses only the direction. How far to go is a separate one-dimensional problem, and with a tree it splits into one problem per leaf, because the leaves do not overlap:
The model then takes the shrunken step . The loss enters twice: in the pseudo-residuals and in the leaf values. The tree structure is always chosen by squared error on the pseudo-residuals, whatever the loss.
Losses
A new loss changes the pseudo-residuals and the leaf values, and nothing else. is the best constant under that loss, the summary of the targets from the topic Conditional expectation: the mean for squared error, the median for absolute error.
| Loss | Pseudo-residual | Leaf value | Predicts |
|---|---|---|---|
| squared | mean of residuals | conditional mean | |
| absolute | median of residuals | conditional median | |
| Huber | residual clipped at | Huber location of residuals | robust mean |
| pinball at level | or | -quantile of residuals | conditional -quantile |
For classification take classes and let be a log-odds, as in the topic Logistic regression: and
Its first derivative in is the one you met in that topic, and you will write the pseudo-residual yourself in the check below. The second derivative is . The best leaf value has no closed form here. One Newton step from (see Unconstrained optimization) replaces it:
The classic AdaBoost is boosting with the exponential loss , with classes (Freund and Schapire, 1997; Friedman, Hastie and Tibshirani, 2000). Its pseudo-residual grows without bound on a confidently misclassified point. A single wrong label can then take over the next tree, so AdaBoost is sensitive to label noise.
Shrinkage, tree size, subsampling
Boosting drives the training loss down fast, and with it, it starts to fit the noise. Three controls slow it down.
- Shrinkage. A smaller learning rate needs more trees to reach the same training loss, and usually gives a lower test error. This is an empirical regularity, not a theorem. The standard recipe is , with the number of trees chosen by early stopping (Friedman, 2001).
- Tree size. A tree with leaves can model interactions of at most features, and so can a sum of such trees. Stumps give an additive model, one feature per term. Hastie, Tibshirani and Friedman (2009) suggest . Small trees have high bias and low variance, which is what boosting needs, the opposite of the deep trees of a forest.
- Subsampling. Stochastic gradient boosting grows each tree on a random half of the training points, drawn without replacement (Friedman, 2002). It is faster, and as in bagging the randomness lowers the variance. XGBoost also samples columns, as a random forest does.
Numbers make the trade-off concrete. Take Friedman's test function of 10 features, 500 training points and trees of depth 3, with a separate validation set.
| Setting | Best validation MSE | Trees at the best | Validation MSE at 1000 trees |
|---|---|---|---|
| , half the rows per tree | — |
A full step finds its best model after eight trees and then overfits. A tenth of a step takes longer and ends much lower.
Second-order boosting: XGBoost
Gradient boosting chooses the tree by squared error on the gradient, an approximation that the leaf step then corrects. XGBoost (Chen and Guestrin, 2016) builds the tree for the actual loss from the start. It uses a second-order expansion and penalizes the tree. The objective at stage is
with a price per leaf and an penalty on the leaf values. With at , the second-order expansion in , without the constant, is
A tree is constant on each leaf. Write and for the sums of and over leaf . The objective becomes a sum of independent parabolas, . Each is minimized by
That value scores a tree structure. The gain of splitting a node into a left part and a right part is how much the score drops:
A split is made only if its gain is positive, so is a minimal gain. shrinks the leaf values towards zero, most strongly in leaves with little curvature. With and log-loss, is the Newton leaf of the previous block.
A leaf with small numbers: log-loss, current log-odds 0, so , and labels . The gradients are , and every . So and . Without the penalty the leaf value is , and the quadratic approximation of the loss falls by . The exact log-loss falls by : close, not equal. With the value shrinks to .
XGBoost, LightGBM and CatBoost
XGBoost, LightGBM and CatBoost share the second-order objective. They differ in how they make it fast and how they handle categories.
| XGBoost (Chen and Guestrin, 2016) | LightGBM (Ke et al., 2017) | CatBoost (Prokhorenkova et al., 2018) | |
|---|---|---|---|
| Split search | exact over sorted values, or approximate on quantiles weighted by | histograms: each feature binned once, splits only at bin edges | — |
| Tree growth | level by level | leaf-wise: always split the leaf with the largest gain | oblivious trees: one split per level, shared by the whole level |
| Rows | row and column subsampling | GOSS: keep the points with the largest , sample the rest and reweight them | ordered boosting |
| Features | a learned default direction for missing values | EFB: bundle sparse features that are never nonzero together | ordered target statistics for categories |
Leaf-wise growth reaches a lower training loss for the same number of leaves, so LightGBM needs a limit on leaves or depth. Oblivious trees are the opposite choice: heavily constrained and very fast to evaluate.
Two CatBoost ideas are about leakage, the problem of the topic Data, features and leakage. A category can be replaced by the average target of the training points in it, smoothed by a prior. Computed over all points, that average contains itself and leaks the target into the feature of point . Ordered target statistics use only the points that come before in a random permutation, an out-of-fold idea. Ordered boosting applies the same rule to the gradients. A residual computed by a model that was trained on the point is smaller than it would be on a new point. The authors call this prediction shift, target leakage inside boosting itself.
Early stopping
The number of trees is the main regularization parameter of boosting. The training loss falls with every tree. The validation loss falls, reaches a minimum and rises. Early stopping tracks the validation loss after each tree and keeps the model at its minimum, or stops when the loss has not improved for a set number of rounds, the patience.
The validation set is carved out of the training data, as in the topic Validation and overfitting, or the number of rounds is chosen by cross-validation. scikit-learn does it in one call. A binary task from its datasets (breast cancer, log-loss), with 20% of the training set held out and a patience of 20 rounds:
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.model_selection import train_test_split
X, y = load_breast_cancer(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)
model = HistGradientBoostingClassifier(
learning_rate=0.1, max_iter=1000, early_stopping=True,
validation_fraction=0.2, n_iter_no_change=20, random_state=0,
).fit(X_tr, y_tr)
print(model.n_iter_, round(model.score(X_te, y_te), 3))73 0.942Out of the 1000 allowed rounds it stopped at 73, with test accuracy . Here is how the two ensembles of this module compare.
| Bagging and random forests | Gradient boosting | |
|---|---|---|
| Trees | deep, grown independently | small, grown one after another |
| Each tree fits | a bootstrap sample of the targets | the negative gradient at the current model |
| Reduces | variance | bias; variance is held back by , and subsampling |
| More trees | never hurt | eventually overfit |
| Tuning | little | learning rate, number of trees, depth, penalties |
Stacking and what comes next
Boosting and bagging combine many models of one kind. Stacking (Wolpert, 1992; Breiman, 1996) combines a few models of different kinds, say a forest, a boosted model and a nearest-neighbour model. Their predictions become the features of a meta-model, often a linear or logistic regression, which learns how much to trust each.
The obvious training set for the meta-model is the base models' predictions on their own training data, and it is wrong. The fix is out-of-fold predictions. Split the training set into folds and predict each fold with copies of the base models trained on the other . Every point's meta-feature then comes from models that never saw it, just as at test time. Then refit the base models on all the data for prediction.
On Friedman's function with 500 training points, take 1-nearest-neighbour, ridge and a random forest, and a linear meta-model with non-negative weights.
| Meta-model trained on | Weights (1-NN, ridge, forest) | Test MSE |
|---|---|---|
| in-sample predictions | ||
| 5-fold out-of-fold predictions |
The best single model, the forest, has test MSE . Blending is the holdout version: base models on one part of the data, the meta-model on their predictions for another. It leaks nothing but uses less data. With time-ordered data, folds and holdouts must respect time.
This closes the module on trees and ensembles. Every model in it splits on features that someone provided: rooms, income, the count of a word. On tabular data, where each column means something, that is enough, and boosted trees remain hard to beat: a benchmark of 45 tabular datasets found tree ensembles still ahead of deep networks at around ten thousand rows (Grinsztajn, Oyallon and Varoquaux, 2022). But one pixel of a handwritten digit, or the identity of a token, says little on its own. What matters is a pattern across many of them, and a threshold on one input rarely asks a good question. For such data the features themselves have to be learned. The topic From linear models to networks starts from the linear models of this course, stacks them with nonlinearities in between and trains the whole stack by the same gradient descent.
Check your understanding
The same questions as in Pulse. Answers are shared between modes.
Answers are saved on the server and tied to this browser until you sign in.