Sub topic 10
Gradient-boosted trees
This chapter assumes you know how a decision tree splits data, how a random forest averages many trees, and how to run cross_val_score on a scikit-learn pipeline. It builds on the baseline and fold setup from earlier chapters. Gradient-boosted trees are usually the strongest model family to try on rows-and-columns data. Knowing why they work tells you which settings matter and where they fail.
How boosting differs from bagging
A random forest trains many deep trees independently on bootstrap samples and averages them. Each tree has low bias and high variance, and averaging reduces the variance.
Gradient boosting works the other way. It builds many shallow trees in sequence. Each new tree is fitted to the errors the current ensemble still makes. The ensemble's prediction is the sum of the trees' outputs, each scaled by a small number called the learning rate. Boosting mainly reduces bias. Shallow trees are weak on their own, but the sequence gradually corrects them.
The mechanism in code
For squared error, "the errors" are plain residuals. For other losses, such as log loss for classification, the tree is fitted to the negative gradient of the loss, which is where the name comes from. The following sketch shows the idea for regression. It uses only numpy and scikit-learn.
import numpy as np
from sklearn.tree import DecisionTreeRegressor
rng = np.random.default_rng(0)
X = rng.uniform(-3, 3, size=(300, 1))
y = np.sin(X[:, 0]) + rng.normal(0, 0.2, 300)
learning_rate = 0.1
prediction = np.full_like(y, y.mean())
trees = []
for m in range(100):
residual = y - prediction
tree = DecisionTreeRegressor(max_depth=2).fit(X, residual)
prediction += learning_rate * tree.predict(X)
trees.append(tree)
if m + 1 in (1, 10, 50, 100):
mse = np.mean((y - prediction) ** 2)
print(f"after {m + 1:3d} trees: training MSE = {mse:.3f}")Training error falls with every round. That is the central risk: nothing in the loop stops it from fitting noise. The number of rounds is therefore a real hyperparameter, and you choose it with held-out data.
Using a production implementation
In practice you use a histogram-based implementation. It bins each numeric feature into at most 255 buckets, so split search is fast even on large tables. scikit-learn provides HistGradientBoostingClassifier and HistGradientBoostingRegressor. The separate libraries XGBoost, LightGBM and CatBoost follow the same idea with different engineering choices.
The scikit-learn estimators handle missing values natively. Each split learns which side the missing values should go to, so imputation is optional. They can also treat a pandas category column as categorical without one-hot encoding. This example needs scikit-learn 1.4 or later.
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(
learning_rate=0.1,
max_iter=500,
early_stopping=True,
n_iter_no_change=10,
validation_fraction=0.1,
categorical_features="from_dtype",
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"roc_auc: {scores.mean():.3f} +/- {scores.std():.3f}")
model.fit(X, y)
print("trees actually built:", model.n_iter_)Here max_iter=500 is only a ceiling. With early_stopping=True, the estimator holds out 10% of the training data it receives. It stops when the score on that part has not improved for 10 rounds, and n_iter_ reports where it stopped.
Hyperparameters that matter
Boosting has many settings, but a few do most of the work.
| Hyperparameter | What it controls | Typical direction |
|---|---|---|
| `learning_rate` | Size of each tree's contribution | Smaller (0.03 to 0.1) is usually better, but needs more trees |
| `max_iter` | Maximum number of trees | Set high, let early stopping choose |
| `max_leaf_nodes` or `max_depth` | Complexity of each tree, hence interaction depth | 15 to 63 leaves; lower for small or noisy data |
| `min_samples_leaf` | Smallest allowed leaf | Raise it to fight overfitting on small data |
| `l2_regularization` | Penalty on leaf values | Small positive values often help a little |
| `max_features` | Fraction of features tried per split (scikit-learn 1.4+) | Below 1.0 adds randomness and decorrelates trees |
Learning rate and number of trees trade against each other. Halving the learning rate roughly doubles the trees you need, and it often gives a slightly better model. A common practice is to fix a modest learning rate, let early stopping pick the tree count, and spend the tuning budget on tree size and min_samples_leaf. The tuning chapter covers how to search these settings without contaminating your evaluation.
Tree size sets the order of feature interactions the model can represent. A tree with 2 splits along any path can capture two-way interactions. The synthetic target above, an XOR of age and city, needs interactions. A linear model cannot represent it without hand-built features, and boosted trees can.
Strengths on tabular data
- No scaling needed. Splits depend on the order of values, not their magnitude, so monotonic transformations change nothing.
- Native missing values. Missingness itself can carry signal, and the model can use it.
- Interactions and nonlinearity come for free. You do not specify them in advance.
- Strong default accuracy. Boosting is often the best or close to the best model on structured data with a few hundred to millions of rows. This is why it is the usual challenger after a linear baseline.
Failure modes and gotchas
Overfitting through too many rounds. Without early stopping, the training score keeps improving while validation score peaks and then falls. Always monitor a held-out score.
Early stopping on the evaluation fold. If you stop based on the same fold you report, the score is optimistic. The built-in early_stopping=True avoids this because it carves its validation set out of the training data only. With XGBoost or LightGBM, pass a separate validation set, not the test fold.
No extrapolation. Trees predict constants within leaves. If a target grows linearly with a feature and test rows lie beyond the training range, predictions flatten at the edge. A linear component or a transformed target can help.
Noisy labels. Boosting keeps trying to fit the largest remaining errors, so mislabeled rows can attract many trees. Larger min_samples_leaf, a smaller learning rate and stronger regularization limit the damage.
High-cardinality categories. The scikit-learn estimator supports at most 255 categories per categorical feature. Features such as zip code or user ID need grouping, target encoding done inside a pipeline, or a library like CatBoost that encodes them with ordered statistics. Target encoding done outside the cross-validation loop is a classic leakage source.
Class imbalance. The default loss optimizes overall fit, which can ignore a rare class. Use class_weight or sample weights, and judge the result with a metric chosen for imbalance, such as average precision, rather than accuracy.
Cost. Training is sequential across trees, so it parallelizes less than a random forest. Prediction cost grows with the number of trees times their depth, which matters for the latency discussion in a later chapter.
Where it fits in the selection workflow
Treat boosting as a strong candidate, not as an automatic winner. Score it on the same folds and metric as your baseline, linear model and random forest. If it beats a well-built logistic regression only by a small amount, compare the gap with the fold-to-fold standard deviation before accepting extra complexity. On very small datasets (a few hundred rows) or strongly linear relationships, a regularized linear model can match it and is easier to explain.
Exercise
A colleague trains a gradient-boosted model with learningrate=0.1 and maxiter=2000, no early stopping, and reports a cross-validated AUC that is lower than a random forest's. Training AUC is near 1.0. What is the likely cause, and what two changes would you try first?
Show answer
The model is overfitting because it keeps adding trees long after validation performance peaked. Turn on early stopping (for example earlystopping=True with niternochange=10) so the number of trees is chosen from held-out data, and increase regularization by raising minsamplesleaf or lowering maxleafnodes (a smaller learning rate with early stopping is another good option). Then rescore on the same folds.
Exercise
Why does the manual boosting loop use max_depth=2 trees and a learning rate of 0.1 instead of one deep tree fitted to the residuals?
Show answer
Boosting relies on many weak learners that each correct a little. A deep tree would fit the residuals, including noise, almost perfectly in one step, so the ensemble would overfit immediately. Shallow trees and a small learning rate make each step a modest correction, and the number of rounds then controls the fit.