Gradient boosting wins more machine learning competitions on tables of data than any other method, and it powers credit scoring, search ranking, fraud detection and demand forecasting at many large companies. XGBoost, LightGBM and CatBoost are all versions of it.
The idea is simple: build a model one small tree at a time, where each new tree predicts the errors left by all the trees before it. Add enough small corrections, and the model becomes very accurate. This lesson builds gradient boosting by hand in a few lines so you can see exactly how it works, then explains the learning rate, early stopping and the main settings, using scikit-learn's fast HistGradientBoosting models. It follows on from bagging vs boosting.
The idea: fit the leftovers
Imagine guessing house prices:
- Start simple: predict the average price for every house. The errors are large.
- Look at the errors (the residuals: actual minus predicted). Train a small tree to predict them. Maybe it learns "big houses are underpriced by ₹20 lakh".
- Add a fraction of that tree's prediction to the current prediction. The errors shrink a little.
- Repeat: a new tree on the new residuals, and so on, hundreds of times.
Each tree fixes part of what's still wrong. The name comes from maths: the residuals are the direction (the gradient) that reduces the error fastest, so each step is like a step of gradient descent.
Gradient boosting by hand
A noisy curve, so you can see the fit improve:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeRegressor
rng = np.random.default_rng(0)
x = np.sort(rng.uniform(0, 10, 200))
y = np.sin(x) * 3 + x * 0.5 + rng.normal(0, 0.6, 200)
X = x.reshape(-1, 1)
learning_rate = 0.3
prediction = np.full_like(y, y.mean()) # step 1: start with the average
snapshots = {0: prediction.copy()}
for round_number in range(1, 51):
residuals = y - prediction # step 2: what's still wrong
tree = DecisionTreeRegressor(max_depth=2).fit(X, residuals)
prediction += learning_rate * tree.predict(X) # step 3: small correction
if round_number in (1, 5, 50):
snapshots[round_number] = prediction.copy()
if round_number in (1, 5, 20, 50):
print(f"round {round_number:2}: error (RMSE) {np.sqrt(np.mean((y - prediction) ** 2)):.3f}")
round 1: error (RMSE) 1.942
round 5: error (RMSE) 1.008
round 20: error (RMSE) 0.539
round 50: error (RMSE) 0.424
That loop is gradient boosting for regression: about five lines. The error falls steadily as trees are added. Plot the snapshots:
fig, ax = plt.subplots()
ax.scatter(x, y, s=10, color="lightgrey", label="Data")
for rounds, pred in snapshots.items():
ax.plot(x, pred, label=f"After {rounds} trees")
ax.legend()
ax.set_title("Each round of boosting fixes more of the error")
plt.show()
After 0 trees the model is a flat line; after 1 a crude step; after 5 a rough staircase; after 50 it follows the wave closely. Look carefully at the 50-tree line, though: it has started to spike towards individual noisy points, such as near x = 1.2. That's the beginning of overfitting, and it's why the number of trees must be controlled. Each tree has only depth 2 (four leaves), so no single tree could do this alone. Regression metrics explains RMSE.
For classification, the same idea works on the log-odds of the class, as in logistic regression, with the residuals replaced by the gradient of the log loss.
The learning rate
The learning_rate (also called shrinkage) scales each tree's correction. It's the key trade-off in boosting:
| Learning rate | Effect |
|---|---|
| High (0.3–1) | Learns fast with few trees, but overshoots and overfits sooner |
| Low (0.01–0.1) | Needs many more trees, but usually generalises better |
A good rule: use a small learning rate and let early stopping pick the number of trees.
Gradient boosting in scikit-learn
Scikit-learn has two versions. HistGradientBoostingClassifier and HistGradientBoostingRegressor bin the feature values into at most 255 groups, which makes them much faster on large data, and they handle missing values natively. Prefer them over the older GradientBoostingClassifier for anything over about 10,000 rows.
We'll use the adult census dataset: predict whether a person earns more than $50,000 a year from 32,561 records of the 1994 US census. The code downloads it once from the UCI Machine Learning Repository (well under 1 MB) and reuses the file:
Download the data: adult-income.csv (5.3 MB), or from the original source, the UCI Machine Learning Repository. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with
pd.read_csv("adult-income.csv").
import zipfile
import urllib.request
from pathlib import Path
import pandas as pd
url = "https://archive.ics.uci.edu/static/public/2/adult.zip"
path = Path("adult.zip")
if not path.exists():
urllib.request.urlretrieve(url, path)
columns = ["age", "workclass", "fnlwgt", "education", "education-num",
"marital-status", "occupation", "relationship", "race", "sex",
"capital-gain", "capital-loss", "hours-per-week", "native-country", "income"]
with zipfile.ZipFile(path) as z:
adult = pd.read_csv(z.open("adult.data"), header=None, names=columns,
na_values="?", skipinitialspace=True)
X = adult.drop(columns="income")
text_cols = X.select_dtypes("object").columns
X[text_cols] = X[text_cols].astype("category")
y = (adult["income"] == ">50K").astype(int)
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=0)
print(X.shape, f"{y.mean():.1%} earn >50K")
print(len(text_cols), "categorical columns")
(32561, 14) 24.1% earn >50K
8 categorical columns
The file has no header row, so we name the columns ourselves, and missing values are written as "?", which na_values turns into proper missing values. The text columns are converted to pandas category type. Eight columns are categories (education, occupation, and so on) and some have missing values. HistGradientBoosting can handle both directly:
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.metrics import roc_auc_score
hgb = HistGradientBoostingClassifier(categorical_features="from_dtype", random_state=0)
hgb.fit(X_train, y_train)
print("Test accuracy:", round(hgb.score(X_test, y_test), 3))
print("Test ROC AUC: ", round(roc_auc_score(y_test, hgb.predict_proba(X_test)[:, 1]), 3))
Test accuracy: 0.871
Test ROC AUC: 0.926
No encoding, no imputation, no scaling: categorical_features="from_dtype" treats every pandas category column as categorical, and missing values are sent down whichever branch works best at each split. Compare that with the encoding and scaling a linear model would need. ROC AUC measures how well the model ranks high earners above others.
Early stopping
How many trees? Too few underfits, too many overfits. Early stopping holds back part of the training data as a validation set and stops adding trees once the validation score hasn't improved for a while:
hgb_es = HistGradientBoostingClassifier(
learning_rate=0.05, max_iter=2000, early_stopping=True,
validation_fraction=0.1, n_iter_no_change=30,
categorical_features="from_dtype", random_state=0)
hgb_es.fit(X_train, y_train)
print("Trees used:", hgb_es.n_iter_)
print("Test ROC AUC:", round(roc_auc_score(y_test, hgb_es.predict_proba(X_test)[:, 1]), 3))
Trees used: 233
Test ROC AUC: 0.926
Up to 2,000 trees were allowed, but the model stopped at 233 when the validation loss stopped improving. The test score is the same as the default model's, but early stopping found the right number of trees automatically, for a learning rate of our choice. Plot the training and validation loss to see why:
fig, ax = plt.subplots()
ax.plot(-hgb_es.train_score_, label="Training loss")
ax.plot(-hgb_es.validation_score_, label="Validation loss")
ax.set_xlabel("Number of trees")
ax.set_ylabel("Log loss")
ax.set_title("Early stopping: stop when validation stops improving")
ax.legend()
plt.show()
Training loss keeps falling forever, because boosting can always fit the training data more closely. Validation loss levels off, and that's where to stop. (Scikit-learn stores scores, where higher is better, so the code flips the sign to show the loss.)
Important settings
| Setting (scikit-learn name) | What it does | Typical values |
|---|---|---|
learning_rate | Size of each correction | 0.01–0.1 |
max_iter | Maximum number of trees | 100–5,000, with early stopping |
max_leaf_nodes / max_depth | Size of each tree | 15–63 leaves, or depth 3–8 |
min_samples_leaf | Minimum rows per leaf | 20–200 on large data |
l2_regularization | Penalty on leaf values, like ridge | 0–10 |
max_features | Share of features per split, adding randomness | 0.5–1.0 |
Tune in this order: learning rate and number of trees (with early stopping), then tree size, then regularisation. RandomizedSearchCV with a pipeline works well.
Gradient boosting vs random forest
| Random forest | Gradient boosting | |
|---|---|---|
| Trees built | Independently | Sequentially, each fixing the last |
| Tree size | Deep | Shallow |
| Tuning needed | Little | Some (learning rate, trees, depth) |
| Overfitting risk | Low | Higher without early stopping |
| Accuracy on tabular data | Very good | Usually the best |
| Missing values and categories | Need preparation in scikit-learn | Handled by HistGradientBoosting |
Strengths and weaknesses
| Strengths | Weaknesses |
|---|---|
| Usually the most accurate model for tabular data | More settings to tune than a random forest |
| Handles mixed types, missing values and interactions | Can overfit noisy data without early stopping |
| No scaling needed | Sequential, so training can't be fully parallel |
| Fast with histogram-based implementations | Less interpretable; can't extrapolate beyond the training range |
For very large datasets or the last few points of accuracy, the specialised libraries help: see XGBoost vs LightGBM vs CatBoost.
Practice
- In the hand-built example, change
learning_rateto 1.0 and then 0.05. How does the RMSE after 50 rounds change?
Show the answer
With 1.0 the error falls much faster at first and ends lower on the training data, because it fits the noise more aggressively. With 0.05, 50 rounds are not enough and the error is still high: a small learning rate needs more trees.
- Why does training loss always keep falling in boosting, and what does that mean for choosing the number of trees?
Show the answer
Each new tree fits the remaining training errors, so training loss keeps falling, eventually fitting the noise. The number of trees must be chosen on validation data, for example with early stopping.
- Train
HistGradientBoostingClassifier(max_leaf_nodes=4)on the adult data. Is it better or worse than the default of 31 leaves?
Show the answer
m = HistGradientBoostingClassifier(max_leaf_nodes=4, categorical_features="from_dtype", random_state=0)
m.fit(X_train, y_train)
print(roc_auc_score(y_test, m.predict_proba(X_test)[:, 1]))
Slightly worse: a test ROC AUC of about 0.915 against 0.926. Tiny trees capture fewer interactions between features, so with the same number of rounds they learn less.
Interview questions
How does gradient boosting work?
It builds an additive model sequentially. Starting from a constant prediction, each new shallow tree is fitted to the negative gradient of the loss (the residuals for squared error) with respect to the current predictions, and its output, scaled by a learning rate, is added to the model.
What is the role of the learning rate in gradient boosting?
It shrinks each tree's contribution. Smaller values require more trees but usually generalise better, because the model approaches the fit gradually. It is tuned together with the number of trees.
How do you prevent gradient boosting from overfitting?
Use early stopping on a validation set, a lower learning rate, shallower trees, minimum samples per leaf, L2 regularisation, and row or feature subsampling.
What to learn next
- Compare the three most popular libraries in XGBoost vs LightGBM vs CatBoost.
- Revisit bagging vs boosting.