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 (the mean of ). Then repeat for :
- compute the residuals , what the current model still gets wrong;
- fit a small regression tree to the residuals;
- add a damped copy of it: .
The learning rate (shrinkage) , 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:
Why "gradient"
For the squared loss , the residual is exactly the negative gradient with respect to the prediction:
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 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 plus noise, 300 training and 300 test points, 100 rounds of depth-3 trees with :
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 , 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 | 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 () |
number of trees; too many overfits, choose with early stopping |
learning_rate () |
smaller needs more trees and usually generalises better; roughly constant |
max_depth |
interaction order: depth 1 stumps give an additive model, depth captures -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 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
- After the first round with , a training point had and , and the first tree predicts the residual exactly. What is at that point, and how many such rounds would close half the gap?
Answer
. Each round removes 10 % of the remaining gap, so after rounds the gap is ; half the gap remains when , , so 7 rounds.
- Why does boosting with depth-1 trees (stumps) give a model without interactions?
Answer
Each stump depends on one feature only, so the sum groups into , 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?
- The original target
- The residuals of the current ensemble
- A bootstrap sample of
- The predictions of the previous tree
What happens to a gradient-boosted model as you keep adding trees with a fixed learning rate?
- It can only improve
- Training error keeps falling, and at some point validation error starts rising
- Nothing changes after 10 trees
- Bias increases
Which statement about the learning rate is right?
- Larger is always better
- Smaller rates need more trees but usually generalise better
- It only affects training speed
- It must be 1 for squared loss