Bagging and Out-of-Bag Error
A deep decision tree has low bias and high variance: it fits its training set closely, and a slightly different training set gives a very different tree. Averaging is the classic cure for variance: the average of many noisy measurements is less noisy than any one of them. But you have only one training set. Bagging (bootstrap aggregating, Leo Breiman, 1996) manufactures many training sets from the one you have, fits a model on each and averages their predictions. The Machine Learning course shows BaggingClassifier at work; here you build it and measure the variance it removes.
The bootstrap
A bootstrap sample draws rows from the training rows with replacement. Some rows appear twice or more, others not at all. The chance that a given row is never drawn is
so each bootstrap sample contains about 63.2 % of the distinct rows. The rows a model never saw are its out-of-bag (OOB) rows, a free validation set for that model.
Why averaging helps
Suppose models each have prediction variance and every pair has correlation . The variance of their average is
The second term vanishes as grows; the first does not. Averaging removes the part of the variance in which the models disagree, and leaves the part they share. Bootstrap samples overlap heavily, so bagged trees remain correlated, which is the gap random forests attack next. The bias is not reduced: averaging models that are all wrong in the same way does not fix them. That is why bagging uses deep, low-bias trees. (Covariance and Correlation has the variance of a sum.)
Bagging from scratch
A generated classification problem (600 rows, 20 features, 6 informative, 5 % of labels flipped) with 100 unpruned trees, each fitted on its own bootstrap sample. Every tree also predicts its own out-of-bag rows, and those votes give the OOB estimate:
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import BaggingClassifier
X, y = make_classification(n_samples=600, n_features=20, n_informative=6, flip_y=0.05, random_state=0)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)
n = len(y_tr)
rng = np.random.default_rng(0)
B = 100
votes_te = np.zeros((len(y_te), 2))
oob_votes = np.zeros((n, 2))
single_scores = []
for b in range(B):
idx = rng.integers(0, n, n) # bootstrap: n draws with replacement
oob = np.setdiff1d(np.arange(n), idx) # rows this tree never saw
tree = DecisionTreeClassifier(random_state=b).fit(X_tr[idx], y_tr[idx])
votes_te[np.arange(len(y_te)), tree.predict(X_te)] += 1
oob_votes[oob, tree.predict(X_tr[oob])] += 1
single_scores.append(tree.score(X_te, y_te))
if b == 0:
print("first bootstrap: distinct rows", len(np.unique(idx)), "of", n, f"({len(np.unique(idx)) / n:.1%})")
has_oob = oob_votes.sum(axis=1) > 0
print("single trees, test accuracy: mean", round(np.mean(single_scores), 3), " min", round(min(single_scores), 3), " max", round(max(single_scores), 3))
print("bag of 100, test accuracy:", round(np.mean(votes_te.argmax(axis=1) == y_te), 3))
print("bag of 100, OOB estimate: ", round(np.mean(oob_votes[has_oob].argmax(axis=1) == y_tr[has_oob]), 3))
sk = BaggingClassifier(DecisionTreeClassifier(), n_estimators=100, oob_score=True, random_state=0).fit(X_tr, y_tr)
print("BaggingClassifier: test", round(sk.score(X_te, y_te), 3), " OOB", round(sk.oob_score_, 3))first bootstrap: distinct rows 273 of 420 (65.0%)
single trees, test accuracy: mean 0.774 min 0.717 max 0.861
bag of 100, test accuracy: 0.867
bag of 100, OOB estimate: 0.819
BaggingClassifier: test 0.861 OOB 0.819
The first bootstrap sample contains 273 of the 420 rows (65.0 %, near the expected 63.2 %). Single trees score anywhere from 0.717 to 0.861 on the 180 test rows, 0.774 on average; their majority vote scores 0.867, better than the average tree by 9 points and as good as the luckiest one. The OOB estimate (0.819) comes from the training data alone. It is 0.048 below the test score, less than two standard errors of an accuracy measured on 180 rows (one standard error is about ); it is also slightly pessimistic by design, since each row is voted on by only the third of the trees that left it out. scikit-learn's BaggingClassifier, with its own random bootstrap draws, gives similar numbers.
Measuring bias and variance directly
The decomposition from polynomial regression can be measured by refitting on many independent training sets of the same size and looking at how the predictions spread at fixed test points:
import numpy as np
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import BaggingRegressor
rng = np.random.default_rng(1)
x_test = np.linspace(0, 1, 50)[:, None]
truth = np.sin(2 * np.pi * x_test[:, 0])
def variance_over_datasets(make_model, runs=30):
preds = []
for r in range(runs): # 30 independent training sets
x = rng.uniform(0, 1, (40, 1))
y = np.sin(2 * np.pi * x[:, 0]) + rng.normal(scale=0.3, size=40)
preds.append(make_model(r).fit(x, y).predict(x_test))
preds = np.array(preds)
bias2 = np.mean((preds.mean(axis=0) - truth) ** 2)
var = np.mean(preds.var(axis=0))
return bias2, var
for name, make in [("one deep tree", lambda r: DecisionTreeRegressor(random_state=r)),
("bag of 50 deep trees", lambda r: BaggingRegressor(DecisionTreeRegressor(), n_estimators=50, random_state=r))]:
b2, v = variance_over_datasets(make)
print(f"{name:21s} bias^2 {b2:.3f} variance {v:.3f} sum {b2 + v:.3f}")one deep tree bias^2 0.006 variance 0.099 sum 0.104
bag of 50 deep trees bias^2 0.005 variance 0.047 sum 0.052
Bagging leaves the (small) bias as it was and halves the variance, from 0.099 to 0.047. It does not remove it all: the 50 trees share most of their training rows, so they are correlated (the term).
Hyperparameters
| Hyperparameter | Effect |
|---|---|
n_estimators |
more is never worse for accuracy, only slower; gains flatten after 50 to 500 |
max_samples |
size of each bootstrap sample (default ) |
max_features |
each model sees a random subset of features (random subspaces) |
bootstrap=False |
sample without replacement (pasting) |
oob_score=True |
compute the OOB estimate |
Strengths, weaknesses, when to use it
Bagging is simple, parallel (each model trains independently), and turns an unstable model into a stable one, with a built-in validation estimate. It does little for stable, high-bias models (bagging linear regression barely changes anything), costs times the training and prediction time, and loses the single tree's readability. Use it to stabilise any high-variance learner; for trees, a random forest is almost always the better version.
Pitfalls
- Bagging a stable model. Averaging near-identical linear fits is wasted work.
- Treating OOB as a test score after tuning on it. Once you choose hyperparameters by OOB score, it is a validation score.
- Grouped or time-ordered data. Bootstrap rows from the same patient or neighbouring days make OOB rows not truly unseen.
Practice
- With rows, what is the exact probability that a given row is out of bag?
Answer
, already close to the limit .
- Using the variance formula, 100 models with and : what is the variance of their average, and what if ?
Answer
; as it tends to . Adding models stops helping; only lowering helps further.
Test yourself
What fraction of the distinct training rows does a bootstrap sample contain on average, for large ?
- about 37 %
- about 50 %
- about 63 %
- 100 %
Which part of the error does bagging mainly reduce?
- bias
- variance
- the noise
- all three equally
Why is the out-of-bag estimate a fair estimate of generalisation?
- It uses the test set
- Each row is predicted only by models that did not train on it
- It averages training accuracy
- It uses cross-validation folds