How does bagging work?
Bagging (Bootstrap Aggregating) reduces variance by training multiple instances of a high-variance base model independently on bootstrap datasets sampled with replacement from the training set. Averaging their predictions for regression or taking majority votes for classification cancels out sample-specific noise and yields more stable generalization.
Study Card: How does Bagging work?
Direct Answer
Bagging (Bootstrap Aggregating) is an ensemble technique designed to stabilize unstable, high-variance learners (most famously deep, unpruned decision trees) by combining predictions across parallel models:
- Bootstrap Sampling: Draw datasets of size independently by sampling with replacement from the original training set of size . Because sampling is with replacement, each draw omits an observation with probability , so the probability a point is never chosen in draws is: Thus, each bootstrap sample contains roughly 63.2% distinct training examples, leaving 36.8% as Out-of-Bag (OOB) validation samples.
- Parallel Training: Fit an independent base estimator on each bootstrap sample .
- Aggregation: Combine predictions via arithmetic mean for regression, or majority voting / averaged class probabilities for classification.
For identically distributed predictors with individual variance and average pairwise correlation , ensemble variance shrinks to:
Key Terms
- Bootstrap Sample: A dataset of size generated by uniform random sampling with replacement from the original training points.
- Out-of-Bag (OOB) Samples: The ~36.8% of training observations omitted from a given bootstrap sample, usable as a built-in validation set.
- Variance Reduction: Averaging uncorrelated or weakly correlated predictors smooths sensitivity to single outliers or split boundary shifts.
- Aggregation: Combining ensemble predictions via averaging (regression / soft voting) or majority voting (hard classification).
Example
Suppose a single unpruned decision tree predicting customer churn shifts dramatically whenever a few training records change (high variance). With bagging (), we train 100 independent unpruned trees on 100 bootstrap resamples. For a new customer, if 70 trees vote churn and 30 vote stay (or their predicted churn probabilities average to 0.68), the bagged ensemble outputs churn—smoothing out erratic single-tree splits.
Code Implementation
import numpy as np
from sklearn.datasets import make_classification
from sklearn.ensemble import BaggingClassifier
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
# Generate a synthetic classification dataset
X, y = make_classification(
n_samples=300, n_features=10, n_informative=6, n_redundant=2, random_state=42
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=42, stratify=y
)
# Single unpruned decision tree (low bias, high variance)
single_tree = DecisionTreeClassifier(random_state=42)
single_tree.fit(X_train, y_train)
print(f"Single Tree Test Accuracy: {accuracy_score(y_test, single_tree.predict(X_test)):.4f}")
# Bagging Classifier with Out-of-Bag evaluation
bagging_model = BaggingClassifier(
estimator=DecisionTreeClassifier(),
n_estimators=50,
oob_score=True,
random_state=42,
)
bagging_model.fit(X_train, y_train)
print(f"Bagging OOB Accuracy: {bagging_model.oob_score_:.4f}")
print(f"Bagging Test Accuracy: {accuracy_score(y_test, bagging_model.predict(X_test)):.4f}")
# Manual bootstrap sampling demonstration (first 5 trees)
rng = np.random.default_rng(42)
for i in range(5):
indices = rng.integers(0, len(X_train), size=len(X_train))
tree = DecisionTreeClassifier(random_state=i)
tree.fit(X_train[indices], y_train[indices])
acc = accuracy_score(y_test, tree.predict(X_test))
print(f"Bootstrap Tree {i + 1} Test Accuracy: {acc:.4f}")
Related Concepts
- Random Forest: Extends tree bagging by sampling a random subset of
max_featuresat every node split, further lowering pairwise tree correlation and tightening the ensemble variance floor . - Boosting: Trains weak learners sequentially to correct residual errors (reducing bias) rather than independently in parallel (reducing variance).
- When Bagging Helps Least: Bagging offers little variance reduction for already stable, low-variance linear models (such as OLS or Ridge) compared to unstable models like decision trees.
- Pasting: Samples training subsets without replacement (
bootstrap=Falsein scikit-learn), useful when training datasets are massive and cannot easily hold duplicate rows.