Sub topic 5
Bagging: training on resampled data
This chapter assumes you know how a decision tree is grown and why a fully grown tree overfits (high variance). It also assumes you know what a bootstrap sample is: n rows drawn with replacement from n rows. You should be comfortable with NumPy and with scikit-learn's fit and predict interface.
The idea
You cannot collect a new training set each time you want another model. You have one dataset. Bagging, short for bootstrap aggregating, gets around this by treating the bootstrap as a stand-in for new datasets.
The procedure has three steps:
- Draw B bootstrap samples from the training set. Each has the same size as the original.
- Fit one model, here a decision tree, on each bootstrap sample.
- Combine the B predictions into one. For classification this is a vote. For regression it is an average. The next chapter covers the details of combining.
Each tree sees a slightly different version of the data, so each tree makes slightly different mistakes. If the mistakes are partly independent, averaging cancels some of them.
What each tree actually sees
A bootstrap sample of n rows is drawn with replacement. The chance that a given row is never picked in one draw is 1 - 1/n. Over n draws, the chance that the row is missing from the sample is (1 - 1/n)^n. This value approaches 1/e, about 0.368, as n grows.
| Training rows n | Expected fraction of distinct rows in a bootstrap sample |
|---|---|
| 10 | 0.651 |
| 100 | 0.634 |
| 1000 | 0.632 |
So each tree trains on about 63.2% of the distinct rows. Some of those rows appear two or three times. The remaining 36.8% are left out of that tree. These left-out rows are called out-of-bag rows, and a later chapter uses them as a free validation set.
Two consequences follow:
- Each tree is trained on less distinct information than the full dataset. A single bagged tree is therefore usually a little worse than a tree fit on all the data.
- The trees differ only because their samples differ. If the data has a very strong signal, many trees will still choose the same splits.
Why averaging reduces variance
Suppose you have B models. Each makes a prediction with variance σ². Let ρ be the average pairwise correlation between their predictions. The variance of their average is:
Var(average) = ρσ² + (1 - ρ)σ² / B
The formula has two terms:
- The second term, (1 - ρ)σ² / B, shrinks as you add models. This is the part that adding trees fixes.
- The first term, ρσ², does not depend on B. It is a floor set by how correlated the models are.
The table gives the variance of the average for σ² = 1.
| Correlation ρ | B = 1 | B = 10 | B = 100 |
|---|---|---|---|
| 0.0 | 1.000 | 0.100 | 0.010 |
| 0.3 | 1.000 | 0.370 | 0.307 |
| 0.8 | 1.000 | 0.820 | 0.802 |
With uncorrelated models, 100 of them cut the variance by a factor of 100. With ρ = 0.8, 100 models barely help. The lesson is that bagging works to the extent that the bagged models are decorrelated.
You can check the formula by simulation. This script draws correlated Gaussian "predictions", averages them, and compares the measured variance to the formula.
import numpy as np
rng = np.random.default_rng(0)
sigma2 = 1.0
for rho in [0.0, 0.3, 0.8]:
for B in [1, 10, 100]:
cov = np.full((B, B), rho * sigma2)
np.fill_diagonal(cov, sigma2)
samples = rng.multivariate_normal(np.zeros(B), cov, size=20000)
empirical = samples.mean(axis=1).var()
theory = rho * sigma2 + (1 - rho) * sigma2 / B
print(f"rho={rho:.1f} B={B:>3} empirical={empirical:.3f} theory={theory:.3f}")The empirical and theoretical columns should agree to about two decimal places.
What bagging does to bias and variance
Averaging does not change the expected prediction of the models. If every tree has the same expected prediction, so does their average. This has two effects:
- Bias stays about the same. It can go up slightly, because each tree sees only about 63% of the distinct rows.
- Variance goes down, as the formula above shows.
This is why bagging is applied to deep, unpruned trees. A deep tree has low bias and high variance. Bagging removes much of the variance and keeps the low bias. Bagging shallow trees (stumps) is much less useful, because their error is mostly bias and averaging does not remove bias.
The same reasoning explains which learners benefit. Bagging helps unstable learners, whose predictions change a lot when the training data changes slightly. Decision trees are the standard example. A stable learner such as linear regression with few features gives nearly the same model on every bootstrap sample, so the average equals any single model and nothing is gained.
Bagging with scikit-learn
BaggingClassifier implements the procedure for any base estimator. The next example compares one fully grown tree with a bagged ensemble of 100 such trees, using 5-fold cross-validation.
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import BaggingClassifier
from sklearn.model_selection import cross_val_score
from sklearn.tree import DecisionTreeClassifier
X, y = load_breast_cancer(return_X_y=True)
tree = DecisionTreeClassifier(random_state=0)
bagged = BaggingClassifier(
estimator=DecisionTreeClassifier(),
n_estimators=100,
bootstrap=True,
n_jobs=-1,
random_state=0,
)
for name, model in [("single tree", tree), ("bagged trees", bagged)]:
scores = cross_val_score(model, X, y, cv=5)
print(f"{name}: mean={scores.mean():.3f}, std={scores.std():.3f}")Expect the bagged ensemble to have a higher mean accuracy and a smaller spread across folds than the single tree. The exact numbers depend on your scikit-learn version.
The main parameters are:
n_estimators: the number of bootstrap samples and trees, B.bootstrap: ifTrue(the default), rows are drawn with replacement. IfFalse, rows are drawn without replacement, which is a variant called pasting.max_samples: the size of each sample. A float is a fraction of the training set. The default of 1.0 gives the standard n-row bootstrap.max_features: the fraction of features given to each tree. The default of 1.0 uses all features. This is the hook that connects bagging to random forests, as the next chapter explains.oob_score: whenTruewithbootstrap=True, the estimator computes an out-of-bag score from the left-out rows.
Limits of plain bagging
Bagged trees are still correlated. Suppose one feature is far more informative than the rest. Almost every bootstrap sample still contains enough rows to make that feature the best choice at the root. Nearly all trees will then start with the same split, and the splits below it will often resemble each other too. The correlation ρ stays high, and the floor ρσ² in the variance formula stays high with it.
Bagging also has practical costs:
- Training and prediction cost grow linearly with B. Training parallelizes easily because the trees are independent, but prediction still runs every tree.
- The ensemble is not as easy to read as one tree. You cannot draw one diagram of the decision rules.
- Adding trees past a point stops helping. The second term of the formula shrinks as 1/B, so the curve flattens, but it never reaches zero. More trees do not cause overfitting in the usual sense, but they cost time and memory.
The next chapters address the correlation problem directly. Combining the predictions is covered first. Then random feature subsets are added to make the trees differ more, and that step turns bagged trees into a random forest.
Common errors
- Bagging shallow or high-bias models and expecting large gains. If the model underfits, its error is mostly bias, and averaging cannot fix that.
- Using a stable base learner. Bagged linear models or bagged k-nearest neighbors with large k change very little.
- Forgetting
random_state. Bootstrap draws are random. Without a fixed seed, two runs give different scores, which makes comparisons between settings noisy. - Reading a lower training score as worse. A bagged ensemble is often less perfect on its own training data than a single deep tree, which usually reaches 100%. Judge the model on held-out data or the out-of-bag score.
- Assuming that more trees mean lower error without limit. Beyond a few hundred trees the improvement is usually negligible compared with the cost.
Exercise
Ten trees each have prediction variance σ² = 4, and the average correlation between their predictions is ρ = 0.5. What is the variance of their average with B = 10, and what does it approach as B grows without limit?
Show answer
Var = ρσ² + (1 - ρ)σ² / B = 0.5 × 4 + 0.5 × 4 / 10 = 2 + 0.2 = 2.2. As B grows, the second term goes to zero and the variance approaches ρσ² = 2. More trees cannot push it lower. Only reducing the correlation ρ can.
Exercise
A colleague bags 200 decision stumps (trees with one split) and finds the ensemble is barely better than one stump. Using what you know about bias and variance, explain why, and suggest a change.
Show answer
A stump is a high-bias, low-variance model. Its error comes mostly from being too simple, and averaging models with the same bias leaves that bias unchanged. Bagging mainly reduces variance, so it has little to remove here. Use deeper trees, with low bias and high variance, as the base learner.
Exercise
For a training set of 1000 rows, about how many distinct rows does one bootstrap sample contain, and about how many rows are out of bag for that tree?
Show answer
About 63.2% of 1000, or roughly 632 distinct rows. About 368 rows are out of bag for that tree.