A random forest builds many trees side by side and lets them vote. Gradient boosting builds trees one after another instead. Each new tree studies the mistakes left by the trees before it and fixes a little of them. In this lesson you will boost by hand in a few lines of NumPy, then use scikit-learn’s fast version with early stopping.
In this lesson you will learn
- How boosting differs from bagging and random forests
- What residuals are and why each tree learns them
- What the learning rate and the number of trees do
- How to use
GradientBoostingClassifierandHistGradientBoostingClassifier - How early stopping picks the number of trees for you
You should know decision trees and random forests and mean squared error.
The Idea: Fix the Mistakes, Step by Step
Imagine a team guessing the price of a house. The first person gives a rough guess. The second person does not start again. They look at how far off the first guess was and suggest a correction. A third person corrects what is still wrong, and so on. Each correction is small, but together they get close.
Gradient boosting works the same way. The gap between the true value and the current guess is called the residual. Every new tree is trained to predict the residuals, not the original target. Its answer is added to the running guess, usually scaled down by a learning rate.
Boosting by Hand
Here we fit a wavy curve with tiny trees of depth 2. One such tree alone is a poor model. Watch the training error fall as we add them one at a time.
import numpy as np
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.tree import DecisionTreeRegressor
# Boosting by hand: each small tree learns the mistakes (residuals) of the trees before it
rng = np.random.default_rng(0)
X = np.sort(rng.uniform(0, 10, 80)).reshape(-1, 1)
y = np.sin(X[:, 0]) * 3 + rng.normal(0, 0.3, 80)
pred = np.full_like(y, y.mean()) # step 0: predict the average for everyone
lr = 0.5 # learning rate: take half of each correction
for step in range(1, 6):
residual = y - pred # what we still get wrong
tree = DecisionTreeRegressor(max_depth=2).fit(X, residual)
pred += lr * tree.predict(X) # nudge predictions towards the truth
mse = np.mean((y - pred) ** 2)
print(f"after tree {step}: training MSE = {mse:.3f}")
# scikit-learn does the same thing for us
gbr = GradientBoostingRegressor(n_estimators=5, learning_rate=0.5, max_depth=2,
random_state=0).fit(X, y)
print(f"GradientBoostingRegressor, 5 trees: MSE = {np.mean((y - gbr.predict(X)) ** 2):.3f}")
Output
after tree 1: training MSE = 1.834
after tree 2: training MSE = 1.204
after tree 3: training MSE = 0.781
after tree 4: training MSE = 0.569
after tree 5: training MSE = 0.355
GradientBoostingRegressor, 5 trees: MSE = 0.355
- We start by guessing the average for every point. Then each tree learns
y - pred, the part we still get wrong. - With a learning rate of 0.5 we only take half of each tree’s correction. That sounds wasteful, but small steps make the final model more stable.
- The error drops after every tree. scikit-learn’s
GradientBoostingRegressorwith the same settings gives exactly the same number, so our loop really is gradient boosting.
Why “gradient”?
For squared error, the residual is the direction that lowers the loss fastest, which is the negative gradient. For other losses, such as log loss in classification, the trees learn that gradient instead of a plain residual. The idea is the same as in gradient descent, but each step is a tree.
Learning Rate and Number of Trees
These two settings work as a pair. A big learning rate learns fast but can overshoot. A small one needs more trees but usually ends up better. Too many trees can still overfit, because later trees start learning noise.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.ensemble import GradientBoostingClassifier, HistGradientBoostingClassifier
X, y = make_classification(n_samples=3000, n_features=20, n_informative=8,
flip_y=0.05, random_state=42)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, random_state=42)
# Watch test accuracy as trees are added, for two learning rates
for lr in (1.0, 0.1):
gb = GradientBoostingClassifier(n_estimators=300, learning_rate=lr, max_depth=3,
random_state=0).fit(X_tr, y_tr)
scores = [np.mean(p == y_te) for p in gb.staged_predict(X_te)]
best = int(np.argmax(scores)) + 1
print(f"learning_rate={lr}: best {max(scores):.3f} at {best} trees, "
f"after 300 trees {scores[-1]:.3f}")
# HistGradientBoosting: much faster on big data, with built-in early stopping
hgb = HistGradientBoostingClassifier(max_iter=1000, learning_rate=0.1,
early_stopping=True, validation_fraction=0.1,
n_iter_no_change=20, random_state=0).fit(X_tr, y_tr)
print(f"HistGradientBoosting stopped after {hgb.n_iter_} trees, "
f"test accuracy {hgb.score(X_te, y_te):.3f}")
Output
learning_rate=1.0: best 0.864 at 96 trees, after 300 trees 0.851
learning_rate=0.1: best 0.884 at 141 trees, after 300 trees 0.876
HistGradientBoosting stopped after 115 trees, test accuracy 0.886
staged_predictgives the predictions after 1 tree, 2 trees, and so on. That lets us see the whole path in one fit.- With a learning rate of 1.0, accuracy peaks early and then falls as the model overfits. With 0.1 it climbs more slowly but reaches a higher peak.
HistGradientBoostingClassifierputs each column into at most 255 bins first, which makes it much faster on large data. It also handles missing values without an imputer.- With
early_stopping=Trueit keeps 10% of the training data aside and stops when the score has not improved for 20 rounds. Here it stopped at 115 trees and matched the best result.
Settings That Matter Most
| Setting | What it does | Good start |
|---|---|---|
learning_rate | Size of each correction | 0.05 to 0.1 |
max_iter / n_estimators | Most trees allowed | Large, with early stopping |
max_depth / max_leaf_nodes | Size of each tree | Depth 3 to 6, or 31 leaves |
min_samples_leaf | Smallest group a leaf may hold | 20 or more on noisy data |
l2_regularization | Shrinks leaf values | 0 to 1 |
Popular libraries such as XGBoost, LightGBM and CatBoost use the same core idea with extra speed tricks. If you understand the loop above, you understand them too. To tune these settings, see hyperparameter tuning.
Boosting vs Random Forest
| Random forest | Gradient boosting | |
|---|---|---|
| How trees are built | Side by side, independent | One after another |
| Tree size | Deep trees | Small trees |
| Main risk | Slightly lower top score | Overfitting if not tuned |
| Tuning needed | Very little | Some: rate, trees, depth |
Common Mistakes
- Using a high learning rate to save time. It often gives a worse model. Lower the rate and let early stopping choose the tree count.
- Growing deep trees. Boosting needs weak, small trees. Deep trees make each step too strong and overfit quickly.
- Picking the tree count from the test set. Use early stopping or cross-validation, so the test set stays unseen.
- Using the slow version on big data. On more than about 10,000 rows, prefer
HistGradientBoostingClassifier.
Practice Exercises
Exercise 1. In gb1.py, change the learning rate to 1.0. Does the training error fall faster or slower? Is that good news?
Show answer
It falls faster, because each tree’s full correction is used. But training error is not the goal. A fast drop on training data often means the model will overfit sooner, as the 1.0 line in gb2.py shows.
Exercise 2. Why does boosting use small trees, while a random forest uses deep ones?
Show answer
A forest averages many deep trees to cancel out their noise. Boosting adds trees together, so each one must be weak. Small trees make small corrections, and many small corrections build a strong model without jumping to fit noise.
Frequently Asked Questions
Is gradient boosting better than a random forest?
On many tables of data, a well-tuned boosting model scores a little higher. A random forest is easier to use and harder to break. Try both with cross-validation and keep the one that wins on your data.
Do I need to scale features for gradient boosting?
No. Trees split on thresholds, so the scale of a column does not matter. You can skip StandardScaler for boosting models.
Should I use XGBoost or scikit-learn?
Start with HistGradientBoostingClassifier from scikit-learn. It is fast and needs no extra install. Move to XGBoost, LightGBM or CatBoost if you need their special features or a little more speed.
Summary
- Boosting builds trees one after another, each fixing the errors left so far.
- Each tree learns the residuals, and a learning rate scales its step.
- A lower learning rate with more trees usually generalises better.
- Use
HistGradientBoostingClassifierwith early stopping as your default.
Next: AdaBoost in Python.
