TExcelTAD
Home › Classical ML Algorithms: Supervised & Unsupervised › Gradient Boosting: Fitting the Residuals

Gradient Boosting: Fitting the Residuals

Random forests grow many independent deep trees and average them. Boosting does the opposite: it grows small trees one after another, and each new tree is trained to fix the mistakes the ensemble still makes. Gradient-boosted trees (Friedman, 2001) and their fast descendants XGBoost, LightGBM and CatBoost win most competitions on tabular data and power ranking, pricing and risk models everywhere. The Machine Learning course uses GradientBoostingClassifier; this lesson builds the regression version from residuals.

The idea: add a correction, again and again

Start from a constant prediction F0F_0 (the mean of yy). Then repeat for m=1,…,Mm = 1, \dots, M:

  1. compute the residuals ri=yi−Fm−1(xi)r_i = y_i - F_{m-1}(\mathbf{x}_i), what the current model still gets wrong;
  2. fit a small regression tree hmh_m to the residuals;
  3. add a damped copy of it: Fm(x)=Fm−1(x)+ν hm(x)F_m(\mathbf{x}) = F_{m-1}(\mathbf{x}) + \nu \, h_m(\mathbf{x}).

The learning rate (shrinkage) ν\nu, typically 0.01 to 0.3, makes each tree fix only part of the error, which leaves room for later trees and generalises better. The final model is a sum:

FM(x)=F0+ν∑m=1Mhm(x)F_M(\mathbf{x}) = F_0 + \nu \sum_{m=1}^{M} h_m(\mathbf{x})

Why "gradient"

For the squared loss L(y,F)=12(y−F)2L(y, F) = \frac{1}{2}(y - F)^2, the residual is exactly the negative gradient with respect to the prediction:

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

So each tree approximates a step of gradient descent, taken not in the space of weights but in the space of functions: the "parameters" being updated are the nn predictions themselves, and the tree generalises the step to new inputs. Replace the squared loss by any differentiable loss and fit trees to its negative gradients (the pseudo-residuals), and the same algorithm handles absolute error, Huber loss, log-loss for classification (next lesson) and ranking losses. The connection to gradient descent is in Gradient Descent and Training Machine Learning Models.

From scratch

Data from y=2sin⁡x1+0.5x22y = 2\sin x_1 + 0.5 x_2^2 plus noise, 300 training and 300 test points, 100 rounds of depth-3 trees with ν=0.1\nu = 0.1:

python · try it yourself
import numpy as np
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import GradientBoostingRegressor

rng = np.random.default_rng(0)
X = rng.uniform(-3, 3, (300, 2))
y = np.sin(X[:, 0]) * 2 + 0.5 * X[:, 1] ** 2 + rng.normal(scale=0.3, size=300)
X_te = rng.uniform(-3, 3, (300, 2))
y_te = np.sin(X_te[:, 0]) * 2 + 0.5 * X_te[:, 1] ** 2 + rng.normal(scale=0.3, size=300)

def boost(X, y, n_rounds=100, lr=0.1, depth=3):
    f0 = y.mean()                                      # start from the best constant
    pred = np.full(len(y), f0)
    trees = []
    for m in range(n_rounds):
        residual = y - pred                            # negative gradient of squared error / 2
        tree = DecisionTreeRegressor(max_depth=depth, random_state=0).fit(X, residual)
        pred += lr * tree.predict(X)                   # a small step towards the residuals
        trees.append(tree)
        if m + 1 in (1, 10, 50, 100):
            print(f"  round {m + 1:3d}  training MSE {np.mean((y - pred) ** 2):.4f}")
    return f0, trees

def boost_predict(f0, trees, X, lr=0.1):
    return f0 + lr * sum(t.predict(X) for t in trees)

f0, trees = boost(X, y)
ours = boost_predict(f0, trees, X_te)
sk = GradientBoostingRegressor(n_estimators=100, learning_rate=0.1, max_depth=3,
                               criterion="squared_error", random_state=0).fit(X, y)
diff = np.abs(ours - sk.predict(X_te))
print(f"test points where the two differ by more than 1e-6: {np.sum(diff > 1e-6)} of 300, largest {diff.max():.2f}")
print("test MSE ours", round(np.mean((ours - y_te) ** 2), 4), " sklearn", round(np.mean((sk.predict(X_te) - y_te) ** 2), 4))
  round   1  training MSE 3.1912
  round  10  training MSE 0.8652
  round  50  training MSE 0.0652
  round 100  training MSE 0.0371
test points where the two differ by more than 1e-6: 15 of 300, largest 0.07
test MSE ours 0.138  sklearn 0.1383

The training error falls steadily as trees are added. The test MSE of 0.138 is above the noise variance 0.32=0.090.3^2 = 0.09, which is as low as any model could get. Our booster and scikit-learn's GradientBoostingRegressor (with the same squared-error split criterion; its default friedman_mse is a slight variant) build the same first trees; late in the sequence, a few splits where two thresholds score almost equally go different ways because the residuals differ in the last floating-point digits, so 15 of the 300 test predictions differ by up to 0.07. Both reach the same test error.

How boosting differs from a forest

Random forest Gradient boosting
trees deep, independent, in parallel shallow (depth 2 to 8), sequential
each tree fits a bootstrap sample of yy the current residuals
reduces mainly variance bias (and variance via shrinkage)
more trees never overfits eventually overfits; needs early stopping
tuning little learning rate, number of trees, depth matter

Hyperparameters

Hyperparameter Effect
n_estimators (MM) number of trees; too many overfits, choose with early stopping
learning_rate (ν\nu) smaller needs more trees and usually generalises better; ν×M\nu \times M roughly constant
max_depth interaction order: depth 1 stumps give an additive model, depth kk captures kk-way interactions
subsample fit each tree on a random fraction of rows (stochastic gradient boosting); 0.5 to 0.8 adds regularisation
min_samples_leaf, max_features as for trees
loss "squared_error", "absolute_error", "huber", "quantile"

The "quantile" loss with alpha=0.9 gives a model of the 90th percentile instead of the mean, a cheap way to get prediction intervals.

Strengths, weaknesses, when to use it

Gradient boosting is usually the most accurate classical model on tabular data, works with any differentiable loss, needs no scaling, and handles mixed features. It is sequential (slower to train than a forest, though prediction is fast), sensitive to hyperparameters, can overfit noisy labels, and like all trees cannot extrapolate. Use it when accuracy on tabular data matters; in practice use the histogram implementations (HistGradientBoostingRegressor, XGBoost, LightGBM), which are much faster than the classic one for more than a few thousand rows.

Pitfalls

  • A big learning rate with many trees. It fits the noise quickly; lower ν\nu and use early stopping.
  • Choosing the number of trees on the test set. Use a validation set or cross-validation.
  • Deep trees. Depth 10 boosted trees overfit fast; boosting wants weak learners.

Practice

  1. After the first round with ν=0.1\nu = 0.1, a training point had y=5y = 5 and F0=1F_0 = 1, and the first tree predicts the residual exactly. What is F1F_1 at that point, and how many such rounds would close half the gap?
Answer

F1=1+0.1⋅4=1.4F_1 = 1 + 0.1 \cdot 4 = 1.4. Each round removes 10 % of the remaining gap, so after kk rounds the gap is 4⋅0.9k4 \cdot 0.9^k; half the gap remains when 0.9k=0.50.9^k = 0.5, k=ln⁡0.5/ln⁡0.9≈6.6k = \ln 0.5 / \ln 0.9 \approx 6.6, so 7 rounds.

  1. Why does boosting with depth-1 trees (stumps) give a model without interactions?
Answer

Each stump depends on one feature only, so the sum F0+ν∑mhm(x)F_0 + \nu\sum_m h_m(\mathbf{x}) groups into ∑jgj(xj)\sum_j g_j(x_j), one function per feature: an additive model. Depth-2 trees can test two features on one path, which creates pairwise interactions.

Test yourself

In gradient boosting with squared loss, what is each new tree trained to predict?

  1. The original target yy
  2. The residuals y−Fm−1(x)y - F_{m-1}(\mathbf{x}) of the current ensemble
  3. A bootstrap sample of yy
  4. The predictions of the previous tree

What happens to a gradient-boosted model as you keep adding trees with a fixed learning rate?

  1. It can only improve
  2. Training error keeps falling, and at some point validation error starts rising
  3. Nothing changes after 10 trees
  4. Bias increases

Which statement about the learning rate ν\nu is right?

  1. Larger is always better
  2. Smaller rates need more trees but usually generalise better
  3. It only affects training speed
  4. It must be 1 for squared loss