Skip to content
E
Educatum

How does bagging work?

Curated by Educatum AI teamLast updated:
Basic Concepts
Direct Answer

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 BB parallel models:

  1. Bootstrap Sampling: Draw BB datasets of size NN independently by sampling with replacement from the original training set of size NN. Because sampling is with replacement, each draw omits an observation with probability 1−1/N1 - 1/N, so the probability a point is never chosen in NN draws is: (1−1N)N→N→∞e−1≈0.368\left(1 - \frac{1}{N}\right)^N \xrightarrow{N \to \infty} e^{-1} \approx 0.368 Thus, each bootstrap sample contains roughly 63.2% distinct training examples, leaving 36.8% as Out-of-Bag (OOB) validation samples.
  2. Parallel Training: Fit an independent base estimator f^b(x)\hat{f}_b(x) on each bootstrap sample b=1,…,Bb = 1, \dots, B.
  3. Aggregation: Combine predictions via arithmetic mean 1B∑b=1Bf^b(x)\frac{1}{B}\sum_{b=1}^B \hat{f}_b(x) for regression, or majority voting / averaged class probabilities for classification.

For BB identically distributed predictors with individual variance σ2\sigma^2 and average pairwise correlation ρ\rho, ensemble variance shrinks to:

Var ⁣(1B∑b=1Bf^b(x))=ρσ2+1−ρBσ2\text{Var}\!\left(\frac{1}{B}\sum_{b=1}^B \hat{f}_b(x)\right) = \rho\sigma^2 + \frac{1 - \rho}{B}\sigma^2

Key Terms

  • Bootstrap Sample: A dataset of size NN generated by uniform random sampling with replacement from the original NN 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 (B=100B = 100), 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}")
  • Random Forest: Extends tree bagging by sampling a random subset of max_features at every node split, further lowering pairwise tree correlation ρ\rho and tightening the ensemble variance floor ρσ2\rho\sigma^2.
  • 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=False in scikit-learn), useful when training datasets are massive and cannot easily hold duplicate rows.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.