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.
What runs in CodeSplash
- XGBoost Verified in Python and R
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
One correction at a time
ReadGradient boostingGradient boostingAdds small trees in sequence, each fitted to the loss's gradient at the current prediction. builds a sum of small trees:
For squared error, each tree fits the current residuals. For any other loss it fits the loss's gradient, so each tree is a downhill step. 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.
Bagging or boosting?
PredictPredict first
You keep adding trees, far past the point where error stopped improving. For which method can error on new data start to rise?
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.
Race them
ExploreSet 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?
Method
Commit your prediction above to see the result
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?
Which error does it remove?
Read| Bagging and forests | Boosting | |
|---|---|---|
| Trees | Deep | Shallow |
| Built | Independently | In sequence |
| Attacks mostly | Variance | Bias |
| More trees | Harmless | Can 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.
Rate and rounds trade
ReadHalve 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.
Check your understanding
CheckpointCheck 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
. 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.
Train it
In the appIn 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.
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))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")
}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