Sub topic 10
Gradient-boosted trees
This chapter assumes you know decision trees and random forests from the previous chapters, and that you can run cross-validation with scikit-learn pipelines.
How boosting works
A random forest trains many deep trees independently and averages them. Gradient boosting builds shallow trees one after another. Each new tree is fitted to the errors the current ensemble still makes. More precisely, it is fitted to the gradient of the loss with respect to the current predictions.
- Start with a constant prediction, such as the average of the target.
- Compute how wrong each row is under the loss function.
- Fit a small tree to those errors.
- Add the tree to the ensemble, scaled by the learning rate.
- Repeat until you reach the maximum number of iterations or validation error stops improving.
Because trees are added in sequence, boosting reduces bias. A forest mainly reduces variance. The cost is that boosting can overfit if you add too many trees.
Why it is often the strongest tabular model
Boosted trees handle mixed feature types, nonlinear effects, and interactions without much feature engineering. They are insensitive to feature scaling. In scikit-learn, HistGradientBoostingClassifier and HistGradientBoostingRegressor also handle missing values natively and can use categorical columns directly. They bin each feature into at most 255 buckets, which makes them fast on large tables.
A runnable example
This example uses native missing-value and categorical support, plus early stopping. It needs scikit-learn 1.4 or newer for categorical_features="from_dtype".
import numpy as np
import pandas as pd
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.model_selection import StratifiedKFold, cross_val_score
rng = np.random.default_rng(0)
n = 500
X = pd.DataFrame({
"age": rng.integers(18, 80, n).astype(float),
"income": rng.normal(50000, 15000, n),
"city": pd.Categorical(rng.choice(["a", "b", "c"], n)),
})
X.loc[rng.choice(n, 25, replace=False), "income"] = np.nan
y = ((X["age"] > 45) ^ (X["city"] == "a")).astype(int)
model = HistGradientBoostingClassifier(
categorical_features="from_dtype",
max_iter=500,
learning_rate=0.1,
early_stopping=True,
validation_fraction=0.1,
n_iter_no_change=10,
random_state=0,
)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
scores = cross_val_score(model, X, y, cv=cv, scoring="roc_auc")
print(f"hist_gb: {scores.mean():.3f} +/- {scores.std():.3f}")With early_stopping=True, the model holds out 10% of each training fold. It stops adding trees when that held-out score has not improved for 10 rounds. The outer test fold is never used for this.
Parameters that matter
| Parameter | Effect | Typical direction |
|---|---|---|
| `learning_rate` | Size of each tree's contribution | Lower is safer but needs more iterations |
| `max_iter` | Maximum number of trees | Set high and let early stopping decide |
| `max_leaf_nodes` / `max_depth` | Complexity of each tree | Smaller values reduce overfitting |
| `min_samples_leaf` | Minimum rows per leaf | Larger values smooth the model |
| `l2_regularization` | Penalty on leaf values | Raise it if the model overfits |
Common errors
- Using the test fold for early stopping. The score then looks better than real performance. Let the estimator hold out its own validation split from the training data.
- Tuning only the number of trees. Learning rate and tree size interact. A lower learning rate usually needs more trees.
- Encoding categories as plain integers. The trees then treat the codes as ordered numbers. Use a categorical dtype or one-hot encoding.
- Assuming it always wins. On small or mostly linear data, a logistic regression can match it, and the gap may be inside the fold-to-fold spread.
- Ignoring noisy labels. Boosting keeps fitting the remaining error, so it can chase label noise. Use stronger regularization and early stopping.
Exercise
A colleague's boosted model scores 0.95 AUC in cross-validation, but only 0.88 on new data. Their code passes the outer test fold as the early-stopping validation set. What is wrong, and how do you fix it?
Show answer
The number of trees was chosen using the same rows that are scored, so the cross-validation score is optimistic. Fix it by letting early stopping use a validation split taken from the training portion only, for example with earlystopping=True and validationfraction. Leave the outer test fold untouched until scoring.