Sub topic 15
Where trees go next: random forests and boosting
This chapter assumes you can fit and cross-validate a scikit-learn tree. It also assumes you know that a deep tree has low bias and high variance. The earlier chapters on overfitting and on the limits of single trees cover those points.
The problem ensembles solve
A single deep tree fits its training data closely. A small change in that data can produce a very different tree. This is high variance. A shallow tree has the opposite problem. It is stable but too simple, which is high bias.
An ensemble combines many trees so that their errors partly cancel. Two strategies dominate. Bagging reduces variance. Boosting reduces bias.
Bagging and random forests
Bagging is short for bootstrap aggregating. It works in three steps:
- Draw a bootstrap sample of the training rows. This means sampling with replacement, to the same size as the original.
- Fit one deep tree on each sample.
- Combine the trees. For classification, take a majority vote. For regression, average the predictions.
Averaging many noisy but roughly unbiased models lowers variance. It only helps much if the trees make different mistakes. Bootstrap trees are still correlated, because a few strong features dominate the top splits in all of them.
A random forest adds one more step. At every split, the tree considers only a random subset of the features. In scikit-learn this is max_features, and the classifier's default is the square root of the feature count. This makes the trees less alike, so averaging them helps more.
Each bootstrap sample leaves out about 37% of the rows. Those rows are "out of bag" for that tree. You can score the forest on them without a separate validation set by passing oob_score=True.
Boosting
Boosting builds trees one after another, and each tree corrects the ones before it. In gradient boosting, the ensemble starts with a constant prediction. Each new shallow tree is fitted to the current errors, which are the negative gradient of the loss. Its output is added to the ensemble after being scaled by a learning rate.
The weak learners are usually shallow, with depth 1 to 4. Individually they have high bias. The sequence of corrections reduces it.
Comparing them in code
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier
from sklearn.model_selection import cross_val_score
from sklearn.tree import DecisionTreeClassifier
X, y = load_breast_cancer(return_X_y=True)
models = {
"single tree": DecisionTreeClassifier(random_state=0),
"random forest": RandomForestClassifier(n_estimators=200, random_state=0),
"gradient boosting": GradientBoostingClassifier(
n_estimators=200, learning_rate=0.1, max_depth=2, random_state=0
),
}
for name, model in models.items():
scores = cross_val_score(model, X, y, cv=5)
print(f"{name}: {scores.mean():.3f} +/- {scores.std():.3f}")The ensembles usually score higher than the single tree and vary less between folds. Exact numbers depend on your scikit-learn version.
Trade-offs
| Aspect | Random forest | Gradient boosting |
|---|---|---|
| Main effect | Lowers variance | Lowers bias |
| Tree depth | Deep | Shallow |
| Training | Parallel | Sequential |
| Tuning sensitivity | Low | High |
| Overfitting risk | Low as trees are added | Rises if you add too many trees or use a high learning rate |
Boosting needs more care. The key hyperparameters are n_estimators, learning_rate, and max_depth. A smaller learning rate needs more trees but usually generalizes better. Use cross-validation or early stopping to choose the number of trees.
Libraries such as XGBoost, LightGBM, and CatBoost are optimized implementations of gradient boosting. They are often the first choice for tabular data.
Exercise
A random forest of 500 fully grown trees still overfits slightly. Name one hyperparameter change that makes the individual trees more different from each other, and explain why that helps.
Show answer
Lower max_features, so each split sees fewer candidate features. This makes the trees less correlated. Averaging less correlated predictions removes more variance than averaging near-identical ones.
Exercise
In gradient boosting, what does each new tree get fitted to, and why are the trees kept shallow?
Show answer
Each tree is fitted to the errors (the negative gradient of the loss) left by the current ensemble. Shallow trees are weak learners, so each step makes a small correction. This lowers bias gradually and limits overfitting.