Sub topic 15
Where Trees Go Next: Random Forests and Boosting
This chapter assumes you can fit a scikit-learn decision tree and read cross-validation scores. It also assumes you know why a deep tree overfits, and that you understand the variance of a model. If those ideas are shaky, review the chapters on overfitting and pruning first.
Why a single tree is not enough
A fully grown tree has low bias but high variance. A small change in the training data can move an early split, and everything below that split changes with it. Axis-aligned splits also approximate diagonal boundaries with staircases, and predictions are piecewise constant.
Pruning reduces variance by making one tree simpler, which often adds bias. Ensembles take a different route. They train many trees and combine their predictions. Two families dominate:
- Bagging and random forests train deep trees independently and average them. This mainly reduces variance.
- Boosting trains shallow trees one after another, each correcting the errors of the ensemble so far. This mainly reduces bias.
Bagging: averaging away variance
Bagging is short for bootstrap aggregating. It works in three steps:
- Draw a bootstrap sample from the training set. This means sampling n rows with replacement, so some rows repeat and about 37% are left out.
- Fit a deep tree on that sample.
- Repeat B times. Predict by majority vote (classification) or by the mean (regression).
Averaging B models whose errors are independent with variance σ² gives variance σ²/B. Trees trained on overlapping samples are correlated, so the real gain is smaller. If the pairwise correlation is ρ, the variance of the average is ρσ² + (1 − ρ)σ²/B. Adding trees shrinks the second term only. The first term, ρσ², remains.
The next section targets that remaining term.
Random forests: decorrelating the trees
A random forest is bagging plus one change. At every split, the tree considers only a random subset of the features, not all of them. In scikit-learn this is max_features. The usual defaults are "sqrt" for classification and all features (1.0) for regression.
Without this change, one strong feature wins the root split in nearly every bootstrap tree, and the trees look alike. Restricting the candidates forces some trees to use other features, which lowers ρ. Each tree is a bit worse on its own, but the average is better.
The leftover rows of each bootstrap sample give a free validation set. This is the out-of-bag (OOB) estimate: each row is scored using only the trees that did not see it.
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import (
BaggingClassifier,
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),
"bagged trees": BaggingClassifier(
estimator=DecisionTreeClassifier(), n_estimators=200, random_state=0
),
"random forest": RandomForestClassifier(n_estimators=200, random_state=0),
"gradient boosting": GradientBoostingClassifier(
n_estimators=200, learning_rate=0.1, max_depth=3, random_state=0
),
}
for name, model in models.items():
scores = cross_val_score(model, X, y, cv=5)
print(f"{name:18s} mean={scores.mean():.3f} std={scores.std():.3f}")
forest = RandomForestClassifier(n_estimators=200, oob_score=True, random_state=0)
forest.fit(X, y)
print("OOB accuracy:", round(forest.oob_score_, 3))On a dataset like this one, you should expect the three ensembles to beat the single tree and to have a smaller standard deviation across folds. Exact numbers depend on your scikit-learn version. The OOB accuracy should land close to the cross-validated forest score, without a separate validation split.
Forest hyperparameters
| Parameter | Effect | Practical guidance |
|---|---|---|
| `n_estimators` | Number of trees | More trees never overfit by themselves. Returns flatten, so pick a number where the OOB score stops improving. |
| `max_features` | Features tried per split | The main tuning knob. Smaller values give less correlation but weaker trees. |
| `max_depth`, `min_samples_leaf` | Size of each tree | Forests tolerate deep trees. Raise `min_samples_leaf` if the model is too slow or too large. |
| `max_samples` | Bootstrap sample size | Smaller values speed up training and add diversity. |
| `class_weight` | Reweights classes | Useful for imbalanced labels. |
Boosting: fitting the mistakes
Boosting builds the model in stages. Start with a constant prediction. At each stage, fit a small tree to what the current ensemble gets wrong, then add that tree with a small weight.
For squared error, "what it gets wrong" is the residual y − F(x). Gradient boosting generalizes this idea. Each new tree fits the negative gradient of the loss, which for squared error equals the residual. For log loss, it equals a difference between the label and the predicted probability. The update is:
Fm(x) = F{m−1}(x) + η · h_m(x)
Here h_m is the new shallow tree and η is the learning rate (also called shrinkage). A small η, such as 0.05 to 0.1, makes each tree contribute little. That needs more trees, but it generalizes better.
The trees in boosting are weak on purpose, usually depth 3 to 8. Each one adds a small correction, so the ensemble reduces bias step by step.
Why boosting can overfit
Unlike a forest, a boosted model does overfit as you add trees. Training loss keeps falling, and eventually the model starts fitting noise. Three controls matter:
- Number of trees against learning rate. Lower the rate and raise the tree count together.
- Tree depth (
max_depth, ormax_leaf_nodes). Deeper trees allow higher-order feature interactions. - Subsampling. Using a fraction of rows per tree (
subsample < 1) adds randomness and often helps.
The cleanest control is early stopping. Hold out part of the training data and stop when its loss stops improving.
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.model_selection import train_test_split
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=0, stratify=y
)
hgb = HistGradientBoostingClassifier(
max_iter=500,
learning_rate=0.05,
early_stopping=True,
validation_fraction=0.1,
n_iter_no_change=10,
random_state=0,
)
hgb.fit(X_train, y_train)
print("trees actually built:", hgb.n_iter_)
print("test accuracy:", round(hgb.score(X_test, y_test), 3))The model is allowed up to 500 iterations but usually stops far earlier. HistGradientBoostingClassifier bins features into histograms first, so it is much faster than GradientBoostingClassifier on large tables. The libraries XGBoost, LightGBM, and CatBoost follow the same idea with their own optimizations.
Choosing between forest and boosting
| Question | Random forest | Gradient boosting |
|---|---|---|
| Training | Trees are independent, so it parallelizes easily | Trees are sequential, so each stage must wait for the last |
| Main effect | Lowers variance | Lowers bias |
| Tuning effort | Low. Defaults are often good | Higher. Learning rate, depth, and tree count interact |
| Overfitting with more trees | Does not overfit from tree count | Can overfit without early stopping |
| Noisy labels | Fairly robust | More sensitive, since it keeps chasing errors |
| Typical accuracy on tabular data | Strong | Often a little stronger after tuning |
A reasonable workflow is to start with a forest as a baseline, because it needs little tuning and its OOB score is free. Then try boosting with early stopping if you need the last bit of accuracy.
What you lose: interpretability
A single tree reads as a short list of rules. A forest of 200 trees does not. Neither does a boosted model of hundreds of stages. Some tools recover part of the picture:
- Impurity-based importances (
feature_importances_) carry over from single trees, averaged across the ensemble. They keep the caveats you saw earlier. They favor high-cardinality and continuous features, and they are computed on training data. - Permutation importance (
sklearn.inspection.permutation_importance) shuffles one feature on held-out data and measures the drop in score. It is usually more trustworthy. - Partial dependence plots show how the average prediction changes as one feature varies.
Common errors
- Tuning a forest's
n_estimatorsas if it were a complexity knob. More trees only reduce noise in the average. Complexity comes from tree depth andmax_features. - Evaluating on rows the model trained on. A deep forest scores near 100% on its own training data. Use cross-validation or the OOB score.
- Using a large learning rate with many trees. This overfits quickly. Lower the rate first, then use early stopping to set the tree count.
- Leaking through early stopping. The validation set used to stop is not a clean test set. Keep a separate test split for the final number.
- Expecting ensembles to extrapolate. Trees predict averages of training targets, so regression forests and boosted trees flatten outside the training range.
Exercise
A random forest of 500 trees gets 0.94 cross-validated accuracy. A colleague proposes raising n_estimators to 5000 to "fix overfitting". Would you expect this to help? What would you try instead?
Show answer
It is unlikely to help much. Tree count only reduces the noise in the average, and the gain flattens after a few hundred trees. A forest does not overfit more as trees are added, so more trees will not fix overfitting either. Try lowering max_depth or raising min_samples_leaf to simplify each tree, and tune max_features to change how correlated the trees are. Compare the OOB or cross-validated score for each setting.
Exercise
You train a gradient boosting model with learning_rate=0.5 and 1000 trees. Training accuracy is 100% and validation accuracy is falling. Name two changes that should reduce the overfitting, and explain why each one works.
Show answer
Lower the learning rate (for example to 0.05) and enable early stopping on a validation split. A smaller rate makes each tree's correction small, so the model fits the signal gradually instead of chasing noise, and early stopping ends training once validation loss stops improving. Other valid answers are to reduce tree depth, which limits the interactions each tree can fit, or to set subsample below 1, which adds randomness across stages.
Exercise
In bagging, the variance of the averaged prediction is ρσ² + (1 − ρ)σ²/B. If ρ = 0.6 and σ² = 1, what is the variance when B = 10 and when B = 1000? What does the result say about why random forests restrict features at each split?
Show answer
For B = 10: 0.6 + 0.4/10 = 0.64. For B = 1000: 0.6 + 0.4/1000 = 0.6004. Adding trees barely helps once B is large, because the correlation term ρσ² dominates. Restricting features at each split lowers ρ, which is the only way to reduce that remaining term.