Skip to content
BIASED

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, F0=yˉF_0 = \bar y. Its errors on the training set are the residuals ri=yi−F0r_i = y_i - F_0. Fit a regression tree b1b_1 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 η∈(0,1]\eta \in (0, 1]:

F1(x)=F0+η b1(x).F_1(x) = F_0 + \eta \, b_1(x).

Then fit b2b_2 to the new residuals yi−F1(xi)y_i - F_1(x_i), and so on. After MM stages the model is

FM(x)=F0+η∑m=1Mbm(x).F_M(x) = F_0 + \eta \sum_{m=1}^{M} b_m(x).

A toy version of the house-price task: four houses with x=1,2,3,4x = 1, 2, 3, 4 rooms and prices y=1,3,4,8y = 1, 3, 4, 8 (in hundreds of thousands). Take stumps, trees with one split, and η=0.5\eta = 0.5. Then F0=4F_0 = 4 and the residuals are −3,−1,0,4-3, -1, 0, 4. The best stump splits between 3 and 4 rooms and predicts −4/3-4/3 on the left and 44 on the right. Half of it moves the model to (3.333,3.333,3.333,6)(3.333, 3.333, 3.333, 6). 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.47

The training MSE falls from 6.56.5 to 2.52.5, 1.1391.139 and 0.470.47. 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

Q(F)=∑i=1nL(yi,F(xi))Q(F) = \sum_{i=1}^n L\big(y_i, F(x_i)\big)

depends on the function FF only through its nn values F(x1),…,F(xn)F(x_1), \dots, F(x_n). 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:

F(xi)←F(xi)−η gi,gi=∂L(yi,F)∂F∣F=Fm−1(xi).F(x_i) \leftarrow F(x_i) - \eta \, g_i, \qquad g_i = \frac{\partial L(y_i, F)}{\partial F}\Big|_{F = F_{m-1}(x_i)}.

For L=12(y−F)2L = \frac12 (y - F)^2 the negative gradient is −gi=yi−Fm−1(xi)-g_i = y_i - F_{m-1}(x_i), 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 −g-g by the closest function in the base class: a regression tree fitted to the pseudo-residuals −gi-g_i by least squares,

bm=arg⁡min⁡b∑i=1n(−gi−b(xi))2.b_m = \arg\min_{b} \sum_{i=1}^n \big(-g_i - b(x_i)\big)^2.

Why does this lower the loss? By the first-order Taylor expansion (see Derivatives and Taylor series), adding εb\varepsilon b changes QQ by about ε∑igi b(xi)\varepsilon \sum_i g_i \, b(x_i). That change is most negative when the vector (b(x1),…,b(xn))(b(x_1), \dots, b(x_n)) points along −g-g, 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 R1,…,RJR_1, \dots, R_J do not overlap:

wj=arg⁡min⁡w∑xi∈RjL(yi,Fm−1(xi)+w).w_j = \arg\min_{w} \sum_{x_i \in R_j} L\big(y_i, F_{m-1}(x_i) + w\big).

The model then takes the shrunken step Fm=Fm−1+η∑jwj [x∈Rj]F_m = F_{m-1} + \eta \sum_j w_j \, [x \in R_j]. 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. F0F_0 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 L(y,F)L(y, F) Pseudo-residual −g-g Leaf value Predicts
squared 12(y−F)2\frac12 (y - F)^2 y−Fy - F mean of residuals conditional mean
absolute ∣y−F∣\lvert y - F \rvert sign⁡(y−F)\operatorname{sign}(y - F) median of residuals conditional median
Huber residual clipped at ±δ\pm\delta Huber location of residuals robust mean
pinball at level qq qq or q−1q - 1 qq-quantile of residuals conditional qq-quantile

For classification take classes {0,1}\{0, 1\} and let FF be a log-odds, as in the topic Logistic regression: p=σ(F)p = \sigma(F) and

L(y,F)=−ylog⁡p−(1−y)log⁡(1−p).L(y, F) = -y \log p - (1 - y) \log(1 - p).

Its first derivative in FF is the one you met in that topic, and you will write the pseudo-residual yourself in the check below. The second derivative is h=p(1−p)h = p(1 - p). The best leaf value has no closed form here. One Newton step from w=0w = 0 (see Unconstrained optimization) replaces it:

wj=−∑xi∈Rjgi∑xi∈Rjhi.w_j = -\frac{\sum_{x_i \in R_j} g_i}{\sum_{x_i \in R_j} h_i}.

The classic AdaBoost is boosting with the exponential loss e−yFe^{-yF}, with classes {−1,+1}\{-1, +1\} (Freund and Schapire, 1997; Friedman, Hastie and Tibshirani, 2000). Its pseudo-residual y e−yFy \, e^{-yF} 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 η\eta 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 η≤0.1\eta \le 0.1, with the number of trees chosen by early stopping (Friedman, 2001).
  • Tree size. A tree with JJ leaves can model interactions of at most J−1J - 1 features, and so can a sum of such trees. Stumps give an additive model, one feature per term. Hastie, Tibshirani and Friedman (2009) suggest 4≤J≤84 \le J \le 8. 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
η=1\eta = 1 5.725.72 88 6.756.75
η=0.1\eta = 0.1 2.712.71 189189 2.742.74
η=0.1\eta = 0.1, half the rows per tree 2.382.38 205205 —

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 mm is

∑i=1nL(yi,Fm−1(xi)+b(xi))+γJ+λ2∑j=1Jwj2,\sum_{i=1}^n L\big(y_i, F_{m-1}(x_i) + b(x_i)\big) + \gamma J + \frac{\lambda}{2} \sum_{j=1}^J w_j^2,

with a price γ\gamma per leaf and an L2L_2 penalty λ\lambda on the leaf values. With hi=∂2L/∂F2h_i = \partial^2 L / \partial F^2 at Fm−1(xi)F_{m-1}(x_i), the second-order expansion in b(xi)b(x_i), without the constant, is

∑i=1n[gi b(xi)+12hi b(xi)2]+γJ+λ2∑jwj2.\sum_{i=1}^n \Big[ g_i \, b(x_i) + \frac12 h_i \, b(x_i)^2 \Big] + \gamma J + \frac{\lambda}{2} \sum_j w_j^2.

A tree is constant on each leaf. Write GjG_j and HjH_j for the sums of gig_i and hih_i over leaf jj. The objective becomes a sum of independent parabolas, ∑j[Gjwj+12(Hj+λ)wj2]+γJ\sum_j \big[ G_j w_j + \frac12 (H_j + \lambda) w_j^2 \big] + \gamma J. Each is minimized by

wj∗=−GjHj+λ,with value−12∑j=1JGj2Hj+λ+γJ.w_j^* = -\frac{G_j}{H_j + \lambda}, \qquad \text{with value} \quad -\frac12 \sum_{j=1}^J \frac{G_j^2}{H_j + \lambda} + \gamma J.

That value scores a tree structure. The gain of splitting a node into a left part LL and a right part RR is how much the score drops:

gain=12[GL2HL+λ+GR2HR+λ−(GL+GR)2HL+HR+λ]−γ.\text{gain} = \frac12 \left[ \frac{G_L^2}{H_L + \lambda} + \frac{G_R^2}{H_R + \lambda} - \frac{(G_L + G_R)^2}{H_L + H_R + \lambda} \right] - \gamma.

A split is made only if its gain is positive, so γ\gamma is a minimal gain. λ\lambda shrinks the leaf values towards zero, most strongly in leaves with little curvature. With λ=0\lambda = 0 and log-loss, wj∗w_j^* is the Newton leaf of the previous block.

A leaf with small numbers: log-loss, current log-odds 0, so p=0.5p = 0.5, and labels 1,1,01, 1, 0. The gradients p−yp - y are −0.5,−0.5,0.5-0.5, -0.5, 0.5, and every hi=0.25h_i = 0.25. So G=−0.5G = -0.5 and H=0.75H = 0.75. Without the penalty the leaf value is 0.5/0.75=0.6670.5 / 0.75 = 0.667, and the quadratic approximation of the loss falls by 12⋅0.25/0.75=0.167\frac12 \cdot 0.25 / 0.75 = 0.167. The exact log-loss falls by 0.1700.170: close, not equal. With λ=1\lambda = 1 the value shrinks to 0.5/1.75=0.2860.5 / 1.75 = 0.286.

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 hih_i 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 ∣gi∣\lvert g_i \rvert, 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 yky_k itself and leaks the target into the feature of point kk. Ordered target statistics use only the points that come before kk 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 MM 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.942

Out of the 1000 allowed rounds it stopped at 73, with test accuracy 0.9420.942. 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 η\eta, MM 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 KK folds and predict each fold with copies of the base models trained on the other K−1K - 1. 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 (1,0,0)(1, 0, 0) 13.7113.71
5-fold out-of-fold predictions (0.03,0.32,0.76)(0.03, 0.32, 0.76) 4.294.29

The best single model, the forest, has test MSE 4.764.76. 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.

Full notes

Answers are saved on the server and tied to this browser until you sign in.