Lesson 14 of 227 min
Gradient boosting
Start from the average; each new small tree learns what the guesses still miss and adds a share of its answer, until new rows stop getting better.
After this lesson you can explain how each new tree fixes the errors of the last (XGBoost, LightGBM, CatBoost).
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
Score the bank’s calls
Put bank-additional-full.csv from UCI Bank Marketing by your notebook. Use the twelve columns from the chapter and give the word columns pandas’ category type. Seal 1,000 calls. Early stopping for the large folds uses a small validation split inside each fit. Classifier reference
import pandas as pd
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.model_selection import cross_val_score, train_test_split
from sklearn.metrics import roc_auc_score
calls = pd.read_csv("bank-additional-full.csv", sep=";")
words = ["job", "marital", "education", "default", "housing", "loan",
"contact", "poutcome"]
features = words + ["age", "campaign", "pdays", "previous"]
features = [column for column in calls.columns if column in features]X = calls[features].astype({column: "category" for column in words})
y = calls["y"].eq("yes")
X, X_test, y, y_test = train_test_split(
X, y, test_size=1000, stratify=y, random_state=0
)
baseline = HistGradientBoostingClassifier(random_state=0)
scores = cross_val_score(baseline, X, y, scoring="roc_auc")
print(round(scores.mean(), 4), baseline.fit(X, y).n_iter_)0.7353 45
Pick the stopping rule
Use your own validation set with X_val and y_val. max_iter caps the run, n_iter_no_change sets its patience, and max_leaf_nodes limits each tree. Here scoring="roc_auc" makes the stop watch the same score as the folds. The sealed calls are still out of the fit. Fit reference
X_fit, X_val, y_fit, y_val = train_test_split(
X, y, test_size=0.10, stratify=y, random_state=0
)
model = HistGradientBoostingClassifier(
early_stopping=True, max_iter=500, n_iter_no_change=10,
max_leaf_nodes=15, scoring="roc_auc", random_state=0
)
model.fit(X_fit, y_fit, X_val=X_val, y_val=y_val)
print(model.n_iter_, round(roc_auc_score(y_val, model.predict_proba(X_val)[:, 1]), 4))16 0.7549
Stop in three other libraries
All three can watch the same validation calls. XGBoost takes patience on the model. LightGBM takes a callback. CatBoost takes names of the word columns and can keep the best iteration. CatBoost 1.2.10 failed to clone in our scikit-learn 1.9.1 run. For folds, fit a fresh model in each split.
import xgboost as xgb
import lightgbm as lgb
from catboost import CatBoostClassifier
xmodel = xgb.XGBClassifier(enable_categorical=True, n_estimators=500,
random_state=0, early_stopping_rounds=10)
xmodel.fit(X_fit, y_fit, eval_set=[(X_val, y_val)], verbose=False)
lmodel = lgb.LGBMClassifier(n_estimators=500, verbose=-1, random_state=0)
lmodel.fit(X_fit, y_fit, eval_X=X_val, eval_y=y_val,
callbacks=[lgb.early_stopping(10, verbose=False)])
print(xmodel.best_iteration + 1, lmodel.best_iteration_)14 28
Xt = X_fit.astype({column: str for column in words})
Xv = X_val.astype({column: str for column in words})
cmodel = CatBoostClassifier(cat_features=words, iterations=500,
random_seed=0, verbose=False)
cmodel.fit(Xt, y_fit, eval_set=(Xv, y_val),
early_stopping_rounds=10, use_best_model=True)
print(cmodel.tree_count_)82
Leave a numeric gap
Histogram boosting can send a missing value to the side of a split that works better during training. Here both training and validation contain a few missing ages. This is one way to handle a numeric gap. For CatBoost’s word columns, use a string such as "missing" when you need a category for blanks. Missing-value reference
X_with_gaps = X_fit.copy()
X_with_gaps.loc[X_with_gaps.index[:20], "age"] = float("nan")
gap_model = HistGradientBoostingClassifier(max_iter=30, random_state=0)
gap_model.fit(X_with_gaps, y_fit)
one_gap = X_val.iloc[:1].assign(age=float("nan"))
print(one_gap["age"].isna().item(), round(gap_model.predict_proba(one_gap)[0, 1], 3))True 0.289
Predict a mass with one-question trees
Put Palmer Penguins’ penguins.csv next to the notebook. Use max_depth=1 for one question per tree. With squared error, each leaf adds a share of its training penguins’ average miss. Use staged_predict to score the validation penguins after each addition. Regressor reference
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.metrics import root_mean_squared_error
penguins = pd.read_csv("penguins.csv").dropna(subset=["flipper_length_mm", "body_mass_g"])
Xp, yp = penguins[["flipper_length_mm"]], penguins["body_mass_g"]
X_rest, _, y_rest, _ = train_test_split(Xp, yp, test_size=0.25, random_state=0)
X_peng, X_check, y_peng, y_check = train_test_split(
X_rest, y_rest, train_size=20, random_state=0
)mass = GradientBoostingRegressor(max_depth=1, learning_rate=0.1,
n_estimators=100, random_state=0)
mass.fit(X_peng, y_peng)
errors = [root_mean_squared_error(y_check, guess)
for guess in mass.staged_predict(X_check)]
best = min(range(len(errors)), key=errors.__getitem__)
print(best + 1, round(errors[best]))30 408
Follow a probability step
For a yes or no, the model adds tree answers to a raw score. The sigmoid turns that score into a probability. With log loss, the direction to move the raw score for one call is y - p. The tree’s leaf uses the group of calls and the loss to find the size of the update. Gradient boosting guide
from scipy.special import expit
raw_score = model.decision_function(X_val.iloc[:3])
chance_yes = expit(raw_score)
direction = y_val.iloc[:3].to_numpy(dtype=int) - chance_yes
print(chance_yes.round(3).tolist())
print(direction.round(3).tolist())[0.121, 0.07, 0.107] [-0.121, -0.07, -0.107]
Run on Python 3.13.3, scikit-learn 1.9.1, pandas 3.1.1, XGBoost 3.4.1, LightGBM 4.7.0, CatBoost 1.2.10. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: Decision trees
One cut on the bill leaves 83 Adelies alone in one pile, a perfect pile, and the other pile very mixed. A cut on the flipper leaves two piles, each mostly one kind. Which does the tree keep as its first question?
2 of 3
You keep adding boosted trees. The miss on the penguins they learned from keeps falling. What does the miss on new penguins do?
3 of 3
A penguin's guess is the average, 4,203 grams. It really weighs 4,850. The next tree, learned on the misses, answers +875 grams for its pile. The learning rate is a tenth. What is the penguin's new guess?
The ideas in this lesson
- Gradient boosting
- Start from the average; each new small tree learns what the guesses still miss, and a share of its answer is added.
- Early stopping
- After each new tree, score the validation set; stop when its error stops falling, and keep the best number of trees.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
Gradient boosting
Here's an idea. What if each new tree fixed the last one's mistakes? Each tree learns only what the trees before it still miss. Grow them one after another. Keep adding trees. Does it keep getting better?
Keep your guess
Hold on to your guess. Here are twenty penguins to learn from, by flipper and mass. Two hundred and thirty-six new penguins are kept aside, to choose how many trees to use, and eighty-six stay sealed. Start with the simplest guess: their average, about four thousand two hundred grams, for every penguin. Look at this one, with a long flipper. It's heavier than the guess, by about six hundred and fifty grams. Over all twenty, a typical miss is about nine hundred grams.
The misses are what it learns
So what should the next tree learn?
Not the masses. For every penguin, take its mass minus the guess.
What's left is its miss.
The misses are what the next tree learns.
For our penguin, that's plus six hundred and fifty grams.
A tree for a number
The tree is small: one question, one cut on the flipper. Where will it cut?
It tries every cut, the way a tree does, and keeps the one that leaves the smallest misses on its two sides. Two hundred and three and a half millimeters.
Each side answers with the average miss of its pile. The eleven shorter flippers: about minus seven hundred grams. The nine longer ones: plus eight hundred and seventy-five. So our penguin's own miss is six hundred and fifty, and its pile's answer is eight hundred and seventy-five.
Add it
Now add the tree's answer to every guess. For short flippers, the guess drops to about three thousand five hundred grams. For long ones, it rises to about five thousand one hundred. Most misses get smaller. A few grow: those penguins are far from their pile's average. A typical miss is now four hundred and forty-six grams, not nine hundred.
Again: boosting
So do it again. The next tree learns what's still missed. This one cuts at two hundred and twenty-one and a half. Add it.
Then the next tree, and the next.
After ten trees, the guess is a staircase that follows the penguins. It misses them by about one hundred and ninety grams.
Each new tree fixes what all the trees before it still miss. That's boosting.
One after another
Small trees, one after another, adding up. A forest is the other way around: many trees, grown separately, that vote.
A share of each tree
So far, each tree added its whole answer: whole steps. But should each tree fix it all at once? Think of editing a piece of writing. Each pass fixes a little of what's still wrong. So add only a tenth of each tree's answer. After one tree, our penguin's guess moves up by about ninety grams. A tenth of its pile's answer. This needs more trees. But on the new penguins, will it do better, or worse?
A little better. Its lowest miss on the new penguins is four hundred and eight grams, at thirty trees. With whole steps, the lowest was four hundred and twenty-two, at four trees.
Why gradient
You've seen this idea before. It's gradient descent, with trees. Each tree is one small step that makes the misses smaller. How big a step? The share. And that share is called the learning rate. That's where the word gradient comes from.
More trees, worse on new penguins
Boosting adds small trees, each one learning what's still missed. So keep adding them. Does it keep getting better?
Guess what happens on the new penguins.
On its own twenty, the miss keeps falling: one hundred and twenty-seven grams at five hundred trees.
On the new penguins, it climbs, from four hundred and eight up to four hundred and thirty-seven. The staircase jumps up and down to hit each of the twenty. That's overfitting. What's left to fix is partly each penguin's own luck, and the trees learn that too. More trees never make a forest overfit. More boosted trees can.
Early stopping
So stop early. After each tree, score the new penguins. When the next ten trees don't lower the miss, stop, and keep the best. Here it stops at forty trees, and keeps thirty. That's early stopping.
The test set, once
Now open the test set, just once.
Thirty small trees miss the eighty-six penguins by four hundred and thirty-nine grams. Always guessing the average misses them by seven hundred and forty-four.
In code
Now a real table, and a yes or no: the bank's calls. Here the model gives each call a chance of a yes. Each tree learns how far that chance is from the real answer, one or zero.
In scikit-learn, boosted trees take one line. They handle the columns of words, like the job, by themselves.
And on a table this big, they also stop early by themselves.
Guess the area under the ROC curve, on the folds.
Zero point seven four, after forty-five trees. About the same as the forest and the bank's model. On this table, every good model lands around there.
Now turn early stopping off. Grow a thousand trees.
About zero point seven. The trees learned the training calls' own luck, and did worse on new calls.
XGBoost, LightGBM and CatBoost are the same idea, in other libraries.
On most tables, boosted trees are the first strong model to try.
Two ideas
So: each small tree learns what the guesses still miss, and a share of its answer is added.
And you stop when it stops getting better on the new penguins.
Each tree fixes what's left
Each small tree fixes what's left, and you stop in time. Now try it on this lesson's page, and take the quiz. Find the best learning rate.
You use this lesson in Lab 5: Boosted trees or a pretrained model?, after Tabular foundation models.
Facts last checked on .
