Back to Tutorials
Machine Learning
Advanced

Gradient Boosting and XGBoost, Step by Step

The method behind countless winning models on table-shaped data. Add small trees one at a time, each fixing the last one’s mistakes, and find out when to stop.

10 minInteractive: drag, click and try things as you read


Most of the world’s business data sits in tables: customers, orders, readings, claims. On that kind of data, one family of methods keeps coming out on top: gradient boosting, the idea inside XGBoost, LightGBM and CatBoost. Instead of one clever model, it builds hundreds of small, simple ones in a row, each trained only on the mistakes of the ones before it. Here you’ll add the trees yourself, one at a time, and find out when to stop.

Learning from mistakes#

Say you run a bike-hire station and want to predict how many bikes get rented in each hour of the day, so you know when to restock. You have 50 readings from past days: the hour, and how many bikes went out.

The simplest possible model ignores the hour and guesses the average every time: 105 bikes. It’s wrong almost everywhere, but it’s a start. Write down how wrong it is at each reading (the actual count minus the guess). Those leftovers are called residuals: positive where the guess was too low, negative where it was too high.

Now train a small decision tree to predict the residuals. Here each tree may ask two yes-or-no questions about the hour (“before 6:38?”, “after 19:28?”), so it splits the day into at most four stretches and gives each one a number: the average residual there. Add that tree’s answers to the model, work out the new residuals, and train the next tree on those. That’s boosting.

Predict first

The first tree has been added. What does the second tree learn to predict?

Try it
The 50 readings are made up for the demo, from a daily pattern with a morning and a bigger evening rush plus day-to-day noise. Every tree is really fitted in your browser. “New days” are 500 more made-up readings the model never trains on.

The first tree learns the obvious: nights are far below average, the daytime above it. But at a learning rate of 0.3, the model only takes 30% of each tree’s correction. So the second tree finds almost the same thing again, smaller. After that the corrections get more specific: the evening rush is still too low, the middle of the day too high. Twelve trees in, the average miss on the 50 readings has fallen from 68 bikes to 15, and on new days from 59 to 22.

Why not take each tree’s whole correction? Switch the learning rate to 1 and start again. Two trees take the training miss from 68 to 16, but new days stall at 22 to 24 bikes, however many trees you add. Full-size steps chase every bump in the readings, noise included. Small steps let many trees each contribute a little, which averages the noise out. Boosting is many small corrections, each fixing a fraction of what’s still wrong.

When to stop#

Boosting has three main dials: the learning rate, how deep each tree may grow, and how many trees to add. The first two you set; the third you should let the data decide.

Predict first

Keep adding trees, hundreds of them. What happens to the average miss on new days?

Try it
The same made-up readings. For each setting, 300 trees are trained in your browser; the slider shows the model after any number of them. The dashed blue curve is the true daily pattern, which in real life you’d never get to see.

With the learning rate at 0.3 and trees two levels deep, new days are best at 22 trees, off by 21.2 bikes. By 300 trees, it misses the training readings by a tenth of a bike on average, and new days by 23.7. The red line is the floor: even the true pattern misses new days by 16, because no model can predict a random busy afternoon. Any training miss below that floor is memorising, not learning.

Try the other dials. A learning rate of 1 never comes out best, at any depth. Trees 6 levels deep (XGBoost’s default) do worst on new days at every learning rate: with only one column to split on, they chop the day into slivers around single readings. Between 0.3 and 0.1 the difference is small: at depth 2, 0.1 needs 78 trees to 0.3’s 22, and ends a little better, 20.9 against 21.2. Smaller steps rarely hurt, but they cost time.

So in practice you set a small learning rate, allow plenty of trees, and use early stopping: hold back some data as a validation set, score it after every tree, and stop once it hasn’t improved for a while. The yellow dot is where early stopping lands. Small steps, and let a validation set decide how many trees.

Why it’s everywhere#

Gradient-boosted trees are a default choice for table-shaped data. In the 2016 paper introducing XGBoost, its authors counted the winning solutions published on Kaggle’s blog during 2015: 17 of 29 used XGBoost, against 11 that used deep neural networks. Years later, a 2022 benchmark of 45 tabular datasets by Grinsztajn and colleagues still found tree-based models ahead of deep learning on medium-sized data, around 10,000 rows, and found the learning rate to be the most important setting to tune for boosted trees.

Why trees suit tables: columns like age, price and postcode mean different things on different scales, and a tree just asks about one column at a time (“price over £40?”). It doesn’t care about units, copes with sudden jumps, and ignores columns that don’t help. Neural networks still win on images, sound and text.

In code#

XGBoost (pip install xgboost scikit-learn) on scikit-learn’s real breast cancer dataset (569 tumours, 30 measurements each), with early stopping on a validation set that’s kept apart from the final test:

import xgboost as xgb
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split

X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.25, random_state=0, stratify=y_train)

model = xgb.XGBClassifier(
    n_estimators=1000,         # an upper limit; early stopping picks the real number
    learning_rate=0.05,
    max_depth=3,
    early_stopping_rounds=50,  # stop when 50 trees in a row don't help on the validation set
)
model.fit(X_train, y_train, eval_set=[(X_val, y_val)], verbose=False)
print("trees kept:", model.best_iteration + 1)             # trees kept: 258
print("test accuracy:", round(model.score(X_test, y_test), 3))  # test accuracy: 0.947

XGBoost’s defaults are a learning rate of 0.3, trees 6 deep and 100 trees. Two more settings borrow the random forest’s trick: subsample trains each tree on a random share of the rows, and colsample_bytree on a random share of the columns. LightGBM, CatBoost and scikit-learn’s HistGradientBoostingClassifier work on the same idea with different shortcuts.

What to remember

  • Gradient boosting starts from a simple guess and adds small trees one at a time, each trained on what the model still gets wrong.
  • The learning rate sets how much of each tree’s correction is kept: smaller steps need more trees and usually generalise a little better.
  • Too many trees memorise the noise, so hold back a validation set and stop early when it stops improving.

Keep going

Sign in to save your place and keep a learning streak. Free, with Google.