Skip to main content

Beginner-Friendly Topic

Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!

Lesson 2 of 9

Random Forests & Bagging: Bootstrap Sampling, Feature Subsampling & OOB Error

Random Forest is the premier workhorse algorithm for tabular data. It extends standard bagging via two layers of randomization: (1) Bootstrap Sample Aggregation (each tree trains on an independent sample with replacement of size N), and (2) Random Subspace Feature Selection (at every split, only a random subset of sqrt(p) features is considered). Furthermore, samples left out during bootstrapping (Out-of-Bag, ~36.8%) provide built-in validation without requiring a separate cross-validation split.

25 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Random Forest Architecture & Out-of-Bag (OOB) Validation

Random Forest Architecture & Out-of-Bag (OOB) Validation
import numpy as np
import pandas as pd
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import roc_auc_score, accuracy_score

# Ingest high-dimensional medical dataset (569 samples, 30 features)
raw = load_breast_cancer(as_frame=True)
X, y = raw.data, raw.target

# 1. OUT-OF-BAG (OOB) ERROR EVALUATION
# In a bootstrap sample of size N with replacement, the probability a sample is NOT chosen is:
# lim_{N->inf} (1 - 1/N)^N = 1/e โ‰ˆ 36.8%.
# These left-out samples serve as a completely free validation set during training!
rf = RandomForestClassifier(
    n_estimators=200,
    max_features='sqrt', # At each split, evaluate only sqrt(30) โ‰ˆ 5 random features
    oob_score=True,      # Compute out-of-bag validation score
    random_state=42,
    n_jobs=-1            # Maximize parallel CPU execution
)
rf.fit(X, y)

print("=== RANDOM FOREST OUT-OF-BAG EVALUATION ===")
print(f"OOB Accuracy Score : {rf.oob_score_*100:.2f}%")
print(f"OOB Prediction Array shape: {rf.oob_decision_function_.shape}")

# Calculate OOB ROC-AUC
oob_auc = roc_auc_score(y, rf.oob_decision_function_[:, 1])
print(f"OOB ROC-AUC Score  : {oob_auc:.4f}")

# 2. FEATURE IMPORTANCE: MEAN DECREASE IN IMPURITY (MDI)
mdi_importances = pd.Series(rf.feature_importances_, index=X.columns).sort_values(ascending=False)
print("\nTop 5 Most Informative Features (MDI):")
print(mdi_importances.head(5).round(4).to_string())

Pro Tip: Permutation Importance vs Impurity-Based Importance

Default `rf.feature_importances_` (Mean Decrease in Impurity) is heavily biased toward high-cardinality numerical columns. In production, always validate feature importance using `sklearn.inspection.permutation_importance`, which measures the true performance drop when feature values are randomly shuffled on held-out test data.

Diagram
Loading diagramโ€ฆ

XGBoost = best for tabular.

Hands-On Challenge: Tune `max_features` to Minimize Tree Correlation

Train Random Forests with `max_features` set to 1.0 (all features), 'sqrt', and 'log2'. Compute the average pairwise Pearson correlation of predictions between individual trees in each forest, verifying that smaller feature subsets produce more diverse, decorrelated trees.

Quick Quiz & Key Concept Checks

Common Pitfall: Setting `max_depth` to None on Extremely Large Datasets

Allowing trees to grow unconstrained (`max_depth=None`) on massive datasets (e.g. 10,000,000 rows) causes trees to grow 30+ levels deep, consuming tens of gigabytes of RAM to store leaf nodes and slowing down inference latency. Constrain trees with `max_depth=16` or `min_samples_leaf=20`.

Topics in This Module

0/9 done