Curriculum02. Supervised LearningLesson 5 of 7

Random Forest

Bootstrap aggregation (bagging) and random subspace feature sampling.

20 min readIntermediateModule 02
01 // CORE INTUITION

Core Intuition: Wisdom of Decorrelated Crowds

A single deep decision tree resembles one brilliant yet erratic expert: sensitive to tiny quirks in its training experience. Asking that same expert the same question twice changes nothing.

A Random Forest trains a committee of BB independent trees, giving each tree a slightly different reshuffled dataset and forcing each split to consider only a random subset of features. Averaging their votes cancels individual noise spikes while preserving the shared underlying signal.

Takeaway:Random Forests stabilize erratic single decision trees by averaging predictions across many decorrelated bootstrap trees.
02 // THE PROBLEM IT SOLVES

The Problem It Solves: High Variance in Single Trees

Unpruned decision trees achieve low bias on complex non-linear boundaries, yet suffer severe variance: perturbing 5 percent of training points can alter the root split and flip predictions across large regions of space.

If you prune one tree aggressively to control variance, bias climbs sharply. Bagging with random feature selection solves this dilemma: each tree stays deep and low-bias, while averaging across BB trees collapses ensemble variance.

Takeaway:Random Forests capture deep non-linear tree boundaries while suppressing single-tree overfitting variance.
03 // STEP-BY-STEP MECHANISM

Step-by-Step Mechanism: Bagging + Feature Subspaces

Building a Random Forest of BB trees executes two randomization loops:

1. Bootstrap Sampling (Bagging): Draw mm observations *with replacement* from the original dataset to build training subset Db\mathcal{D}_b. Roughly 36.8 percent of rows are left out as Out-of-Bag (OOB) validation samples.

2. Random Subspace Splitting: At each tree node, sample only mtry≈dm_{\text{try}} \approx \sqrt{d} candidate features instead of all dd columns, preventing one dominant feature from making every tree look identical.

3. Ensemble Aggregation: Predict by majority class vote (classification) or arithmetic mean (regression).

Takeaway:Bootstrap rows plus random feature subsets (mtry≈dm_{\text{try}} \approx \sqrt{d}) ensure trees make independent errors that cancel when averaged.
04 // INTERACTIVE SANDBOX

Interactive Sandbox: Ensemble Size & Variance Collapse

Increase the Ensemble Size ($B$ trees) slider from 1 tree up to 15 bootstrapped trees on a 2D dataset containing a noisy outlier.

Inspect how a single bootstrapped tree overreacts along one axis, whereas aggregating multiple random-subspace splits smooths the decision confidence and raises overall accuracy while cutting variance.

Bootstrap Aggregation & Majority Vote
1 TREE ACC: 90%FOREST ACC: 90%VAR DROP: -80%
ENSEMBLE SIZE (B TREES)5
Query (195, 125) P(y=1)P(y=1): 1Ensemble Vote: Class 1
Feature x₁Feature x₂
Class 0
Class 1
x₁ splits
x₂ splits
Query point
Takeaway:Adding trees monotonically shrinks ensemble variance without causing the ensemble to overfit training noise.
05 // MATHEMATICAL FORMULATION

Mathematical Formulation: Variance of Correlated Averages

When BB grows large, the second term 1−ρBσ2\frac{1 - \rho}{B}\sigma^2 vanishes toward zero, leaving only ρσ2\rho \sigma^2. Plain bagging without feature subsampling keeps ρ\rho high because every tree picks the same strong root split. Sampling d\sqrt{d} features at each split drops ρ\rho dramatically, cutting total ensemble variance well below any single tree.

PRIMARY OBJECTIVE FORMULATION
Variable & Symbol Definitions
Tb(x)T_b(\mathbf{x})Prediction of the bb-th bootstrapped decision tree at query x\mathbf{x}
BBTotal number of trees grown in the forest ensemble
ρ\rhoAverage pairwise correlation between distinct trees in [0,1][0, 1]
σ2\sigma^2Prediction variance of an individual deep tree
Takeaway:Ensemble variance shrinks to ρσ2\rho \sigma^2 as BB grows; random feature subsampling directly lowers tree correlation ρ\rho.
06 // KEY ASSUMPTIONS

Key Assumptions: Parallel Independence & Interpolation

Random Forests assume training observations are sampled independently so bootstrap resamples reflect data uncertainty, and that useful predictive structure can be approximated by combining axis-aligned regions.

Like single trees, Random Forest regressors average leaf labels from training data, so they cannot extrapolate linearly above the maximum or below the minimum target observed in training.

Takeaway:Random Forests handle mixed scales and non-linearities effortlessly, yet cannot extrapolate target values outside training bounds.
07 // COMMON PITFALLS

Common Pitfalls: Correlated Features & Memory Bloat

Although adding more trees BB does not cause overfitting in the classical sense, growing unconstrained deep trees on millions of rows consumes gigabytes of RAM and slows inference.

Additionally, Gini feature importances bias toward high-cardinality continuous features and split importance evenly across collinear twins (such as income in dollars vs. euros), making individual importance scores misleading without permutation checks.

Algorithmic Checkpoint

Suppose you train 500 bootstrapped trees using ALL d features at every split (bagging) vs. sqrt(d) random features (Random Forest) when one strong feature dominates. What happens?

Takeaway:Prefer permutation importance over raw Gini importance when features correlate, and cap max_depth or min_samples_leaf on large datasets.
08 // COMPLEXITY

Computational Complexity: Embarrassingly Parallel Trees

Growing BB trees each considering mtry=dm_{\text{try}} = \sqrt{d} features per node runs in O(B⋅mtry⋅mlog⁡m⋅depth)O(B \cdot m_{\text{try}} \cdot m \log m \cdot \text{depth}) time. Because every tree trains independently on its own bootstrap copy, training parallelizes linearly across CPU cores (n_jobs=-1).

Inference routes a sample down all BB trees in O(B⋅depth)O(B \cdot \text{depth}) operations, while model memory scales linearly as O(B⋅nodes)O(B \cdot \text{nodes}).

Takeaway:Random Forest training scales linearly with BB and parallelizes across CPU cores, while inference costs O(B⋅depth)O(B \cdot \text{depth}).
09 // REAL-WORLD USE

Real-World Use: Tabular Baselines & Anomaly Scoring

Across healthcare risk modeling, credit default scoring, and industrial sensor diagnostics, Random Forests serve as the fastest zero-tuning baseline for tabular data: they tolerate unscaled features, handle missingness after simple imputation, and require far less hyperparameter tuning than neural networks.

Out-of-Bag validation lets teams check generalization accuracy during training without setting aside a separate validation fold on small clinical cohorts.

Takeaway:Random Forests provide a reliable low-tuning tabular benchmark with free Out-of-Bag validation on small datasets.
10 // PRODUCTION CODE

Production Code: Bootstrap Voting & OOB Scoring

Simulate bootstrap aggregation in NumPy and train a parallelized Random Forest with Out-of-Bag scoring in scikit-learn.

Production Implementation
import numpy as np

rng = np.random.default_rng(42)
X = np.array([[1.0, 2.0], [1.5, 1.5], [2.0, 3.0], [6.0, 5.5], [6.5, 6.5], [7.0, 6.0]])
y = np.array([0, 0, 0, 1, 1, 1])

# Train B=5 bootstrapped 1D random-subspace stumps
B = 5
stumps = []
for _ in range(B):
    idx = rng.integers(0, len(X), size=len(X))
    feat = int(rng.integers(0, X.shape[1]))
    thresh = float(np.median(X[idx, feat]))
    left_cls = int(np.mean(y[idx][X[idx, feat] <= thresh]) >= 0.5) if np.any(X[idx, feat] <= thresh) else 0
    right_cls = 1 - left_cls
    stumps.append((feat, thresh, left_cls, right_cls))

x_q = np.array([2.2, 2.5])
votes = [l if x_q[f] <= t else r for (f, t, l, r) in stumps]
print("Individual tree votes:", votes, "| Ensemble prob(1):", np.mean(votes))
Implementation Walkthrough:

The NumPy snippet demonstrates both pillars of a Random Forest: drawing bootstrap index sets rng.integers(0, len(X), size=len(X)) and sampling a random feature feat per stump before averaging votes. In scikit-learn, max_features="sqrt" decorrelates trees, oob_score=True evaluates each sample only on the trees that excluded it during bootstrapping, and n_jobs=-1 uses all CPU cores.

Takeaway:Enable oob_score=True and max_features="sqrt" in RandomForestClassifier for fast parallelized baselines.