Sub topic 5
Bagging: training on resampled data
This chapter assumes you know how a decision tree is trained, why a fully grown tree has high variance, and what a bootstrap sample is. You should also be comfortable with NumPy and scikit-learn's fit and predict.
The idea
Bagging is short for bootstrap aggregating. You train many models of the same kind, each on a different bootstrap sample of the training set. Then you combine their predictions. The variation between the resampled datasets makes each model differ from the others. Averaging the models cancels part of their individual errors.
The procedure has three steps:
- Draw a bootstrap sample of size n from the n training rows, sampling with replacement.
- Fit one model on that sample.
- Repeat B times, then combine the B predictions.
Combining the predictions is covered in the next chapter. This chapter focuses on the resampling.
Why it reduces variance
A fully grown tree is a high-variance model. A small change in the training data can produce a very different tree. Bagging uses that instability on purpose. Each bootstrap sample is a slightly different version of the data, so each tree is different.
If you average B models whose predictions each have variance σ² and pairwise correlation ρ, the variance of the average is:
ρσ² + (1 − ρ)σ² / B
As B grows, the second term shrinks toward zero. The first term does not. It depends only on how correlated the trees are. Two consequences follow:
- Adding trees helps, but with diminishing returns.
- Bagging cannot remove variance shared by all the trees. Bootstrap samples drawn from the same data still produce trees that look alike, especially when a few strong features dominate every top split. The next chapters address this with random feature subsets.
Bagging barely changes bias. Each tree is trained on about the same amount of distinct data as before, so the average has roughly the bias of a single tree. This is why bagging is paired with deep, low-bias trees.
Bagging by hand
The code below bags trees without any random feature selection. Each tree sees every feature at every split. Compare it with a single tree using the same train and test split.
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
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.2, random_state=0, stratify=y
)
rng = np.random.default_rng(0)
trees = []
for i in range(50):
idx = rng.integers(0, len(X_train), size=len(X_train))
tree = DecisionTreeClassifier(random_state=i)
trees.append(tree.fit(X_train[idx], y_train[idx]))
single = DecisionTreeClassifier(random_state=0).fit(X_train, y_train)
votes = np.stack([t.predict(X_test) for t in trees])
bagged = (votes.mean(axis=0) > 0.5).astype(int)
print("Single tree accuracy:", single.score(X_test, y_test))
print("Bagged trees accuracy:", (bagged == y_test).mean())The exact numbers depend on the split. On most splits the bagged ensemble matches or beats the single tree. A single run on 114 test rows is noisy, so use cross-validation before drawing conclusions.
Bagging in scikit-learn
BaggingClassifier wraps this loop for any base estimator.
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import BaggingClassifier
from sklearn.tree import DecisionTreeClassifier
X, y = load_breast_cancer(return_X_y=True)
bag = BaggingClassifier(
estimator=DecisionTreeClassifier(),
n_estimators=100,
bootstrap=True,
oob_score=True,
n_jobs=-1,
random_state=0,
)
bag.fit(X, y)
print("OOB accuracy:", bag.oob_score_)The estimator argument is named base_estimator in scikit-learn versions before 1.2.
Common errors
- Sampling without replacement by accident. With
bootstrap=Falseevery tree sees the same rows, or a subsample of them, and the diversity comes from different sources. Keepbootstrap=Truefor classic bagging. - Reusing one random seed. If every tree gets the same
random_stateand the same sample, you build identical trees and the ensemble gains nothing. - Bagging a stable model. Linear models and k-nearest neighbors with large k change little between bootstrap samples. Averaging nearly identical models gives almost no gain.
- Expecting accuracy to keep rising with B. More trees reduce variance up to the ρσ² floor. After that you only pay in training and prediction time.
Exercise
A bagged ensemble of 500 trees performs only slightly better than 100 trees. Using the variance formula ρσ² + (1 − ρ)σ² / B, explain why, and name what limits further improvement.
Show answer
With B = 100 the second term (1 − ρ)σ² / B is already small, so raising B to 500 shrinks it only a little. The remaining error is dominated by ρσ², which depends on the correlation between the trees and does not change with B. To improve further you must make the trees less correlated, for example with random feature subsets at each split.