SeeingML
Core ML Models Guide 3 of 6 · tap to switch
✦ Interactive Visual Guide 9 min · 4 hands-on labs · Beginner friendly

Random Forests

Average hundreds of decorrelated decision trees trained on random bootstrap bags to crush variance and win on tabular datasets out of the box.

In 1906, statistician Francis Galton visited a country fair where 787 villagers tried to guess the weight of an ox. Almost every individual guess missed wildly, some hundreds of pounds too high, others too low. Yet when Galton averaged all 787 guesses together, the crowd landed within one single pound of the true weight.

A Random Forest (Leo Breiman, 2001) puts that exact Wisdom of the Crowd to work on Decision Trees. One deep tree is jumpy and overfits stray outliers. Grow 100 slightly different trees in parallel and let them vote: individual mistakes cancel out, and blocky rectangular boxes melt into a smooth diagonal decision surface!

Click from 1 Tree up to 100 Trees below and watch the chaotic boundaries calm down while accuracy on unseen Test customers climbs!

Interactive Lab 1: Watch 1 Jagged Tree Smooth Into a 100-Tree Forest
Step through 1 Tree up to 100 Trees to watch outlier islands vanish and unseen Test accuracy climb.
LowMidHighLowMidHighCustomer Tenure (Longer Stay on Right)Support Friction (Higher Up)
StayedLeft / ChurnedFilled Circle = PracticeHollow Diamond = Unseen TestDeeper color = stronger forest agreement
Trees Voting
1
Practice Fit
100%
Unseen Test
83% (10/12)
1 Single Tree (83% Unseen Test): blocky, jittery rectangular islands chase the two noisy outliers, hurting accuracy on nearby unseen Test customers.

Notice a reassuring property: adding more trees to a Random Forest does not cause overfitting. Past roughly 100 to 300 trees, error on unseen data simply settles smoothly onto a flat plateau.


How Random Forest Works: Bootstrap Bagging & Out-of-Bag Error

If you feed the exact same table to 100 identical Decision Trees, you get 100 identical clones. So how does a Random Forest make every tree genuinely different?

First, it uses Bootstrap Aggregating (Bagging): to build each tree, it draws a full-sized bag of rows from your training table with replacement (like pulling marbles from a jar and tossing each marble right back in before the next pull). Some rows get picked twice or three times, while roughly 36.8% never get picked for that tree at all!

Click Draw Tree #2 below to inspect how each tree sees a fresh slice of the table, and watch the untouched amber Out-of-Bag (OOB) rows appear automatically.

Interactive Lab 2: Bootstrap Bagging & Free Out-of-Bag (OOB) Validation
Showing Tree #1
Each tree pulls 12 marbles (rows) with replacement from your 12-row table. Green dots show how many copies landed in Tree #1's bag; amber cards were skipped completely.
Row #1OOB (0x)
Row #2In Bag (2x)
Row #3In Bag (1x)
Row #4In Bag (1x)
Row #5OOB (0x)
Row #6OOB (0x)
Row #7In Bag (1x)
Row #8In Bag (2x)
Row #9OOB (0x)
Row #10In Bag (1x)
Row #11In Bag (2x)
Row #12In Bag (2x)
Bag Size (With Replacement)
12 draws (8 unique rows)
Left Out-of-Bag (OOB)
4 rows (33%)
Typical Skipped Share
~36.8% skipped on average
For Tree #1, drawing 12 rows with replacement picked 8 unique rows (up to 2x for repeat draws) and left 4 amber Out-of-Bag rows (33%) untouched. Because Tree #1 never trained on those skipped rows, we can immediately grade Tree #1 on them for a free built-in Out-of-Bag score!

Because Tree #1 never saw its amber Out-of-Bag rows during training, we can grade every row using ONLY the trees that skipped it. That gives you a trustworthy built-in validation benchmark practically for free.


Trick #2: Random Feature Subsampling (what separates Forests from plain Bagging)

Row bagging alone has a hidden flaw. Suppose one powerhouse column (like Debt Ratio) is much stronger than every other clue. Even on bootstrapped bags, nearly every tree will still pick Debt Ratio as its very first top question! Asking 100 near-identical clone trees to vote barely helps because they all share the same blind spots and make the same mistakes.

Random Forests add a brilliant twist: at every single split, each tree is only allowed to look at a small random subset of columns. If your spreadsheet has 9 columns, each split only peeks at 3 random columns (the square root of the total, often written as √p for classification). Temporarily hiding the dominant clue forces other trees to uncover real patterns in Credit Score, Savings, and Income. When genuinely diverse trees vote together, one tree’s mistake gets canceled out by another tree’s strength.

Toggle between Plain Bagging and Random 2-of-6 Columns below to see how hiding dominant clues temporarily unlocks genuine team diversity!

Interactive Lab 3: Why Random Forests Hide Columns at Every Split
Compare the top split chosen by 5 trees trained on the same 6-column loan table:5 of 5 trees clone Debt Ratio!
Tree 1
Debt Ratio
Late BillsCredit Score
Tree 2
Debt Ratio
Late BillsCredit Score
Tree 3
Debt Ratio
IncomeCredit Score
Tree 4
Debt Ratio
Late BillsSavings
Tree 5
Debt Ratio
Late BillsCredit Score
How Similar the Trees Are
86% Similar (Near-identical clones)
Error Wobble Drop (100 Trees)
Only 14% less error wobble
Problem: When every tree sees all 6 columns at every split, one superstar clue (Debt Ratio) wins the top split in every single tree! Asking 100 near-identical clones to vote barely cancels out their shared mistakes (only 14% less error wobble).

Which clues actually helped? Catching the ID-column trap

Once a Random Forest finishes training, teams naturally want to know which columns mattered most. By default, most tools report a quick Default Split Score, officially called Mean Decrease in Impurity (MDI). It adds up how much each column cleaned up the training groups every time a tree split on it.

There is one famous catch: the Default Split Score is easily fooled by columns with lots of unique values, even a completely random Customer Account ID! Because every row has its own unique ID number, deep trees find endless lucky cutoffs on that ID column to memorize training rows, making pure noise look like a star predictor.

The honest check is a Shuffle Test, officially called Permutation Importance. After the forest is trained, you take an unseen validation table and shuffle ONE column like a deck of cards, scrambling its values while keeping all other columns untouched. If shuffling Support Tickets causes validation accuracy to plunge, that clue truly helps. If shuffling Account ID changes accuracy by 0%, you have caught a fake clue red-handed!

Toggle between Default Split Score (MDI) and Shuffle Test (Permutation Importance) below to watch a fake noise ID get exposed instantly.

Interactive Lab 4: Default Split Score (MDI) vs. Shuffle Test (Permutation Importance)
Watch where Random Account ID ranks when you switch from Default Split Score to the Shuffle Test.Training Split Score Share
#1Monthly Support Tickets
36%
#2Random Account ID (Pure Noise!)Fooled by Unique IDs!
28%
#3Customer Tenure (Months)
24%
#4Contract Plan Tier
8%
#5Region Code
4%
Trap! The Default Split Score (MDI) is calculated purely on training splits. Because a Random Account ID has thousands of unique ID values, it gives the tree endless lucky ways to memorize rows, falsely ranking pure noise at #2 (28%)!
See Breiman's Ensemble Variance Equation & the 1/e OOB DerivationThesis / Reference

1. Why Decorrelation Drives Random Forests (Breiman, 2001): Suppose an ensemble averages BB identically distributed trees, each having individual prediction variance σ2\sigma^2 and pairwise correlation ρ∈[0,1]\rho \in [0, 1] between any two trees. The variance of their average fˉ=1B∑b=1Bfb\bar{f} = \frac{1}{B}\sum_{b=1}^{B} f_b is exact:

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

As B→∞B \to \infty, the second term vanishes to zero, leaving an irreducible variance floor of ρ σ2\rho\,\sigma^2. Plain Bagging reduces 1−ρBσ2\frac{1-\rho}{B}\sigma^2 but leaves ρ\rho high; random feature subsampling (max_features = sqrt(p) for classification, p/3 for regression) directly shrinks ρ\rho so the ensemble variance floor plummets!

2. Exact Out-of-Bag (OOB) Probability: When drawing nn rows with replacement from a table of size nn, the probability that any particular training row is skipped on every single draw approaches e−1e^{-1}:

P(row i is OOB)=(1−1n)n→n→∞e−1≈0.3679P(\text{row } i \text{ is OOB}) = \left(1 - \frac{1}{n}\right)^n \xrightarrow{n \to \infty} e^{-1} \approx 0.3679

3. Unbiased Feature Attribution: Strobl et al. (2007) demonstrated that Gini/MDI importance inflates continuous and high-cardinality noise variables because more candidate cutpoints inflate training split gains. Permutation Importance (computed on OOB or held-out validation data) measures the actual drop in predictive performance when column jj is randomly permuted, eliminating training overfitting bias (while keeping correlated twin columns in mind, where SHAP or grouped permutation shines).

See Random Forest + OOB Score + Permutation Importance in PythonOptional Code
python
from sklearn.ensemble import RandomForestClassifier
from sklearn.inspection import permutation_importance

rf = RandomForestClassifier(
  n_estimators=300,
  max_features="sqrt",  # decorrelates trees at every split
  oob_score=True,       # free Out-of-Bag validation estimate
  n_jobs=-1,            # train trees in parallel across CPU cores
  random_state=42,
)
rf.fit(X_train, y_train)
print("Built-in OOB accuracy:", round(rf.oob_score_, 3))

# Honest held-out Permutation Importance (immune to high-cardinality MDI bias)
perm = permutation_importance(rf, X_val, y_val, n_repeats=10, random_state=42)
for name, mean in sorted(zip(feature_names, perm.importances_mean), key=lambda x: -x[1]):
  print(f"{name:24s} -> {mean:.4f}")

Parallel voting vs. learning from your mistakes

Random Forests train hundreds of independent trees in parallel to average away error wobble, without ever checking what previous trees got wrong.

What if instead we built a relay team of small trees in sequence, where every brand-new tree focuses obsessively on fixing the exact leftover mistakes of the team so far?

That brings us to the reigning champion of tabular ML: Gradient Boosting (XGBoost & LightGBM).

✓ Self-Check

Quick Intuition Check

Four quick real-world scenarios. No scores, just test your intuition.

1

What crucial ingredient separates a Random Forest from plain Bagging of Decision Trees?

Pick an option first, or peek anytime
2

Roughly what share of training rows are left untouched (Out-of-Bag) by any single bootstrapped tree in a large dataset?

Pick an option first, or peek anytime
3

Increasing the number of trees in a Random Forest from 200 to 1,000 will cause severe overfitting on unseen data.

Pick an option first, or peek anytime
4

Your Random Forest's Default Split Score (MDI) ranks a randomly generated 6-digit Customer Reference ID as the #2 most important clue. What should you do?

Pick an option first, or peek anytime
Quick Reference

Common Questions

Is Random Forest supervised or unsupervised, and why is it good for classification?
Random Forest is a supervised learning algorithm trained on labeled examples. It excels at classification and tabular data because averaging dozens or hundreds of diverse decision trees (each built on a bootstrap sample and random feature subset) dramatically reduces overfitting compared to a single tree.
What is the difference between Bagging and a Random Forest?
Both train many Decision Trees on random bootstrap samples of rows. Plain Bagging lets every tree consider all features at every split (producing correlated look-alike trees), whereas a Random Forest randomly restricts each split to a subset of features (commonly sqrt(p)), decorrelating the trees for much stronger variance reduction.
Does adding more trees (n_estimators) cause a Random Forest to overfit?
No! Unlike Gradient Boosting, growing more independent trees in a Random Forest does not overfit the training data. Variance smoothly declines and flattens out toward a steady floor; the only downside of 2,000 trees instead of 200 is extra compute time and memory.
What is Out-of-Bag (OOB) error in Random Forests?
Because each bootstrap bag draws N rows with replacement, roughly 36.8% of training rows are left out of any given tree. Predicting each row using only the trees that never saw it during training gives a fast, built-in validation estimate (oob_score=True).
Why should you be cautious with built-in feature_importances_ (MDI)?
Mean Decrease in Impurity (MDI) measures training-set splits and strongly favours continuous or high-cardinality features (even pure random ID numbers) simply because they offer more candidate cutpoints. Always double-check with Permutation Importance on a held-out validation set.
When should you pick Random Forests vs. Gradient Boosting (XGBoost / LightGBM)?
Random Forests are a rock-solid, parallelizable, nearly tuning-free baseline that rarely blows up on noisy data. Gradient Boosting usually squeezes out higher accuracy on clean structured competitions, but requires careful tuning of learning rate, depth, and early stopping to prevent overfitting.

Written & illustrated by Muhammad Aashir Irshad · Updated December 2026 · Free open-access reference

https://seeingml.com/learn/random-forests/ Open GitHub issue Suggest an edit
Cite this guide in a paper, thesis, or course (BibTeX & APA)
BibTeX
@misc{irshad2026randomforests,
  author       = {Irshad, Muhammad Aashir},
  title        = {Random Forests: Interactive Visual Guide},
  howpublished = {SeeingML},
  year         = {2026},
  month        = {dec},
  url          = {https://seeingml.com/learn/random-forests/},
  note         = {Interactive visual guide}
}
APA

Irshad, M. A. (2026). Random Forests: Interactive Visual Guide. SeeingML. https://seeingml.com/learn/random-forests/