Skip to content

Bagging & Boosting

Random Forest and gradient boosting are the two strongest families of tabular models. Gradient boosting is the engine behind XGBoost, LightGBM, and CatBoost. Both are ensembles of decision trees, and they reach the same ceiling by opposite paths.

  • Bagging trains many trees in parallel on resampled data and averages them. It reduces variance.
  • Boosting trains many trees sequentially, each correcting the previous ones. It reduces bias.

Every code block runs in a container in the companion repository, so the numbers and figures are real. They use the breast cancer dataset.

A single decision tree is greedy and high-variance. Small changes to the data shift the splits and give different predictions, and a deep tree will happily memorize noise until it fits the training set almost perfectly and then generalizes badly on anything new. Two strategies fix this without changing the model family. Train many trees on slightly different views of the data and average them, or train them one after another so each new tree corrects the mistakes the ensemble has made so far.

Bagging is bootstrap aggregating: draw a bootstrap sample, train a tree, repeat, and average the predictions.

The data come from Wolberg, Mangasarian, Street, and Street, Breast Cancer Wisconsin Diagnostic, 1993. UCI distributes the data under CC BY 4.0. This lesson partitions the observations and computes model predictions and evaluation results; those results are derived from the source data.

from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import BaggingClassifier
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
out = Path("outputs")
out.mkdir(exist_ok=True)
data = load_breast_cancer()
x_train, x_test, y_train, y_test = train_test_split(
data.data, data.target, test_size=0.3, random_state=42,
stratify=data.target,
)
# One bagging ensemble: 100 trees, each fit on its own bootstrap sample.
bag = BaggingClassifier(DecisionTreeClassifier(random_state=42),
n_estimators=100,
random_state=42,
n_jobs=-1)

Train a single tree across 10 seeds, then bagging ensembles of growing size:

single = []
for seed in range(10):
tree = DecisionTreeClassifier(random_state=seed).fit(x_train, y_train)
single.append(accuracy_score(y_test, tree.predict(x_test)))
single_mean, single_std = np.mean(single), np.std(single)
sizes = [1, 2, 5, 10, 25, 50, 100, 200]
bag_mean, bag_std = [], []
for n_trees in sizes:
accuracies = []
for seed in range(10):
model = BaggingClassifier(DecisionTreeClassifier(random_state=seed),
n_estimators=n_trees,
random_state=seed,
n_jobs=-1)
model.fit(x_train, y_train)
accuracies.append(accuracy_score(y_test, model.predict(x_test)))
bag_mean.append(np.mean(accuracies))
bag_std.append(np.std(accuracies))
print(f" n={n_trees:>3} single {single_mean:.4f} +/- {single_std:.4f}"
f" bagging {bag_mean[-1]:.4f} +/- {bag_std[-1]:.4f}")
n= 1 single 0.9234 +/- 0.0061 bagging 0.9164 +/- 0.0211
n= 2 single 0.9234 +/- 0.0061 bagging 0.9058 +/- 0.0270
n= 5 single 0.9234 +/- 0.0061 bagging 0.9357 +/- 0.0157
n= 10 single 0.9234 +/- 0.0061 bagging 0.9316 +/- 0.0133
n= 25 single 0.9234 +/- 0.0061 bagging 0.9421 +/- 0.0099
n= 50 single 0.9234 +/- 0.0061 bagging 0.9398 +/- 0.0079
n=100 single 0.9234 +/- 0.0061 bagging 0.9444 +/- 0.0047
n=200 single 0.9234 +/- 0.0061 bagging 0.9439 +/- 0.0039
fig, ax = plt.subplots(figsize=(6, 4))
ax.axhline(single_mean, color="#c44e52", ls="--", label="single tree")
ax.plot(sizes, bag_mean, color="#4c72b0", marker="o", label="bagging")
ax.fill_between(sizes, np.array(bag_mean) - np.array(bag_std),
np.array(bag_mean) + np.array(bag_std),
color="#4c72b0", alpha=0.2)
ax.set_xlabel("Number of trees")
ax.set_ylabel("Test accuracy")
ax.set_title("Bagging reduces variance as trees grow")
ax.legend()
fig.tight_layout()
fig.savefig(out / "bagging-vs-single-tree.png", dpi=150)
plt.close(fig)

Single tree accuracy (constant) vs a bagging ensemble that rises and stabilizes as trees grow

The single tree’s mean stays at 0.92 no matter how many seeds you average. Bagging climbs from 0.92 to 0.94. Its standard deviation drops from 0.021 to 0.004. That falling spread is variance reduction in action.

Random Forest adds one trick to bagging. At every split it samples a random subset of features (max_features="sqrt" by default). That decorrelates the trees and cuts variance further.

Boosting builds the ensemble sequentially, each tree fitting the residuals of the previous ensemble, scaled by a learning rate.

from sklearn.ensemble import GradientBoostingClassifier
from sklearn.metrics import log_loss
gbm = GradientBoostingClassifier(n_estimators=200,
learning_rate=0.1,
max_depth=3,
random_state=42)
gbm.fit(x_train, y_train)

Track the log-loss on train and test after each tree:

train_loss, test_loss = [], []
for train_prob, test_prob in zip(gbm.staged_predict_proba(x_train),
gbm.staged_predict_proba(x_test)):
train_loss.append(log_loss(y_train, train_prob))
test_loss.append(log_loss(y_test, test_prob))
best = int(np.argmin(test_loss)) + 1
for iteration in (1, 50, 200):
label = f"Training loss at iter {iteration}:"
print(f" {label:<27}{train_loss[iteration - 1]:.4f}")
for iteration in (1, 50, 200):
label = f"Test loss at iter {iteration}:"
print(f" {label:<27}{test_loss[iteration - 1]:.4f}")
print(f" {'Best test iter:':<27}{best}")
Training loss at iter 1: 0.5718
Training loss at iter 50: 0.0134
Training loss at iter 200: 0.0001
Test loss at iter 1: 0.5852
Test loss at iter 50: 0.1530
Test loss at iter 200: 0.1906
Best test iter: 60
fig, ax = plt.subplots(figsize=(6, 4))
iterations = range(1, 201)
ax.plot(iterations, train_loss, color="#4c72b0", label="train")
ax.plot(iterations, test_loss, color="#c44e52", label="test")
ax.axvline(best, color="grey", ls="--", label=f"best iter ({best})")
ax.set_xlabel("Boosting iteration")
ax.set_ylabel("Log-loss")
ax.set_title("Boosting learning curve")
ax.legend()
fig.tight_layout()
fig.savefig(out / "boosting-learning-curve.png", dpi=150)
plt.close(fig)

Train log-loss falls to near zero while test log-loss bottoms out at iteration 60 then climbs

Training loss falls almost to zero. Test loss bottoms out at iteration 60, then drifts up. That is the boosting overfitting signature. It is why early stopping matters: watch a validation set and stop when it stops improving.

Algorithm Update rule
AdaBoost Reweights misclassified samples so the next stump focuses on them
Gradient boosting Fits each tree to the gradient of the loss
XGBoost / LightGBM / CatBoost Modern gradient boosting with regularization, second-order gradients, and engineering tricks

5-fold accuracy on the same dataset:

from sklearn.ensemble import AdaBoostClassifier, RandomForestClassifier
from sklearn.model_selection import cross_val_score
models = {
"AdaBoost (100 stumps)": AdaBoostClassifier(n_estimators=100,
random_state=42),
"Random Forest (100 trees)": RandomForestClassifier(
n_estimators=100, random_state=42, n_jobs=-1),
"Bagging (100 trees)": BaggingClassifier(
DecisionTreeClassifier(random_state=42), n_estimators=100,
random_state=42, n_jobs=-1),
"Gradient Boosting (100 trees)": GradientBoostingClassifier(
n_estimators=100, random_state=42),
"Single decision tree": DecisionTreeClassifier(random_state=42),
}
rows = []
for name, model in models.items():
scores = cross_val_score(model, data.data, data.target, cv=5,
scoring="accuracy")
rows.append([name, scores.mean(), scores.std()])
results = pd.DataFrame(rows, columns=["model", "cv_accuracy", "std"])
results = results.sort_values("cv_accuracy", ascending=False)
print(results.round(4).to_string(index=False))
model cv_accuracy std
AdaBoost (100 stumps) 0.9772 0.0105
Gradient Boosting (100 trees) 0.9631 0.0210
Bagging (100 trees) 0.9579 0.0382
Random Forest (100 trees) 0.9561 0.0228
Single decision tree 0.9173 0.0242

Every ensemble beats the single tree by 4 to 6 points. The exact ranking is dataset-dependent, so the honest answer is: try both with cross-validation.

Use case Pick
Quick strong baseline, no tuning Random Forest
Highest accuracy on tabular data Gradient boosting (XGBoost, LightGBM, CatBoost)
Many categorical features CatBoost
Very large dataset LightGBM (fastest)
Small dataset Random Forest
  • scikit-learn bias and variance example

    The example decomposes prediction error into squared bias, variance, and noise over repeated datasets. It provides a more complete comparison than a single test-loss curve.

  • scikit-learn cross-validation guide

    The guide distinguishes model selection from evaluation on unseen observations. Use that distinction when a plotted minimum suggests a preferred boosting iteration.