TExcelTAD
Home › Classical ML Algorithms: Supervised & Unsupervised › Bagging and Out-of-Bag Error

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 nn rows from the nn training rows with replacement. Some rows appear twice or more, others not at all. The chance that a given row is never drawn is

(1−1n)n→e−1≈0.368,\Big(1 - \frac{1}{n}\Big)^n \to e^{-1} \approx 0.368,

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 BB models each have prediction variance σ2\sigma^2 and every pair has correlation ρ\rho. The variance of their average is

Var⁡(1B∑b=1Bf^b(x))=ρ σ2+1−ρBσ2.\operatorname{Var}\Big(\frac{1}{B} \sum_{b=1}^{B} \hat{f}_b(\mathbf{x})\Big) = \rho \, \sigma^2 + \frac{1 - \rho}{B} \sigma^2 .

The second term vanishes as BB 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:

python · try it yourself
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 0.84⋅0.16/180≈0.027\sqrt{0.84 \cdot 0.16 / 180} \approx 0.027); 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:

python · try it yourself
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 ρσ2\rho\sigma^2 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 nn)
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 BB 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

  1. With n=5n = 5 rows, what is the exact probability that a given row is out of bag?
Answer

(1−1/5)5=0.85=0.328(1 - 1/5)^5 = 0.8^5 = 0.328, already close to the limit e−1≈0.368e^{-1} \approx 0.368.

  1. Using the variance formula, 100 models with σ2=1\sigma^2 = 1 and ρ=0.5\rho = 0.5: what is the variance of their average, and what if B→∞B \to \infty?
Answer

0.5⋅1+0.5⋅1/100=0.5050.5 \cdot 1 + 0.5 \cdot 1/100 = 0.505; as B→∞B \to \infty it tends to ρσ2=0.5\rho \sigma^2 = 0.5. Adding models stops helping; only lowering ρ\rho helps further.

Test yourself

What fraction of the distinct training rows does a bootstrap sample contain on average, for large nn?

  1. about 37 %
  2. about 50 %
  3. about 63 %
  4. 100 %

Which part of the error does bagging mainly reduce?

  1. bias
  2. variance
  3. the noise
  4. all three equally

Why is the out-of-bag estimate a fair estimate of generalisation?

  1. It uses the test set
  2. Each row is predicted only by models that did not train on it
  3. It averages training accuracy
  4. It uses cross-validation folds