Machine Learning

Random Forests

Random forests turn unstable trees into a vote: bootstrap rows create different trees, feature subsampling decorrelates them, and OOB checks estimate how the vote behaves on rows each tree did not see.

status: reviewimportance: importantdifficulty 3/5math: undergraduateread: 19mlive demo

Concept Structure

Random Forests

01Intuition

Start with the picture, metaphor, or geometric mechanism.

02Math

Make the objects explicit and connect them with notation.

03Code

Mirror the equations with runnable implementation details.

04Interactive Demo

Manipulate the mechanism and watch the idea respond.

3prerequisites
2next concepts
3related links

Learner Contract

What this page should let you do.

You are here becauseRandom forests turn unstable trees into a vote: bootstrap rows create different trees, feature subsampling decorrelates them, and OOB checks estimate how the vote behaves on rows each tree did not see.

This Machine Learning concept is the current idea: keep the same invariant visible across Intuition, Math, Code, Interactive Demo.

By the end4/4 sections ready | runnable code expected | live demo

Explain the mechanism, trace the main notation, and test one prediction in the live demo.

Do this firstIntuition

Read the intuition before the notation; the math should name a mechanism you already felt.

Then go nextGradient Boosting (review)

Follow this edge after making one prediction here; the next page should reuse the result, not restart the route.

Test the linkManipulate one control and predict the visible change.Then continue to Gradient Boosting (review)

Claim/source review status

Substantive review recorded

1/1 claims have bounded review metadata; still check caveats and source scope.Metadata-derived; review may be AI-assisted. Not a human certification.
Claims1/1 reviewed
Sources3 cited
Codeattached
Demolive
Reviewed2026-07-02
Updatedpage 2026-07-02

Learning item flow

4/4 sections readyAsk about thisResearch room
ConceptRandom ForestsMachine Learning
3 sources attachedLocal snapshot ready
concept:machine-learning/random-forests
01

01

Intuition

Build the mental picture first so the rest of the page has something to attach to.

Section prompt

A single decision tree can be easy to read and easy to disturb. Change a few rows, and an early split can change; once the root changes, every downstream branch is trained on a different subset.

A random forest takes that weakness seriously. Instead of asking one unstable tree to be wise, it creates many different trees and lets them vote.

Two kinds of randomness do the work:

  1. Bootstrap rows: each tree trains on a sample drawn with replacement from the training set.
  2. Feature subsampling: at each split, the tree is allowed to consider only a random subset of features.

Bootstrap samples make the trees different. Feature subsampling keeps one strong feature from dominating every root split, so the trees become less correlated. The forest prediction is then an average for regression or a majority vote for classification.

The important caveat is that voting is not magic. If most trees are weak in the same wrong way, the forest can still be wrong. Random forests are powerful because unstable but useful trees often make different mistakes, and averaging different mistakes is safer than trusting one tree.

02

02

Math

Translate the story into symbols, assumptions, and a derivation you can inspect.

Section prompt

Let the training set be

D={(xi,yi)}i=1n.\mathcal D=\{(x_i,y_i)\}_{i=1}^n.

For tree b{1,,B}b\in\{1,\ldots,B\}, draw a bootstrap dataset

Db={(xi1,yi1),,(xin,yin)},\mathcal D_b^\star = \{(x_{i_1},y_{i_1}),\ldots,(x_{i_n},y_{i_n})\},

where each index iji_j is sampled uniformly from {1,,n}\{1,\ldots,n\} with replacement. Some rows appear multiple times; some rows are left out.

A bagged tree fits

f^b(x)=T(x;Db).\hat f_b(x)=T(x;\mathcal D_b^\star).

For regression, bagging predicts by averaging:

f^bag(x)=1Bb=1Bf^b(x).\hat f_{\text{bag}}(x) = \frac{1}{B}\sum_{b=1}^B \hat f_b(x).

For classification with classes 1,,K1,\ldots,K, each tree votes:

y^b(x){1,,K},\hat y_b(x)\in\{1,\ldots,K\},

and the forest predicts

y^forest(x)=argmaxkb=1B1[y^b(x)=k].\hat y_{\text{forest}}(x) = \arg\max_k \sum_{b=1}^B \mathbf 1[\hat y_b(x)=k].

Random forests add feature subsampling. If there are pp input features, then at each split the tree considers only a random subset

Mb,{1,,p},Mb,=mtry,M_{b,\ell}\subseteq\{1,\ldots,p\}, \qquad |M_{b,\ell}|=m_{\text{try}},

for node \ell in tree bb. With mtry=pm_{\text{try}}=p, the method is bagging. With mtry<pm_{\text{try}}<p, strong features cannot appear in every split candidate set, so the trees tend to become less correlated.

The averaging story is clearest under squared error. Suppose each tree's prediction at a fixed xx has variance σ2\sigma^2 and any two tree predictions have correlation ρ\rho. The variance of the average is

Var(1Bb=1Bf^b(x))=ρσ2+1ρBσ2.\operatorname{Var}\left(\frac1B\sum_{b=1}^B \hat f_b(x)\right) = \rho\sigma^2+\frac{1-\rho}{B}\sigma^2.

The 1/B1/B term improves when trees are not perfectly correlated. The ρσ2\rho\sigma^2 term remains when all trees move together. That is why random forests do not just make many trees; they try to make useful trees whose errors are not too synchronized.

Out-of-bag evaluation uses the rows left out of a tree's bootstrap sample. For row ii, define

Oi={b:iDb}.O_i=\{b: i\notin \mathcal D_b^\star\}.

The OOB prediction for row ii uses only trees in OiO_i, so it is a built-in validation-like estimate for the forest:

y^OOB(xi)=argmaxkbOi1[y^b(xi)=k].\hat y_{\text{OOB}}(x_i) = \arg\max_k \sum_{b\in O_i}\mathbf 1[\hat y_b(x_i)=k].

This is useful, but it is not a replacement for careful evaluation contracts, distribution-shift checks, calibration checks, or domain-specific costs.

03

03

Code

Keep the implementation aligned with the notation so the algorithm is legible.

Section prompt
from collections import Counter

labels = {"a": 1, "b": 1, "c": 1, "d": 1, "e": 0, "f": 1,
          "g": 0, "h": 1, "i": 0, "j": 0, "k": 0, "l": 0}

trees = [
    {"sample": list("abcdefghijkl"), "vote": 0},
    {"sample": list("abbcdefghkkl"), "vote": 0},
    {"sample": list("acddeffhijll"), "vote": 1},
    {"sample": list("bcdeehijjkl"), "vote": 0},
    {"sample": list("aacefghhikll"), "vote": 0},
    {"sample": list("bdefgghijkkl"), "vote": 0},
    {"sample": list("abcdffghijkl"), "vote": 0},
]

votes = Counter(tree["vote"] for tree in trees)
forest_vote = votes.most_common(1)[0][0]

row = "b"
oob_votes = [
    tree["vote"] for tree in trees
    if row not in tree["sample"]
]
oob_vote = Counter(oob_votes).most_common(1)[0][0]

print("tree votes:", dict(votes))
print("single tree vote:", trees[0]["vote"])
print("forest vote:", forest_vote)
print("OOB votes for row b:", oob_votes)
print("OOB vote:", oob_vote, "actual:", labels[row])

This code starts from a precomputed shallow-tree witness: the point is the aggregation contract. A full random-forest implementation would grow each tree by searching split criteria on each bootstrap sample and feature subset.

04

04

Interactive Demo

Use direct manipulation to connect the explanation to a moving system.

Section prompt

Use the lab to compare bagging with random forests. Predict whether the forest vote, one tree, or the out-of-bag row controls the probe. Then reveal the tree votes, root-split agreement, feature masks, and OOB check. The surprise to watch for: feature subsampling may not change the final vote, but it can reduce how many trees copy the same root split.

Live Concept Demo

Explore Random Forests

The stage is code-native and interactive. Use it to test the explanation against the mechanism.

difficulty 3/5undergraduatecode-aligned
Demo Prediction Checkpoint

Manipulate one control and predict the visible change.

Commit to what Random Forests should make visible before reading the result.

After The First Pass

Turn the concept into an inspected object.

Once the invariant is visible in the intuition, math, code, and demo, use these panels to inspect the mechanism visually, check source support, practice the idea, and attach a grounded research question.

Mechanism Storyboard

See the idea move before the page explains it

Random forests turn unstable trees into a vote: bootstrap rows create different trees, feature subsampling decorrelates them, and OOB checks estimate how the vote behaves on rows each tree did not see.

Prediction open01 / Intuition
Prediction lens

Start with the picture, metaphor, or geometric mechanism.

Commit first

Before reading further, choose the kind of change Random Forests should make visible.

Visual Inquiry

Make the image answer a mathematical question

Random forests turn unstable trees into a vote: bootstrap rows create different trees, feature subsampling decorrelates them, and OOB checks estimate how the vote behaves on rows each tree did not see.

4/4 stages readyLive demo connected
Prediction

Which visible object should carry the first intuition?

Commit first

Pick the cue that should make Random Forests easier to reason about before the page gives the answer.

Source Grounding

Canonical references for the mechanism on this page.

course-notes · 2021CS229 Decision TreesStanford CS229

Supports the motivation that single decision trees are high variance, and random forests use sample and feature bagging to decorrelate trees.

Open source
book · 2023An Introduction to Statistical Learning, Chapter 8James, Witten, Hastie, Tibshirani, and Taylor

Supports bagging via bootstrap training sets, averaging/voting trees, OOB error estimation, random-feature subset size m, and the decorrelation rationale for random forests.

Open source
book · 2009The Elements of Statistical Learning, Chapter 8Hastie, Tibshirani, and Friedman

Supports bagging as bootstrap aggregation, averaging predictions, classification majority vote, variance-reduction intuition, and the caveat that bagging a bad classifier can make it worse.

Open source

Claim Review

Random forests turn unstable trees into a vote: bootstrap rows create different trees, feature subsampling decorrelates them, and OOB checks estimate how the vote behaves on rows each tree did not see.

Status1 substantive review recorded

Claims without a substantive review badge still need exact source-support review.

Sources3 references

cs229-2021-random-forests, james-2023-islr-random-forests, hastie-2009-esl-bagging-forests

Local checks4 local checks

Use equations, runnable code, and demos to check whether the source support is operational.

Substantively reviewedA random forest averages or votes over many bootstrap-grown trees while restricting candidate features at splits; this can reduce variance by averaging useful unstable trees and decorrelating their errors, but OOB error and validation are still needed because voting does not guarantee correctness.Claim metadata: source checked

The sources support bootstrap sample construction, fitting many trees, average/vote aggregation, OOB prediction from trees that did not train on a row, and feature subsampling to reduce tree correlation.

Sources: CS229 Decision Trees, An Introduction to Statistical Learning, Chapter 8, The Elements of Statistical Learning, Chapter 8The lab uses seven deterministic shallow tree voters; it does not implement full CART training, calibrated probabilities, feature-importance methods, missing-value handling, honest forests, or real hyperparameter tuning.A bounded review summary is present; still check caveats and exact reference scope.

Checked Stanford CS229 decision-tree notes, ISLR Chapter 8, and ESL Chapter 8 for tree high variance, bootstrap aggregation, averaging/voting, OOB error, feature-subset m_try/random forest decorrelation, and the caveat that bagging only helps when base learners are useful enough. GPT Pro critique remains pending because 127.0.0.1:51672 was unavailable.

Reviewer: codex-local-source-review; reviewed 2026-07-02

Practice Loop

Try the idea before it explains itself

Random forests turn unstable trees into a vote: bootstrap rows create different trees, feature subsampling decorrelates them, and OOB checks estimate how the vote behaves on rows each tree did not see.

Readiness0/3 checks ready
Predict

Before touching the demo, predict one visible change that should happen in Random Forests.

Hint 1

Reveal when your model needs a nudge.

Hint 2

Reveal when your model needs a nudge.

Hint 3

Reveal when your model needs a nudge.

Grounded research drawerClose
ConceptRandom ForestsMachine Learning

Research Room

Attach the question to a claim, equation, code, or demo

Pick the concept, equation, source, runnable code, claim, misconception, or demo state before asking for help. The handoff keeps that page item in context.
Next local actionNo local draft saved yet

Open the draft below to save one note and next action in this browser.

conceptMachine Learning

Random Forests

Attached question

What is the smallest example that makes Random Forests click without losing the math?

Local action draftNo local draft saved yetExpand only when ready to capture one local next action
Local action draft

This draft stays in this browser, attached to the selected learning item.

No local draft saved.
Evidence to inspect
  • References to inspect: attached references on this page.
  • Definition, prerequisite, and contrast concept links
  • The equation or runnable code that makes the concept operational
  • One demo state that shows the invariant instead of a slogan
What would resolve this
  • The learner can state the mechanism in their own words
  • The learner can name the prerequisite that would repair confusion
  • The learner can predict how the mechanism changes under one perturbation
Grounded AI handoff

I am working in Continuous Function's research reading room. Object: concept - Random Forests Selected item key: recorded for copy. Context: Machine Learning Page anchor: recorded for copy. Open question: What is the smallest example that makes Random Forests click without losing the math? Evidence to inspect: - References to inspect: attached references on this page. - Definition, prerequisite, and contrast concept links - The equation or runnable code that makes the concept operational - One demo state that shows the invariant instead of a slogan What would resolve this: - The learner can state the mechanism in their own words - The learner can name the prerequisite that would repair confusion - The learner can predict how the mechanism changes under one perturbation Answer as a careful research tutor: stay source-grounded, separate verified evidence from assumptions, name the relevant math objects, and end with one next action.

View it in context
concept/concept-notebook/machine-learning/random-forests concept:machine-learning/random-forests