PIXELBANKv9.1.0
Menu

Chapter 6: Ensemble Methods

Week 11-12

Harness the wisdom of crowds in machine learning. Learn how to combine multiple models for superior predictions through bagging with Random Forests, boosting with AdaBoost and XGBoost, and sophisticated stacking techniques.

Topics
4
Demos
5
Min read
51

Chapter Overview

The fundamental insight behind ensemble methods is that a committee of models often outperforms any individual member. Just as diverse perspectives lead to better decisions in human groups, diverse models can cancel out each other's errors.

Ensemble methods come in two main flavors. Bagging (Bootstrap AGGregatING) trains multiple models independently on different random samples and averages their predictions, reducing variance. Random Forests extend this by also randomizing feature selection, creating highly decorrelated trees.

Boosting takes a different approach: train models sequentially, with each new model focusing on the mistakes of the previous ones. AdaBoost reweights samples to emphasize misclassified examples. Gradient Boosting fits each new tree to the residuals (errors) of the ensemble so far, effectively performing gradient descent in function space.

These methods dominate machine learning competitions and real-world applications. Gradient Boosting implementations like XGBoost, LightGBM, and CatBoost are go-to choices for tabular data, often achieving state-of-the-art results with proper tuning.

This chapter covers:

  • Bagging: Reducing variance by training on bootstrap samples and aggregating predictions
  • Random Forests: Highly effective ensemble of decorrelated decision trees, feature importance, and tuning
  • AdaBoost: Adaptive boosting with sample reweighting
  • Gradient Boosting: The powerhouse algorithm (XGBoost, LightGBM, CatBoost) with regularization techniques
  • Voting & Stacking: Combining diverse models for superior performance

Chapter Roadmap

Click any topic to jump in

Interactive demo
1
Bagging & Random Forests

Reduce variance by training on bootstrap samples and combining diverse decision trees through majority vote.

Bootstrap SamplingBaggingWhy Bagging WorksRandom ForestsFeature SubsamplingOut-of-Bag ErrorRF HyperparametersRF Feature Importance
From parallel to sequential

Two sequential refinement strategies

2
Boosting

Sequential learning where each model corrects the mistakes of previous ones via sample reweighting.

Boosting vs BaggingAdaBoost AlgorithmWeak LearnerLearner Weight αSample Weight UpdateFinal PredictionAdaBoost Sensitivity
3
Gradient Boosting

Gradient descent in function space — XGBoost, LightGBM, and CatBoost dominate tabular data.

Gradient Boosting IdeaResidual FittingGradient Descent in Function SpaceLearning Rate (Shrinkage)XGBoostLightGBMCatBoostGB RegularizationEarly Stopping
Combining the best of all worlds
4
Stacking

Train a meta-learner to optimally combine diverse base models for superior ensemble predictions.

Voting EnsembleStacking (Two-Level)Cross-Validation for StackingDiverse Base ModelsMeta-Learner ChoiceBlendingWhen Stacking HelpsSklearn StackingClassifier

Topics

4 topics in this chapter

The previous chapter, Decision Trees, ended on a frustrating trade-off. A deep tree captures complex patterns but has high variance: remove one training sample and the root split can change, producing a completely different tree. A pruned tree is stable but underfits. Could we keep the low bias of deep trees and remove most of their variance? The idea behind this chapter, Ensemble Methods, is that many imperfect models, combined well, can beat any one of them.

This first topic covers the simplest way to combine models: train many on slightly different data and average them. We start with bootstrap sampling, which manufactures many training sets from one, then define bagging and show with the variance of an average why it works, and where it stops working. Random forests add feature subsampling at each split to make the trees less alike. We then use the samples each tree never saw for out-of-bag error, a free validation estimate, and finish with tuning forests and reading their feature importances.

Definition

Bagging, short for bootstrap aggregating, trains B models of the same type on B bootstrap samples of the training data, each drawn with replacement, and averages their predictions or takes a majority vote. A random forest is bagging with decision trees in which each split considers only a random subset of the features.

In this topic

  1. 1Bootstrap Sampling
  2. 2Bagging
  3. 3Why Bagging Works
  4. 4Random Forests
  5. 5Feature Subsampling
  6. 6Out-of-Bag Error
  7. 7RF Hyperparameters
  8. 8RF Feature Importance
1 of 8
Bootstrap Sampling

A bootstrap sample draws nn points from an nn-point training set uniformly at random with replacement. Some points appear several times and others not at all. The probability a given point is never drawn is (1−1/n)n(1 - 1/n)^n, which approaches 1/e1/e, about 0.368, so each bootstrap sample contains about 63.2 percent of the distinct original points. The left-out 36.8 percent are that sample's out-of-bag (OOB) points. Bootstrap samples resemble the original data but differ from each other, which makes them a cheap way to simulate drawing new training sets from the same population.

Mathematical Intuition

Each bootstrap draw is independent with replacement, so the probability a specific sample is never selected in nn draws is (1−1/n)n→1/e≈0.368(1-1/n)^n \to 1/e \approx 0.368. This means each bootstrap sample uses roughly 1−1/e≈63.2%1 - 1/e \approx 63.2\% of the original data. The out-of-bag fraction converges to 1/e1/e by the limit definition of ee itself — one of the most elegant connections between combinatorics and analysis in statistics.

Example:

Dataset: [A, B, C, D, E]. One bootstrap sample might be?

2 of 8
Bagging

y^=1B∑b=1Bfb(x)\hat{y} = \frac{1}{B} \sum_{b=1}^{B} f_b(x)

Bagging trains BB copies of a base model, each on its own bootstrap sample, giving models f1,…,fBf_1, \ldots, f_B. For regression the prediction is their average, the formula above; for classification it is a majority vote or the average of predicted probabilities. The models are independent, so training parallelizes perfectly. Bagging leaves the bias roughly unchanged, since each model is fit the same way, but reduces variance. It therefore helps unstable, low-bias learners such as deep trees and does little for stable ones such as linear regression, whose bootstrap fits barely differ.

Mathematical Intuition

If BB models each have variance σ2\sigma^2 and pairwise correlation ρ\rho, the ensemble variance is ρσ2+(1−ρ)σ2B\rho\sigma^2 + \frac{(1-\rho)\sigma^2}{B}. As B→∞B \to \infty, the second term vanishes but the first remains — the floor is set by ρ\rho. Bootstrap diversity drives ρ\rho below 1, making the floor lower. Bagging cannot reduce bias (the average prediction of infinitely many models), only variance — which is why it works best with low-bias, high-variance base learners like deep trees.

Example:

5 trees predict: [1,0,1,1,0] for classification. Bagged prediction?

3 of 8
Why Bagging Works

Averaging reduces variance. If BB models each have prediction variance σ2\sigma^2 and are uncorrelated, their average has variance σ2/B\sigma^2 / B. Bagged models are trained on overlapping data, so their errors are correlated with some pairwise correlation ρ\rho, and the variance of the average becomes ρσ2+(1−ρ)σ2/B\rho\sigma^2 + (1-\rho)\sigma^2/B. More models shrink only the second term; the first is a floor that no number of trees can lower. Bagging therefore pays off most when individual models have high variance and low correlation, which motivates random forests: decorrelate the trees to lower the floor.

Mathematical Intuition

If BB predictors each have variance σ2\sigma^2 and pairwise correlation ρ\rho, their average has variance ρσ2+(1−ρ)σ2B\rho\sigma^2 + \frac{(1-\rho)\sigma^2}{B}. With uncorrelated predictors (ρ=0\rho = 0) this is σ2/B\sigma^2/B, a reduction by exactly 1/B1/B. With correlated predictors (ρ>0\rho > 0) the second term vanishes as BB grows but the first does not, so the variance saturates at ρσ2\rho\sigma^2. This is why random forests add feature subsampling on top of bootstrap sampling: it decorrelates the trees, pushing ρ\rho down and lowering the variance floor.

Example:

Single tree variance=100. 100 uncorrelated trees, each variance=100. Ensemble variance?

4 of 8
Random Forests

A random forest is bagged decision trees with one addition: at each split, the tree searches only a random subset of max_features features, drawn fresh at every node. Defaults are about p\sqrt{p} features for classification, where pp is the total count, and a larger share for regression; Breiman suggested p/3p/3, and scikit-learn now uses all features for regression by default. Restricting the search makes trees less alike, lowering the correlation term from the previous concept, at the cost of slightly weaker individual trees. Trees are usually grown deep and unpruned, since the averaging handles variance. Random forests are strong defaults for tabular data and need little tuning.

Mathematical Intuition

At each split, considering only p\sqrt{p} random features out of pp total introduces a binomial selection process. The probability that the single best feature is available at a given split is p/p=1/p\sqrt{p}/p = 1/\sqrt{p}. For p=100p=100, there is only a 10%10\% chance the dominant feature appears — forcing the tree to find alternative splits. This decorrelation is multiplicative across tree depth: by the time a tree is dd levels deep, the chance of every split using the best feature drops to (1/p)d(1/\sqrt{p})^d.

Example:

100 features, classification. At each split, how many features considered?

5 of 8
Feature Subsampling

Why does restricting features help? Suppose one feature is far more predictive than the rest. In plain bagging, nearly every tree splits on it at the root, so trees share the same structure and make correlated errors. When each split sees only a random subset, the dominant feature is often missing, and trees must find signal in other features. Individual trees become slightly worse, but the ensemble becomes more diverse, and the reduced correlation usually outweighs the weaker trees. max_features is the main tuning knob: smaller values increase diversity and bias; larger values make trees stronger but more alike.

Mathematical Intuition

Feature subsampling at each split is equivalent to adding a stochastic mask m∼Bernoulli(p/p)\mathbf{m} \sim \text{Bernoulli}(\sqrt{p}/p) to the feature set. The information gain of a split on feature jj is ΔIj=H(parent)−∑c∣c∣nH(c)\Delta I_j = H(\text{parent}) - \sum_{c} \frac{|c|}{n} H(c), but it is only evaluated for j∈{j:mj=1}j \in \{j : m_j = 1\}. A dominant feature with ΔI1≫ΔIj\Delta I_1 \gg \Delta I_j would normally always be selected — the mask prevents this, ensuring the ensemble explores the full feature space rather than repeatedly exploiting the same greedy path.

Example:

Feature X is super predictive. Without subsampling, all trees split on X first. Problem?

6 of 8
Out-of-Bag Error

Each tree is trained on a bootstrap sample, so about 36.8 percent of training points are out-of-bag for it. For each training point, we can therefore collect predictions from only the trees that never saw it, about a third of the forest, and compare their combined vote with the true label. Averaging over all points gives the out-of-bag error, an estimate of generalization error that needs no separate validation set or extra training. In scikit-learn, set oob_score=True. It is slightly pessimistic, because each point is judged by only a third of the trees, and needs enough trees to be stable.

Mathematical Intuition

The OOB estimate is asymptotically equivalent to leave-one-out cross-validation. For each sample xix_i, roughly B/eB/e trees did not see it during training. The OOB prediction aggregates these B/eB/e independent votes, giving an unbiased estimate of the generalization error. As B→∞B \to \infty, the OOB error converges to the true leave-one-out error — the variance of the OOB estimator decreases as O(1/B)O(1/B), making it increasingly reliable with more trees.

Example:

Sample X is OOB for trees [3, 7, 12, 25]. These trees predict [1, 1, 0, 1]. OOB prediction?

7 of 8
RF Hyperparameters

Random forests have few important knobs. n_estimators, the number of trees, improves stability with diminishing returns and does not cause overfitting; a few hundred is typical, limited by time and memory. max_features controls tree diversity and is the most influential. max_depth, min_samples_leaf, and max_leaf_nodes limit individual trees, which matters for noisy data and model size. bootstrap and max_samples control resampling. Tune with the OOB score or cross-validation. A large gap between training and OOB accuracy is normal for forests of deep trees, so judge overfitting by whether OOB accuracy improves when trees are restricted.

Mathematical Intuition

The key hyperparameters control the bias-variance trade-off at two levels: n_estimatorsn\_\text{estimators} controls ensemble variance (more trees always helps, never hurts), while max_depth\text{max\_depth} and min_samples_leaf\text{min\_samples\_leaf} control individual tree bias-variance (deeper trees have lower bias but higher variance). The interaction is multiplicative: a forest of shallow trees has high bias but extremely low variance, while a forest of deep trees has low bias with variance bounded by ρσtree2\rho\sigma^2_{\text{tree}}.

Example:

RF with n_estimators=100, max_depth=None. Train=99%, OOB=85%. Overfitting?

8 of 8
RF Feature Importance

A forest's impurity-based importance averages each feature's weighted impurity decrease over all trees, so it is much more stable than a single tree's: the run-to-run noise of one tree averages out. Feature subsampling also gives secondary features a chance to be used, so importance is spread more fairly among correlated features than in one tree. The biases from the previous chapter remain: the scores are computed on training data and favor high-cardinality features. Permutation importance on held-out or OOB data is the more reliable check, and correlated features should be judged as a group.

Mathematical Intuition

Mean Decrease in Impurity (MDI) for feature jj is Imp(j)=1B∑b=1B∑t∈TbΔIjt\text{Imp}(j) = \frac{1}{B}\sum_{b=1}^{B}\sum_{t \in T_b} \Delta I_{jt} — averaged over all trees and all nodes where feature jj was used to split. By the law of large numbers, as B→∞B \to \infty this converges to E[ΔIj]E[\Delta I_j]. The standard error decreases as 1/B1/\sqrt{B}, which is why RF importance is far more stable than single-tree importance. Permutation importance provides an alternative that is unbiased for correlated features.

Example:

Single tree: age importance varies 0.1-0.4 across runs. RF with 100 trees: age=0.25±0.02. Why?

Theory Exercise

Problem:

A Random Forest with 100 trees achieves 85% accuracy. Adding more trees to 500 improves to 86%. Would adding 5000 trees likely help much more? Why?

Hints:
  • Think about diminishing returns
  • What happens as variance approaches its minimum?
  • Consider computational cost

Coding Exercise

Problem:

Train a RandomForestClassifier with out-of-bag scoring enabled, verify the OOB score approximates held-out test accuracy (free validation), then rank the top features by importance.

Hints:
  • Set bootstrap=True and oob_score=True on the classifier
  • Compare clf.oob_score_ to clf.score(X_test, y_test)
  • Feature importances live in clf.feature_importances_; np.argsort to rank them