Lesson 11 · Other ways to draw a boundary
Boosting and gradient-boosted trees
The problem
Bagging takes deep trees, which are good but jumpy, and averages away the jumpiness. This lesson goes the other way. It starts from small trees, which are steady but too simple, and adds them up until they're good.
A tree with one or two questions can't draw the rush-hour dip. On its own, it scores about 78% on the validation deliveries.
But it gets some things right. So train a second small tree on what the first one gets wrong. Then a third on what the first two still get wrong, and so on. Each tree is a small correction to the ones before it.
Building a model this way, one small piece at a time, each piece fixing the mistakes of the pieces so far, is called boosting. The pieces are usually small decision trees.
One round by hand
Start with a number to predict: delivery time in minutes, from distance alone. Here are four deliveries.
| Distance (km) | 1 | 2 | 4 | 5 |
|---|---|---|---|---|
| Minutes | 10 | 14 | 26 | 30 |
Worked example
One round of boosting
Start with the average. Before any tree, the model predicts the mean time for every delivery: minutes.
The next round does exactly the same thing to the new residuals. Notice what the tree learns. It doesn't predict minutes. It predicts the correction: how far, and in which direction, the model so far is off.
Watching the residuals shrink
Here are 16 real deliveries from the shop's table, all with light traffic and no rain. Each round fits a one-question tree to the residuals and adds half of it.
0 trees: mean squared error 48.0 · next tree: cut at 4.05 km, −2.7 left, +11.7 right; half of it is added
Things to notice:
- With 0 trees the model is a flat line at the average, 22.2 minutes. The first tree cuts at 4.05 km: the three longest trips took about 12 minutes more than average, the rest about 3 minutes less.
- The second tree cuts at 1.55 km. It fixes what the first tree missed: the shortest trips are still predicted too slow.
- Every tree is a single step: one cut, two values. Added together, the steps make a staircase that climbs with distance.
- The mean squared error falls every round: 48.0, 24.3, 15.7, then 5.3 after 10 trees and 3.2 after 20.
- Later trees chase single deliveries, such as the slow 2.4 km trip. That's the first sign of overfitting: on training data, boosting can drive the error as low as you like.
Predict first
A delivery took 30 minutes. The model currently says 24. The learning rate is 0.1. What does the next tree aim to predict for this delivery, and where does the model's prediction end up?
The formula
Write for the model's prediction after trees, and for the -th tree. Then
Read it back: start from the average. Each round, fit a small tree to what's still wrong, and add times it. The learning rate is the same idea as in gradient descent: a number between 0 and 1 that sets how big each step is. In the worked example, and gave , so each prediction moved by .
Why not , and correct the whole residual at once? Because each tree is fitted to a few noisy examples. Trusting it fully means copying its noise too. Small steps let many trees vote on each correction, which works better on new data. The price is that you need more trees.
Why "gradient" boosting
So far the trees fit residuals. That works for squared error. But "late or not" is a yes/no label, and the right loss there is the cross-entropy loss (also called log loss). What does the next tree fit then?
The answer comes from looking at the residual differently. For one delivery, the squared error is . Its derivative with respect to the prediction is
So the residual is the negative gradient of the loss: the direction that lowers each delivery's loss fastest. Fitting a tree to the residuals is the same as fitting a tree to the downhill direction. This is gradient descent, but on the predictions rather than on weights.
That view works for any loss. Compute the negative gradient of the loss at the current predictions, fit a small tree to it, and add a shrunken copy. This is gradient boosting.
For yes/no labels, the model's score is a log-odds: it becomes a probability through the sigmoid, . The negative gradient of the cross-entropy loss with respect to is : the label (0 or 1) minus the predicted probability. A late delivery the model gives has , so the next tree pushes its score up.
DeeperEach tree is a gradient-descent step in prediction spaceTreat the 200 predictions as 200 parameters. Gradient descent would step each one downhill; a tree takes the same step, but in a form that works on new deliveries too. · 3 min
Picture the model's predictions on the training data as a list of numbers, one per delivery: . The total loss is a function of that list. Plain gradient descent on the list would update every number:
That would fit the training data, but it says nothing about a new delivery: there's no rule, only a list.
Gradient boosting fixes this by fitting a small tree to the negative gradients and stepping along the tree instead. The tree is a rule, so it gives a step for any delivery, seen or not. Its leaves average the gradients of similar deliveries, so the step is a smoothed version of the exact one.
Two details from real libraries:
- For cross-entropy, scikit-learn's
GradientBoostingClassifiersets each leaf's value with one Newton step (it uses the second derivative too), not the plain average of . This lesson's figures do the same. - XGBoost uses second derivatives throughout, both to choose the splits and to set the leaves.
Boosted trees on the rush-hour data
Gradient boosting with small decision trees as the pieces is called gradient-boosted trees. It's what XGBoost, LightGBM, CatBoost and scikit-learn's HistGradientBoostingClassifier do.
Back to the rush-hour picture. Each tree here has depth 2 (two levels of questions, up to four leaves), with at least 5 deliveries per leaf. The learning rate is 0.3, and the loss is cross-entropy.
Adding trees: 0 of 300…
Things to notice:
- One tree is a pale, blocky guess: two cuts, and every shade close to one half because the tree was shrunk by 0.3. Validation accuracy is 78.5%.
- After 10 trees the dip at 19:00 is there. Accuracy jumps to 91.5%.
- From 10 to 50 trees, the shading sharpens but the boundary barely moves (91%).
- At 300 trees, small islands appear around single deliveries, and accuracy drops to 87%. The extra trees are fitting noise.
That last point is the big difference from a random forest. Adding trees to a forest never hurts, because each tree is one more voter. Adding trees to a boosted model makes the model more complex, because each tree corrects the training data a little further. Eventually it corrects noise. So the number of trees is a setting you have to choose: a hyperparameter.
Learning rate and the number of trees
The learning rate and the number of trees work together. A smaller learning rate takes smaller steps, so it needs more of them.
Predict first
You cut the learning rate from 1 to 0.1. What happens to the best number of trees, measured on validation data?
Adding trees: 0 of 300… Lowest point (●): 1: 0 trees · 0.3: 0 trees · 0.1: 0 trees
Things to notice:
- All three curves fall, reach a lowest point, and then rise again. This is the loss curve shape of overfitting.
- The lowest points come at 16, 49 and 117 trees.
- The lowest losses are almost the same: 0.252, 0.254 and 0.259. On this data a small learning rate doesn't reach a lower loss. In many real problems it does a little, which is why the usual advice is to keep it small.
- After the lowest point, the curves rise at different speeds. At 300 trees the loss is 0.776 with learning rate 1, but only 0.277 with 0.1. A small learning rate is forgiving: being 50 trees past the best point barely matters.
A common recipe is a rule of thumb, not a law. Pick a small learning rate such as 0.1, allow many trees, and let the validation data decide when to stop.
Early stopping
The best number of trees is where the validation loss is lowest. But you don't want to grow 1,000 trees only to find out that 117 were best. Instead, watch the validation loss as you go, and stop once it has stopped improving.
You can't stop the moment the loss goes up once: it wobbles. So you wait. Count the rounds since the last new lowest point. When the count reaches a limit, called the patience, stop, and keep the model from the lowest point.
This is early stopping.
Adding trees: 0 of 300…
Worked example
Patience 20, learning rate 0.1
The validation loss reaches a new lowest point, 0.259, after 117 trees. The count resets to 0, and the model with 117 trees is the best so far.
Things to notice in the figure:
- The training loss keeps falling the whole way. On training data, more trees always look better. Only the validation loss shows when to stop.
- With learning rate 0.3 and patience 10, training stops at 42 trees and keeps 32. The loss had a small bump there, and the true lowest point comes later, at 49. A patience that's too small can stop on a wobble.
- A bigger patience costs more trees but is safer. The kept model is the same once the patience is long enough to get past the wobbles.
Early stopping uses the validation data to make a choice, so the validation score of the kept model is a little optimistic. Report the final score on a separate test set that played no part in any choice (see train, validation and test sets).
The same rule stops neural-network training. The Neural-net foundations course uses it with epochs in place of trees.
Bagging vs boosting
Both build an ensemble of trees. They do it in opposite ways.
Bagging: one deep tree
validation …
Bagging: 100 averaged
validation …
Boosting: one small tree
validation …
Boosting: 50 added
validation …
Each picture: time sent across (17:00–23:00), distance up (0–8 km); ○ on time, × late. Bagging starts from good-but-noisy trees and averages away the noise. Boosting starts from a weak tree and adds detail.
Things to notice:
- Bagging's single tree already has the right shape, with noisy details (81.5%). Averaging 100 of them keeps the shape and smooths the details (88.5%).
- Boosting's single tree is crude and unsure (78.5%). Adding 50 of them builds up the shape piece by piece (91%).
| Bagging and random forests | Boosting | |
|---|---|---|
| Trees | Deep: low bias, high variance | Small: high bias, low variance |
| How they're built | Independently, so in parallel | In order: each fixes the ones before |
| How they're combined | Averaged | Added, each shrunk by the learning rate |
| What it mainly cuts | Variance | Bias |
| More trees | Never hurts; levels off | Eventually overfits; use early stopping |
In the language of the bias–variance trade-off: bagging starts from low-bias models and removes variance. Boosting starts from low-variance models and removes bias. Boosted trees usually win on tables of data, but they have more settings to tune and must be stopped at the right time.
DigressionWhere boosting comes fromA theory question in 1990, AdaBoost in 1995, gradient boosting in 2001, XGBoost in 2016. · 2 min
- The question. Learning theorists asked whether many "weak" models, each only a little better than guessing, could be combined into a strong one. Robert Schapire showed in 1990 that they could.
- AdaBoost. Yoav Freund and Robert Schapire's AdaBoost first appeared at a conference in 1995, with the journal version in 1997. It doesn't fit residuals. Instead, after each round it gives more weight to the training examples the model got wrong, so the next weak model focuses on them.
- Gradient boosting. Jerome Friedman's "Greedy function approximation: a gradient boosting machine" (2001) described boosting as gradient descent on the predictions, as in this lesson. That made it work for any loss, and he paired it with small regression trees.
- XGBoost. Tianqi Chen and Carlos Guestrin's "XGBoost: A scalable tree boosting system" (2016) made gradient-boosted trees fast and easy to use on large data. It won many machine-learning competitions and is still widely used.
DigressionXGBoost, LightGBM and CatBoost: what they addPenalties on the trees, binned features, missing values and categories. The idea is the same as in this lesson. · 3 min
All three are gradient-boosted trees. Their differences are in the details:
- XGBoost (2016) adds penalties to its training objective: one on the size of each leaf's value and one for each extra leaf. These limit how far one tree can push the model. It uses second derivatives to choose splits, and it learns a default direction for missing values at each split.
- LightGBM (from Microsoft, 2017) first sorts each feature's values into a few hundred bins. Then it only has to try a cut between bins, not between every pair of values, which is much faster on big tables. It also grows each tree leaf by leaf, splitting whichever leaf helps most, rather than level by level.
- CatBoost (from Yandex, 2018) focuses on categorical features, such as a driver's name or a postcode. It turns each category into numbers in a careful order, so a row's own label doesn't leak into its features.
scikit-learn's HistGradientBoostingClassifier uses the same binning idea as LightGBM, handles missing values, and is fast enough for hundreds of thousands of rows. The older GradientBoostingClassifier doesn't bin, and is the exact algorithm of this lesson's figures.
In scikit-learn and XGBoost
The worked example, in scikit-learn. GradientBoostingRegressor starts at the mean and fits each tree to the residuals:
def one_round_by_hand() -> np.ndarray:
"""Four deliveries, one depth-1 tree, learning rate 0.5: predictions after one round."""
km = np.array([[1.0], [2.0], [4.0], [5.0]])
minutes = np.array([10.0, 14.0, 26.0, 30.0])
model = GradientBoostingRegressor(n_estimators=1, max_depth=1, learning_rate=0.5)
model.fit(km, minutes) # starts at the mean, 20, then fits one split to the residuals
return model.predict(km)
print("after one round:", one_round_by_hand()) # [16. 16. 24. 24.]after one round: [16. 16. 24. 24.]staged_predict gives the prediction after 1 tree, then 2 trees, and so on. It's the easiest way to watch boosting work:
def staged_errors(rounds: int = 20, learning_rate: float = 0.5) -> list[float]:
"""Mean squared error on the 16 deliveries after 0, 1, 2, … depth-1 trees."""
km, minutes = one_feature_deliveries()
model = GradientBoostingRegressor(n_estimators=rounds, max_depth=1, learning_rate=learning_rate)
model.fit(km, minutes)
errors = [float(np.mean((minutes - minutes.mean()) ** 2))] # round 0: predict the average
# staged_predict yields the prediction after 1 tree, 2 trees, …
errors += [float(np.mean((minutes - pred) ** 2)) for pred in model.staged_predict(km)]
return errors
for r, err in enumerate(staged_errors()):
if r in (0, 1, 2, 5, 10, 20):
print(f"{r:>2} trees: mean squared error {err:5.1f}") 0 trees: mean squared error 48.0
1 trees: mean squared error 24.3
2 trees: mean squared error 15.7
5 trees: mean squared error 8.0
10 trees: mean squared error 5.3
20 trees: mean squared error 3.2The three learning rates on the rush-hour data. GradientBoostingClassifier uses cross-entropy by default:
def validation_curves(rounds: int = 300) -> dict[float, list[float]]:
"""Validation log loss after 0 … rounds depth-2 trees, for three learning rates (rush-hour data)."""
x_train, y_train, x_val, y_val = load_rush_hour()
start = log_loss(y_val, np.full(len(y_val), y_train.mean())) # round 0: the training late rate
curves = {}
for rate in RATES:
model = GradientBoostingClassifier(n_estimators=rounds, learning_rate=rate, max_depth=2, min_samples_leaf=5)
model.fit(x_train, y_train)
# staged_predict_proba: P(on time), P(late) after each added tree.
curves[rate] = [start] + [log_loss(y_val, p[:, 1]) for p in model.staged_predict_proba(x_val)]
return curves
for rate, curve in validation_curves().items():
best = int(np.argmin(curve))
print(f"learning rate {rate}: lowest validation loss {curve[best]:.3f} after {best} trees; {curve[-1]:.3f} after 300")learning rate 1.0: lowest validation loss 0.252 after 16 trees; 0.776 after 300
learning rate 0.3: lowest validation loss 0.254 after 49 trees; 0.386 after 300
learning rate 0.1: lowest validation loss 0.259 after 117 trees; 0.277 after 300These match the figure to within about 0.001: the browser's trees follow the same algorithm.
HistGradientBoostingClassifier does early stopping itself. Set early_stopping=True; n_iter_no_change is the patience, and max_iter is only an upper limit. Since scikit-learn 1.7, fit accepts your own validation data as X_val and y_val. Without them, it holds back validation_fraction of the training data (10% by default).
def hist_early_stopping(seed: int = 0) -> tuple[int, float]:
"""HistGradientBoostingClassifier stops by itself once the validation loss stops improving."""
x_train, y_train, x_val, y_val = load_rush_hour()
model = HistGradientBoostingClassifier(
learning_rate=0.1,
max_iter=1000, # an upper limit; early stopping decides
max_depth=2,
early_stopping=True,
n_iter_no_change=20, # the patience
random_state=seed,
)
model.fit(x_train, y_train, X_val=x_val, y_val=y_val) # X_val, y_val: new in scikit-learn 1.7
return model.n_iter_, model.score(x_val, y_val)
n_trees, acc = hist_early_stopping()
print(f"HistGradientBoosting: stopped with {n_trees} trees, validation accuracy {acc:.1%}")HistGradientBoosting: stopped with 102 trees, validation accuracy 92.0%In XGBoost, early_stopping_rounds is the patience and goes in the constructor. The validation data goes to fit as eval_set. After training, best_iteration is the best round, counted from 0, and predict and score use only the trees up to it.
def xgboost_early_stopping(seed: int = 0) -> tuple[int, float]:
"""The same in XGBoost: early_stopping_rounds is the patience, eval_set the validation data."""
x_train, y_train, x_val, y_val = load_rush_hour()
model = xgb.XGBClassifier(
n_estimators=1000,
learning_rate=0.1,
max_depth=2,
early_stopping_rounds=20,
eval_metric="logloss",
random_state=seed,
)
model.fit(x_train, y_train, eval_set=[(x_val, y_val)], verbose=False)
# predict() and score() use the trees up to best_iteration (counted from 0).
return model.best_iteration + 1, model.score(x_val, y_val)
n_trees, acc = xgboost_early_stopping()
print(f"XGBoost: best with {n_trees} trees, validation accuracy {acc:.1%}")XGBoost: best with 94 trees, validation accuracy 93.0%The three libraries stop at slightly different places (117, 102 and 94 trees), because their trees differ in the details. Here the validation set both chose the number of trees and gave the score, so these scores are a little optimistic. With real data, keep a separate test set for the final number.
Putting it together
Worked example
Two rounds on one late delivery
The rush-hour training set has 101 late deliveries out of 200, so the model starts at P(late) for everyone. As a log-odds that's .
Common misconceptions
"Each tree predicts the delivery time." Only the starting value does. Each tree predicts a correction to the model so far, and only a learning-rate-sized share of it is added.
"More trees always help, as in a random forest." In a forest, extra trees are extra voters, and the error levels off. In boosting, every tree fits the training data more closely, so the validation error eventually rises. Choose the number of trees with early stopping.
"A smaller learning rate gives a better model." It needs more trees to reach about the same point. Its real advantage is that it rises slowly after the best point, so the exact number of trees matters less.
"Gradient boosting runs gradient descent on the trees' weights." The trees are grown greedily, one split at a time, as in any decision tree. The gradient is taken with respect to the predictions, and each tree is a step in that direction.
"The early-stopping score is an honest estimate of new-data performance." The validation data chose when to stop, so its score is slightly flattering. Use a test set that played no part in any choice.
Recap
- Boosting builds a model in order: each new small model is fitted to what the model so far still gets wrong.
- Gradient boosting fits each tree to the negative gradient of the loss. For squared error that's the residual; for cross-entropy it's the label minus the predicted probability.
- Each tree is added shrunk by the learning rate. Smaller rates need more trees but are more forgiving.
- Unlike a forest, a boosted model overfits if you add too many trees. Early stopping watches the validation loss and keeps the model from its lowest point, after waiting out a patience.
- Bagging averages deep trees to cut variance; boosting adds small trees to cut bias.
- Python names in this lesson: scikit-learn's
GradientBoostingRegressor,GradientBoostingClassifier(n_estimators,learning_rate,max_depth,staged_predict,staged_predict_proba) andHistGradientBoostingClassifier(early_stopping,n_iter_no_change,max_iter,X_val,y_val,n_iter_); XGBoost'sXGBClassifier(early_stopping_rounds,eval_set,best_iteration).