Chapter 28 of 42 · ~25 min read & lab+70 XP
Chapter 28 · Machine Learning

Bagging, Random Forests, ExtraTrees & Feature Importance

Bootstrap 63.2% / 36.8% Out-of-Bag validation, why feature subsampling (m = √d) breaks tree correlation, ExtraTrees, and MDI vs. Permutation Importance.

What Is It?

Random Forests train hundreds of decorrelated decision trees on bootstrap samples with random feature subsets, then average (or vote) their predictions.

Why Is It Required?

A single deep decision tree wildly overfits; averaging many diverse trees dramatically slashes variance with almost no hyperparameter tuning.

Everyday Analogy: Asking 100 independent doctors who each examined slightly different subsets of lab tests, then taking the majority diagnosis.
Why ML Engineers & Data Scientists Actually Need This

Random Forests are the ultimate 'works out of the box' tabular baseline — virtually impossible to overfit by adding more trees!

ML / AI Engineer

Random Forests train completely in parallel across CPU cores (n_jobs=-1), require almost zero hyperparameter babysitting, and give free OOB validation scores.

Data Scientist

Knowing NOT to trust .feature_importances_ (MDI) when your table has IDs, timestamps, or continuous noise — and using held-out Permutation Importance or SHAP instead — prevents embarrassing stakeholder insights!

Interview & Debug Edge

Favorite Staff-level question: 'Does increasing n_estimators in a Random Forest cause overfitting? Write down the ensemble variance formula to prove your answer!'

Step 0 · Test Your Gut Before Any Math!

You have a Random Forest with 100 trees. You increase n_estimators from 100 to 2,000. What happens to the test error?

What You Will Master in This Chapter
  • Derive the 63.2% in-bag / 36.8% Out-of-Bag (OOB) bootstrap probability limit 1/e
  • Prove using Var = ρσ² + ((1−ρ)/B)σ² why Random Forests outperform plain Bagging via feature subsampling
  • Contrast Random Forests with ExtraTrees (random split thresholds) and explain why adding more trees B doesn't overfit
  • Explain why default MDI (Gini) feature importance is biased toward high-cardinality features and use Permutation Importance instead
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 4
BSay aloud:“Number of trees”
Plain-English Meaning
How many bootstrap trees are averaged in the forest
Everyday Example
n_estimators = 300
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

One deep Decision Tree is like asking one brilliant but eccentric stock analyst: low bias, wild variance. Bagging asks 300 analysts trained on slightly different bootstrap subsets and averages their votes. Random Forest goes one genius step further: it forces each analyst to inspect only a random subset of √d clues at every split so they can't all copy the same dominant feature!

1. Bootstrap Sampling & The 36.8% Out-of-Bag (OOB) Free Lunch

Everyday Story First (Zero Math Yet!)

Each tree in a Random Forest trains on N rows drawn with replacement. Any single row has probability (1−1/N)N→e−1≈36.8%(1 - 1/N)^N \to e^{-1} \approx 36.8\% of NEVER being picked for that tree! Test the math live in the simulator below.

Bootstrap Sampling (Draw N with Replacement): Free 36.8% Out-of-Bag Validation!~63.2% Unique Rows In-Bag (Train Tree b)~36.8% Out-of-Bag (OOB)P(row i never picked in N draws) = (1 − 1/N)^N → 1/e ≈ 0.3679 (36.8%)Evaluate every row using ONLY the trees where it was Out-of-Bag → free CV-like estimate!
Each bootstrap sample draws N rows with replacement, capturing ~63.2% unique rows and leaving ~36.8% as a free Out-of-Bag (OOB) validation set.

Free OOB Validation

Set oob_score=True in RandomForestClassifier: each training row xix_i is predicted using ONLY the ~37% of trees that never saw xix_i during training — giving an unbiased CV-like score without holding out a separate validation split!

Interactive Mini-Lab • Bootstrap & OOB Math

Draw N = 50 Rows With Replacement & Measure Free OOB Holdout

Unique In-Bag
66.0%
Simulated OOB
34.0%
Exact (1−1/N)^N
36.4%

2. Decorrelating Trees: Why Random Forest Beats Plain Bagging

Everyday Story First (Zero Math Yet!)

If one super-strong feature exists, plain Bagging puts that same feature at the root of almost every tree — making the trees 85% correlated (ρ = 0.85). Averaging 500 identical clones doesn't reduce variance!

Why Random Forest Beats Plain Bagging: Decorrelating Trees via max_features = √dPlain Bagging (All d features at split)1 dominant feature wins the root splitin EVERY tree → high correlation ρ ≈ 0.85Var_avg → ρ·σ² (stuck at 0.85 σ²!)Random Forest (m = √d random features)Different trees see different subsets →diverse structures → low correlation ρ ≈ 0.25Var = ρ·σ² + (1−ρ)/B · σ² (3× lower!)
Random Forests beat plain Bagging by sampling only m = √d features at every split — breaking tree correlation ρ so ensemble variance ρσ² + (1−ρ)σ²/B drops dramatically!

The Ensemble Variance Identity (Memorize for Interviews!)

For BB identically distributed trees with individual variance σ2\sigma^2 and pairwise correlation ρ\rho: Var ⁣(1B∑b=1BTb)=ρσ2+1−ρBσ2\text{Var}\!\left(\frac{1}{B}\sum_{b=1}^B T_b\right) = \rho \sigma^2 + \frac{1 - \rho}{B}\sigma^2

  • Random Forest restricts each split to a random subset of mm features (m=dm = \sqrt{d} for classification, m=d/3m = d/3 for regression), slashing ρ\rho!
  • ExtraTrees goes even further by picking random split thresholds instead of searching for the optimal threshold — even faster and lower variance!

3. Feature Importance Trap: MDI vs. Permutation Importance

Everyday Story First (Zero Math Yet!)

Suppose you accidentally leave a random high-cardinality column (like user_id or random floats) in your table. A deep Random Forest has thousands of split points on that random column — so MDI (Gini importance) awards it huge fake importance!

Feature Importance Trap: MDI (Gini) vs. Held-Out Permutation ImportanceMDI (Default .feature_importances_)Random UUID (Noise!)True Signal (Binary)Biased toward high-cardinality noise!Permutation Importance (on Val Set)Random UUID (Noise!)True Signal (Binary)Shuffling noise drops Val score by 0.00!
MDI (Gini importance) is biased toward high-cardinality & continuous features; Permutation Importance on validation data measures true predictive drop.

How Held-Out Permutation Importance Fixes It

  1. Compute baseline score SS on the validation set.
  2. Randomly shuffle column jj (breaking its link to yy) and re-score SjS_j.
  3. Importance =S−Sj= S - S_j. Shuffling pure noise drops validation accuracy by 0.00! (Watch out: if two features are 99% correlated, shuffling one leaves the twin intact, splitting their permutation importance — group correlated features or use SHAP in Ch 19!)
“Wait, I'm Confused...” · Teacher Office Hours Q&A

The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.

Because Bagging/RF ONLY reduces Variance (it cannot reduce Bias!). Starting with deep, low-bias trees and averaging away their variance gives low bias + low variance. Boosting, by contrast, aggressively reduces Bias step-by-step, so it starts with shallow weak learners!

Interactive Visual Lab
Lab Challenge: In the Forest Variance Lab below, set B = 200 trees, then drag tree correlation ρ down from 0.85 (Bagging) to 0.20 (Random Forest) to see why decorrelation dominates!
Flagship Deep Lab • Ensemble Variance Formula

Var(Average) = ρ·σ² + ((1 − ρ) / B)·σ² — Watch Why Decorrelation Matters!

Variance Reduction: 68.6%
Single Tree Variance
1.00 σ²
Forest Variance
0.314 σ²
Irreducible Floor (ρ·σ²)
0.30 σ²

Notice that adding more trees B NEVER causes Random Forests to overfit — it just asymptotically approaches the correlation floor ρ·σ². Lowering ρ via max_features="sqrt" is the ONLY way to push the floor down!

Intuition Takeaway: Random Forests slash tree variance via Bootstrap sampling (free 36.8% OOB) + random feature subsampling (cutting correlation ρ) — never overfit from more trees, and always verify feature importance with Permutation or SHAP!
Where This Powers Real ML, Deep Learning & Generative AI

Fast Tabular Baseline

First non-linear benchmark on almost any Kaggle or enterprise tabular dataset.

Parallel Distributed Scoring

All B trees are independent, enabling embarrassingly parallel training and inference.

Production NumPy & PyTorch Code Patterns
from sklearn.ensemble import RandomForestClassifier
from sklearn.inspection import permutation_importance

rf = RandomForestClassifier(
    n_estimators=300,
    max_features="sqrt",
    oob_score=True,
    n_jobs=-1,
    random_state=42,
)
rf.fit(X_train, y_train)
print("Free OOB Accuracy:", round(rf.oob_score_, 4))

# Unbiased held-out Permutation Importance
perm = permutation_importance(rf, X_val, y_val, n_repeats=10, random_state=42)
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Reporting default .feature_importances_ (MDI) on high-cardinality features.
Best Practice: MDI is computed on training data and inflated by continuous/high-cardinality columns; compute Permutation Importance on validation data or TreeSHAP!
Trap #2: Thinking increasing n_estimators in Random Forest causes overfitting.
Best Practice: Variance strictly decreases toward ρσ² as B → ∞; tune max_depth, min_samples_leaf, or max_features instead.
Trap #3: Assuming Bagging reduces Bias.
Best Practice: The expected value of an average equals the expected value of a single tree — Bagging cuts Variance, NOT Bias!
Chapter Mastery Check (+70 XP)
Score: 0 / 5
1In Var = ρσ² + ((1−ρ)/B)σ², what limits Random Forest variance reduction as B → ∞?
2How do Random Forests reduce pairwise tree correlation ρ compared to plain Bagging?
3Why is MDI (Gini) feature importance misleading on mixed tabular data?
4How does ExtraTrees (Extremely Randomized Trees) differ from Random Forests?
5Does Bagging primarily reduce Bias or Variance?

Apply What You Learned — Solve Matching Coding Problems