Skip to content

MLDay 25 of 50Trees and Ensembles

Boosting

Learning from Mistakes

7 min read

The forest from D24 ranks card customers by their risk of default with a ROC-AUC of 0.755. Its 300 trees each learned alone, so no tree knew what the others got wrong. What if every new tree studied exactly those mistakes?

The idea

Boosting builds trees one after another. It starts with one plain guess for every row, such as the mean. Each row's residual is its real value minus the current prediction: what is still wrong. The next tree is a small one, fitted to the residuals instead of the targets. Its output is added to the prediction, and the residuals shrink.

Each tree's output is scaled down first by the learning rate η\eta, a number such as 0.1. No single tree can then take over; many small steps reach a better fit than a few big ones.

The trees stay shallow: a few questions each. A forest averages deep, independent trees. Boosting sums small trees in sequence, each one aimed at the remaining error.

More trees keep lowering the error on the training rows. Past some point they start fitting noise, and new data gets worse predictions, as on D10. Early stopping guards against this. Hold back some training rows as a validation set, check the error on them after every tree, and stop once it stops improving.

A tiny example

Four deliveries, A to D, at 1, 2, 3 and 4 km took 10, 12, 20 and 26 minutes. The last two cross a river. Boost three one-question trees with η=0.5\eta = 0.5. Each tree splits the rows where it best fits the residuals (D23), and each side predicts its mean residual.

Step Residuals A, B, C, D The tree learns Prediction A, B, C, D RMSE
start: the mean 17, 17, 17, 17 6.40
tree 1 −7, −5, +3, +9 A, B → −6; C, D → +6 14, 14, 20, 20 3.74
tree 2 −4, −2, 0, +6 A, B, C → −2; D → +6 13, 13, 19, 23 2.24
tree 3 −3, −1, +1, +3 A, B → −2; C, D → +2 12, 12, 20, 24 1.41

Each prediction moves by half the tree's output: for D, 20+0.5×6=2320 + 0.5 \times 6 = 23. Tree 2 noticed that D was still 6 minutes short and split it off on its own. RMSE, the typical miss (D05), falls with every tree.

The formula

Each round adds one tree's output, scaled by the learning rate:

y^(m)=y^(m−1)+η hm(x)\hat{y}^{(m)} = \hat{y}^{(m-1)} + \eta\, h_m(x)
Symbol Meaning
y^(m)\hat{y}^{(m)} the prediction after mm trees
y^(m−1)\hat{y}^{(m-1)} the prediction before this tree
η\eta the learning rate, between 0 and 1
hm(x)h_m(x) tree mm's output for row xx: its guess of that row's residual

Worked: a row has y=10y = 10 and y^=7\hat{y} = 7, so its residual is 3. A tree predicts 3, and with η=0.1\eta = 0.1 the new prediction is 7+0.1×3=7.37 + 0.1 \times 3 = 7.3.

For a 0/1 target like default, each tree fits y−py - p: the label minus the predicted probability, which is the downhill slope of the log loss (D12). It plays the same part: how far off each row is, and in which direction.

Try it

Boost one-question trees on ten deliveries

Each tree is one split (a stump), fitted to what the ensemble still gets wrong: the red gaps. It is added in at learning rate η. Add trees and watch the RMSE fall.

510102030Distance (km)Delivery time (minutes)

trees 0RMSE 9.952with no trees (predict the mean, 20.4): 9.952

02468100510number of treesRMSE (on these points)

Press Add 10 at η=0.1\eta = 0.1: the RMSE falls from 9.95 to 4.76. Press Reset, drag the learning rate to 1, and press Add a tree three times: the RMSE falls to 1.39. Keep pressing Add 10 up to 100 trees: the RMSE reaches 0.017. The line now chases the 1-minute wiggles (11 at 3 km, then 10 at 4 km), which are noise. At η=0.1\eta = 0.1 the same 100 trees stop at 0.31: small steps fit the wiggles more slowly, so early stopping can catch the best point.

In code

scikit-learn's HistGradientBoostingClassifier is the strong default for tables. It first sorts each feature into at most 255 bins (value ranges), so a split tries at most 254 thresholds, not every value. It also handles missing values (NaN) itself, and treats pandas category columns as categories (categorical_features="from_dtype"). Here it faces the D24 forest on the Phase 3 credit split.

# script_id: day_025_boosting/credit
import os
from pathlib import Path

import numpy as np
import pandas as pd
from sklearn.ensemble import HistGradientBoostingClassifier, RandomForestClassifier
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split

DATA_DIR = Path(os.environ.get("ML_DATA", "datasets"))
df = pd.read_csv(DATA_DIR / "credit_default" / "default_of_credit_card_clients.csv")
df = df.drop(columns="ID").rename(columns={"default payment next month": "default"})
X, y = df.drop(columns="default"), df["default"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y, random_state=42)

def auc(model):
    return roc_auc_score(y_test, model.predict_proba(X_test)[:, 1])

forest = RandomForestClassifier(n_estimators=300, n_jobs=-1, random_state=42).fit(X_train, y_train)
boost = HistGradientBoostingClassifier(random_state=42).fit(X_train, y_train)
print(f"forest, 300 trees: {auc(forest):.3f}")
print(f"boosting:          {auc(boost):.3f}")

val_loss = -boost.validation_score_          # log loss on the held-back rows, after 0, 1, 2, … trees
best = int(np.argmin(val_loss))
print(f"validation loss: {val_loss[0]:.3f} at the start, lowest {val_loss[best]:.3f} after {best} trees")
print(f"stopped after {boost.n_iter_} trees")
forest, 300 trees: 0.755
boosting:          0.781
validation loss: 0.528 at the start, lowest 0.422 after 62 trees
stopped after 72 trees

Boosting wins, 0.781 to 0.755. With over 10,000 training rows, early stopping is on by default (early_stopping="auto"). It holds back 10% of the training rows, never the test set, and checks their log loss after each tree. The best was after tree 62. Ten more trees brought no gain, so it stopped at 72, keeping all 72.

What happens without it? Turn it off and let 1,000 trees run:

# script_id: day_025_boosting/credit
no_stop = HistGradientBoostingClassifier(early_stopping=False, max_iter=1000, random_state=42)
no_stop.fit(X_train, y_train)
print(f"no early stopping, 1,000 trees: {auc(no_stop):.3f}")
no early stopping, 1,000 trees: 0.757

The extra 928 trees learn the training rows' noise and drag the score back to about the forest's level.

Quick check

Quick check

1. A row has y = 50 and the prediction is 40. The next tree predicts 10 for it, with η = 0.1. What is the new prediction?

2. What does each new tree in boosting learn to predict?

3. With early stopping off, 1,000 trees score 0.757, below the 0.781 of the early-stopped model. Why?

Next

The boosted model is the best so far, but which features drive it? D26: Explain a Model's Predictions measures that.

Data: Default of Credit Card Clients (UCI Machine Learning Repository, dataset 350), CC BY 4.0; cite Yeh, I.-C. and Lien, C.-H. (2009), "The comparisons of data mining techniques for the predictive accuracy of probability of default of credit card clients", Expert Systems with Applications 36(2).

Next · Day 26 · 8 minExplain a Model's Predictions← Previous: Day 24 · Bagging and Random Forests
Not tapped yet