Skip to content
E
Educatum

What Makes a Random Forest Random?

Curated by Educatum AI teamLast updated:
Basic Concepts
Direct Answer

A Random Forest introduces randomness in two complementary ways during training: bagging (bootstrap aggregating) and random feature subsampling at each split. Bagging trains each decision tree on a distinct bootstrap sample drawn with replacement from the training set, while split-level feature randomness restricts each node split to a random subset of candidate features (such as sqrt(p) in classification). Together, these mechanisms decorrelate individual low-bias, high-variance trees so averaging their predictions sharply lowers ensemble variance.

Study Card: What Makes a Random Forest Random?

Direct Answer

The “random” in Random Forest comes from two distinct sources of stochasticity applied while growing an ensemble of BB decision trees:

  1. Bagging (Bootstrap Aggregating): Each tree is trained on a bootstrap sample of size nn drawn with replacement from the original nn training examples (covering on average 1−e−1≈63.2%1 - e^{-1} \approx 63.2\% unique examples per tree, leaving ≈36.8%\approx 36.8\% out-of-bag).
  2. Feature Randomness (Random Subspace at Each Split): Whenever a tree chooses a split at a node, it evaluates only a random subset of mm features out of all pp features (typically m=⌊p⌋m = \lfloor \sqrt{p} \rfloor for classification and m≈⌊p/3⌋m \approx \lfloor p/3 \rfloor for regression).

Why is feature randomness critical beyond plain bagging? For BB identically distributed trees each with variance σ2\sigma^2 and pairwise correlation ρ\rho, the variance of the ensemble average is:

Var⁡ ⁣(1B∑b=1BTb(x))=ρσ2+1−ρBσ2\operatorname{Var}\!\left(\frac{1}{B}\sum_{b=1}^{B} T_b(\mathbf{x})\right) = \rho \sigma^2 + \frac{1 - \rho}{B}\sigma^2

If one dominant feature drives every bagged tree’s top splits, ρ\rho remains high and variance reduction stalls at ρσ2\rho\sigma^2. Restricting split candidates forces trees to explore diverse feature combinations, lowering ρ\rho and markedly improving generalization.

Key Terms

  • Bagging (Bootstrap Aggregating): Sampling nn training points with replacement per tree to inject data-level diversity.
  • Out-of-Bag (OOB) Samples: The ≈36.8%\approx 36.8\% of points omitted from a tree’s bootstrap sample, useful for free internal validation (oob_score=True).
  • Feature Subsampling (max_features): Randomly selecting m<pm < p candidate features independently at every node split to decorrelate trees.
  • Decorrelation: Reducing pairwise prediction correlation ρ\rho between trees so ensemble averaging reduces variance further.

Example

Suppose a churn dataset has one ultra-predictive feature (account_age) alongside weaker behavioral signals (support_tickets, usage_drop, billing_failures). Under standard bagging without feature randomness, nearly every tree splits first on account_age, creating structurally similar, highly correlated trees. In a Random Forest with max_features='sqrt', roughly 2/32/3 of root splits exclude account_age, allowing different trees to discover predictive rules across the remaining features and lowering the ensemble variance when predictions are averaged or voted.

Code Implementation

import numpy as np
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.tree import export_text

X, y = make_classification(
    n_samples=1000, n_features=10, n_informative=5, n_classes=2, random_state=42
)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# bootstrap=True enables bagging; max_features="sqrt" enables per-split feature randomness
rf = RandomForestClassifier(
    n_estimators=100,
    max_features="sqrt",
    bootstrap=True,
    oob_score=True,
    random_state=42,
)
rf.fit(X_train, y_train)

# 1. Inspect actual bootstrap sample indices used by the first tree
bagged_indices = rf.estimators_samples_[0]
unique_fraction = len(np.unique(bagged_indices)) / len(X_train)
print(f"Train size: {len(X_train)}, Tree 0 bootstrap draws: {len(bagged_indices)}")
print(f"Unique samples in Tree 0: {len(np.unique(bagged_indices))} ({unique_fraction:.1%}, theoretical ~63.2%)")
print(f"OOB score: {rf.oob_score_:.3f}, Test accuracy: {rf.score(X_test, y_test):.3f}")

# 2. Compare root split features across the first 5 trees (decorrelated splits)
root_features = [est.tree_.feature[0] for est in rf.estimators_[:5]]
print("Root split feature index for first 5 trees:", root_features)

tree_rules = export_text(rf.estimators_[0], feature_names=[f"feature_{i}" for i in range(10)])
print("\nTop of Tree 0 structure:\n", "\n".join(tree_rules.splitlines()[:6]))
  • Decision Trees: High-variance, low-bias base learners that benefit strongly from ensemble averaging.
  • Extremely Randomized Trees (Extra-Trees): Adds a third source of randomness by picking split thresholds randomly rather than searching for optimal thresholds.
  • Bagging vs. Boosting: Random Forests grow independent deep trees in parallel to reduce variance, whereas Gradient Boosting grows shallow trees sequentially to reduce bias.
  • Hyperparameters: n_estimators lowers the 1−ρBσ2\frac{1-\rho}{B}\sigma^2 term asymptotically without overfitting (though training cost grows linearly), while max_features trades individual tree strength against inter-tree correlation ρ\rho.
View all →

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