Skip to content

Gradient boosting

Add small trees one at a time, each fixing what the model still gets wrong. See why boosting attacks bias, why it can overfit, and how learning rate and rounds trade.

Applied ~12 min8 steps

What runs in CodeSplash

You will be able to

  • Describe boosting as fitting each tree to current errors
  • Contrast boosting and bagging by which error each removes
  • Trade learning rate against the number of rounds

Read first

01

One correction at a time

Read

Gradient boostingGradient boostingAdds small trees in sequence, each fitted to the loss's gradient at the current prediction. builds a sum of small trees:

Fm(x)=Fm−1(x)+ν hm(x)F_m(x) = F_{m-1}(x) + \nu\, h_m(x)

For squared error, each tree hmh_m fits the current residuals. For any other loss it fits the loss's gradient, so each tree is a downhill step. ν\nu is the learning rate: only part of each correction is kept.

Weak trees, each adding a little. No tree is good on its own, but the sum can be very good.

02

Bagging or boosting?

Predict

Predict first

You keep adding trees, far past the point where error stopped improving. For which method can error on new data start to rise?

Bagging: more trees never hurtBoosting: more trees can hurtBoth level off the same way
Reveal

Boosting. Each new tree fits what's left, and eventually what's left is noise. Bagging averages independent-ish trees, so its error levels off and stays there. Boosting's number of rounds is a real hyperparameter, and early stopping exists for this reason.

03

Race them

Explore

Set Trees so far to the maximum and read Best tree count. Now lower Learning rate (boosting) and watch the best count rise. Then press boost fast and deep.

DExplorable · Bagging and boosting

How do many weak trees combine into a strong model?

With up to 200 trees available, at how many trees will error on new data be lowest?

101
How sure?

Method

25
0.20
2
0.35
80
Simulating…

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

The check asks you to stop within 10% of the lowest new-data error, using no more than 50 trees. Which settings let you do that?

04

Which error does it remove?

Read
Bagging and forestsBoosting
TreesDeepShallow
BuiltIndependentlyIn sequence
Attacks mostlyVarianceBias
More treesHarmlessCan overfit

Boosting often wins on tabular data because it lets you start simple and add only what's needed. But it isn't a law. On Pima it scores 0.843, and logistic regression 0.857. On ozone, boosting has RMSE 18.2 and a forest 19.0.

05

Rate and rounds trade

Read

Halve the learning rate and you need about twice the rounds, for the same fit or a slightly better one. So fix one and search the other: a common recipe is a small rate, many rounds and early stopping.

Row and column subsampling add a dash of bagging's benefit. So does a stronger penalty. The next lesson on controls has the details.

06

Check your understanding

Checkpoint

Check yourself

With squared-error loss, what does each new tree fit?

Show the answer

Answer: a

Residuals are the negative gradient of squared error. Other losses replace them with their own gradients.

Check yourself

Current prediction 10, actual 15, learning rate 0.4. The next tree predicts the residual exactly. What's the new prediction?

Show the answer

Answer: 12

10+0.4×(15−10)=1210 + 0.4 \times (15 - 10) = 12. Only part of the correction is kept, so the next tree still has something to do.

Check yourself

You lower the learning rate from 0.3 to 0.03. What must also change?

Show the answer

Answer: a

Smaller steps need more of them. With rounds fixed, you'll underfit.

07

Train it

In the app

In the Learners step, select XGBoost and open Hyperparameters. Change Boosting rounds, Learning rate (eta) and Maximum depth. Its card mentions handles missing values and TreeSHAP, so Explain gives exact contributions. Python and R run the same core on the same folds, so their predictions agree to floating-point precision.

Python
import pandas as pd
from sklearn.model_selection import StratifiedKFold, cross_val_score
from xgboost import XGBClassifier

df = pd.read_csv("pima.csv")
X, y = df.drop(columns="diabetic"), df["diabetic"]
cv = StratifiedKFold(5, shuffle=True, random_state=1)
for rate, rounds in [(0.3, 20), (0.1, 60), (0.03, 200)]:
    m = XGBClassifier(n_estimators=rounds, learning_rate=rate, max_depth=3)
    print(rate, rounds, cross_val_score(m, X, y, cv=cv, scoring="roc_auc").mean().round(3))
R
library(xgboost)
df <- rbind(MASS::Pima.tr, MASS::Pima.te)
X <- as.matrix(df[, setdiff(names(df), "type")])
y <- as.numeric(df$type == "Yes")
set.seed(1)
fold <- sample(rep(1:5, length.out = nrow(X)))
for (cfg in list(c(0.3, 20), c(0.1, 60), c(0.03, 200))) {
  auc <- sapply(1:5, function(k) {
    fit <- xgb.train(list(learning_rate = cfg[1], max_depth = 3, objective = "binary:logistic"),
                     xgb.DMatrix(X[fold != k, ], label = y[fold != k]), nrounds = cfg[2], verbose = 0)
    as.numeric(pROC::auc(y[fold == k], predict(fit, X[fold == k, ]), quiet = TRUE))
  })
  cat(cfg, round(mean(auc), 3), "\n")
}
08

Recap

Recap
  • Boosting adds shallow trees in sequence, each correcting the errors so far.
  • It mainly reduces bias, and more rounds can overfit, unlike bagging.
  • Learning rate and rounds trade: a smaller rate needs proportionally more rounds.

Concepts in this lesson