ML Bootstrap Aggregation
A single decision tree is easy to understand but unstable: change a few training rows and you may get a quite different tree with different predictions. Models like this have high variance. A clever way to calm them down is to train many of them on slightly different data and let them vote. That is bootstrap aggregation, usually shortened to bagging.
Step 1: bootstrap samples
A bootstrap sample is drawn from the training set with replacement: pick a random row, put it back, pick again, until you have as many rows as the original. Some rows appear twice or more, others not at all:
import numpy as np
rng = np.random.default_rng(1)
rows = np.arange(10) # pretend these are 10 training rows
for i in range(3):
sample = rng.choice(rows, size=10, replace=True)
left_out = sorted(set(rows.tolist()) - set(sample.tolist()))
print(f"sample {i}: {sorted(sample.tolist())} left out: {left_out}")sample 0: [0, 1, 2, 3, 4, 5, 7, 8, 9, 9] left out: [6]
sample 1: [0, 0, 2, 2, 4, 4, 5, 6, 8, 8] left out: [1, 3, 7, 9]
sample 2: [1, 3, 3, 4, 5, 7, 7, 8, 8, 8] left out: [0, 2, 6, 9]
On average a bootstrap sample contains about 63 % of the distinct rows; the rows it leaves out are called out-of-bag (OOB) rows.
Step 2: aggregate
Train one model on each bootstrap sample. To predict, ask every model and combine the answers: a majority vote for classification, an average for regression. Because each model saw different data, their individual mistakes partly cancel out.
BaggingClassifier
Let's compare one tree with a bag of trees on the breast-cancer data:
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import BaggingClassifier
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=5, stratify=y)
tree = DecisionTreeClassifier(random_state=0).fit(X_train, y_train)
print("single tree train:", round(tree.score(X_train, y_train), 3),
" test:", round(tree.score(X_test, y_test), 3))
bag = BaggingClassifier(estimator=DecisionTreeClassifier(), n_estimators=30, random_state=0)
bag.fit(X_train, y_train)
print("bagged trees train:", round(bag.score(X_train, y_train), 3),
" test:", round(bag.score(X_test, y_test), 3))single tree train: 1.0 test: 0.942
bagged trees train: 1.0 test: 0.971
The single, fully grown tree is perfect on its own training data but noticeably worse on the test set. The bag of 30 trees generalises better.
How many models?
More estimators usually help, with diminishing returns. Training cost grows linearly, so there's a sweet spot:
import matplotlib.pyplot as plt
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import BaggingClassifier
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=5, stratify=y)
sizes = [1, 2, 5, 10, 20, 40]
scores = []
for n in sizes:
bag = BaggingClassifier(estimator=DecisionTreeClassifier(), n_estimators=n, random_state=0)
scores.append(bag.fit(X_train, y_train).score(X_test, y_test))
print(f"{n:3} trees -> test accuracy {scores[-1]:.3f}")
plt.plot(sizes, scores, marker="o")
plt.xlabel("Number of trees")
plt.ylabel("Test accuracy")
plt.show() 1 trees -> test accuracy 0.942
2 trees -> test accuracy 0.930
5 trees -> test accuracy 0.959
10 trees -> test accuracy 0.965
20 trees -> test accuracy 0.965
40 trees -> test accuracy 0.971
Out-of-bag evaluation
Each tree never saw its out-of-bag rows, so those rows can be used as a free validation set. With oob_score=True, every training row is predicted only by the trees that did not train on it:
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import BaggingClassifier
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=5, stratify=y)
bag = BaggingClassifier(estimator=DecisionTreeClassifier(), n_estimators=40,
oob_score=True, random_state=0)
bag.fit(X_train, y_train)
print("OOB accuracy: ", round(bag.oob_score_, 3))
print("test accuracy:", round(bag.score(X_test, y_test), 3))
print("trees trained:", len(bag.estimators_))OOB accuracy: 0.952
test accuracy: 0.971
trees trained: 40
The OOB estimate is close to the test score, without needing a separate validation set.
Looking inside one member
The individual models are stored in estimators_. Each one is an ordinary decision tree, and they differ from each other:
from sklearn.datasets import load_breast_cancer
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import BaggingClassifier
data = load_breast_cancer()
bag = BaggingClassifier(estimator=DecisionTreeClassifier(), n_estimators=5, random_state=0)
bag.fit(data.data, data.target)
for i, tree in enumerate(bag.estimators_):
root = data.feature_names[tree.tree_.feature[0]]
print(f"tree {i}: depth={tree.get_depth()}, leaves={tree.get_n_leaves()}, root split on '{root}'")tree 0: depth=7, leaves=17, root split on 'worst concave points'
tree 1: depth=7, leaves=16, root split on 'worst perimeter'
tree 2: depth=7, leaves=14, root split on 'worst perimeter'
tree 3: depth=7, leaves=16, root split on 'worst perimeter'
tree 4: depth=7, leaves=18, root split on 'mean concave points'
Note: Bagging reduces variance, so it helps most with unstable models such as deep decision trees. Bagging a very stable model (like linear regression) changes little. Random forests (a later lesson) take bagging one step further by also randomising the features each split may use.
Test yourself
How is a bootstrap sample drawn?
- Taking the first half of the data
- Sampling rows with replacement until it has the original size
- Sorting the data and taking every other row
- Removing outliers
How does a bagging classifier combine its models' predictions?
- It uses only the best model
- Majority vote
- It multiplies them
- It picks one at random
What are out-of-bag rows?
- Rows with missing values
- Training rows a particular model did not see in its bootstrap sample
- The test set
- Duplicate rows