Gradient Boosting
Bagging and random forests train many trees independently and average them. Boosting trains trees one after another, where each new tree tries to fix the mistakes of the trees before it. Gradient boosting is the most successful form of this idea; libraries like XGBoost, LightGBM and CatBoost (all based on it) win a large share of competitions on tabular data.
The idea in plain NumPy
For regression the recipe is beautifully simple:
- Start with a constant prediction (the mean of
y). - Compute the residuals:
y - current prediction— what's still wrong. - Fit a small tree to the residuals.
- Add a fraction (the learning rate) of that tree's predictions to the current prediction.
- Repeat.
import numpy as np
from sklearn.tree import DecisionTreeRegressor
rng = np.random.default_rng(0)
x = rng.uniform(0, 6, 100).reshape(-1, 1)
y = np.sin(x).ravel() * 3 + rng.normal(0, 0.3, 100)
learning_rate = 0.3
prediction = np.full_like(y, y.mean()) # step 1
for step in range(1, 31):
residuals = y - prediction # step 2
stump = DecisionTreeRegressor(max_depth=2, random_state=0).fit(x, residuals) # step 3
prediction += learning_rate * stump.predict(x) # step 4
if step in (1, 2, 5, 10, 30):
print(f"after {step:2} trees: mean squared error = {np.mean((y - prediction) ** 2):.3f}")after 1 trees: mean squared error = 2.523
after 2 trees: mean squared error = 1.458
after 5 trees: mean squared error = 0.398
after 10 trees: mean squared error = 0.102
after 30 trees: mean squared error = 0.034
Each small tree on its own is a weak model, yet together they drive the training error down fast: after 10 trees it is already close to the noise level (0.3² = 0.09), and by 30 trees it is below it — a sign that the later trees have started fitting the noise itself. "Gradient" refers to the fact that residuals are the gradient of the squared error — for other loss functions (like log-loss for classification) the trees fit the corresponding gradient instead.
GradientBoostingClassifier
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier
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=5, stratify=y)
gb = GradientBoostingClassifier(n_estimators=100, learning_rate=0.1, max_depth=3, random_state=0)
gb.fit(X_tr, y_tr)
rf = RandomForestClassifier(n_estimators=100, random_state=0).fit(X_tr, y_tr)
print(f"gradient boosting test accuracy: {gb.score(X_te, y_te):.3f}")
print(f"random forest test accuracy: {rf.score(X_te, y_te):.3f}")gradient boosting test accuracy: 0.982
random forest test accuracy: 0.982
The key knobs
| Parameter | Effect |
|---|---|
n_estimators |
number of boosting rounds (trees) |
learning_rate |
how much each tree contributes; smaller needs more trees but generalises better |
max_depth |
depth of each tree; boosting uses shallow trees (2–5) |
subsample |
fraction of rows per tree (< 1.0 adds randomness, "stochastic" boosting) |
Unlike a random forest, boosting can overfit when you add too many trees. staged_predict lets you watch the test score after every round:
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.ensemble import GradientBoostingClassifier
X, y = make_classification(n_samples=600, n_features=20, n_informative=5,
flip_y=0.1, random_state=1)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, random_state=0)
gb = GradientBoostingClassifier(n_estimators=300, learning_rate=0.3, max_depth=3, random_state=0)
gb.fit(X_tr, y_tr)
test_acc = [np.mean(pred == y_te) for pred in gb.staged_predict(X_te)]
best = int(np.argmax(test_acc))
for n in [10, 50, best + 1, 300]:
print(f"{n:3} trees: test accuracy {test_acc[n - 1]:.3f}")
print("best number of trees:", best + 1) 10 trees: test accuracy 0.856
50 trees: test accuracy 0.872
109 trees: test accuracy 0.889
300 trees: test accuracy 0.861
best number of trees: 109
flip_y=0.1 flips 10 % of the labels — label noise that late trees start to memorise.
Early stopping and HistGradientBoosting
Rather than guessing n_estimators, let the model stop when a held-out validation score stops improving. HistGradientBoostingClassifier — scikit-learn's fast, LightGBM-style implementation — does this with early_stopping=True. It also bins features into histograms, which makes it much faster on large data and lets it handle missing values natively:
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.ensemble import HistGradientBoostingClassifier
X, y = make_classification(n_samples=600, n_features=20, n_informative=5,
flip_y=0.1, random_state=1)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, random_state=0)
hgb = HistGradientBoostingClassifier(max_iter=300, learning_rate=0.1, early_stopping=True,
validation_fraction=0.2, n_iter_no_change=10, random_state=0)
hgb.fit(X_tr, y_tr)
print("trees actually built:", hgb.n_iter_)
print(f"test accuracy: {hgb.score(X_te, y_te):.3f}")
X_missing = X_te.copy()
X_missing[::5, 0] = np.nan # punch holes in the data
print(f"with missing values: {hgb.score(X_missing, y_te):.3f}")trees actually built: 27
test accuracy: 0.839
with missing values: 0.839
Bagging vs boosting
| Bagging / random forest | Boosting | |
|---|---|---|
| Trees trained | independently (parallel) | sequentially, each fixing the last |
| Typical trees | deep | shallow |
| Mainly reduces | variance | bias (and variance) |
| Too many trees | harmless | can overfit |
| Tuning effort | low | moderate (learning rate, depth, rounds) |
Note: XGBoost, LightGBM and CatBoost are separate libraries with the same core idea plus many engineering tricks. They follow the scikit-learn
fit/predictAPI, so everything you learn here transfers.
Go further: Gradient Boosting: Fitting the Residuals builds boosting from scratch and explains the "gradient" in its name; the lessons after it cover XGBoost, LightGBM and CatBoost.
Test yourself
In gradient boosting for regression, what does each new tree learn to predict?
- The original target y
- The residual errors of the current ensemble
- A random subset of labels
- The feature importances
What is the usual effect of lowering the learning rate?
- Fewer trees are needed
- More trees are needed, often with better generalisation
- The model can no longer overfit
- Trees become deeper
Which statement about boosting is true?
- Its trees are trained independently
- Adding more and more trees can overfit
- It uses only deep trees
- It cannot do classification