Method · Statistics Library

Random forest

A random forest averages hundreds of decision trees, each grown on a bootstrap sample with only a random subset of predictors available at each split, decorrelating the trees so their averaged prediction is far more stable than any single tree's, with cross-validated metrics and a free out-of-bag honesty check.

Topic indexA reference reading outside the guided chapter sequence

Understand the idea

A single decision tree is powerful but jittery: grow it again on a slightly different sample of the same data and you can get a noticeably different tree, because one changed split near the root cascades through everything beneath it. A random forest tames this jitteriness by growing hundreds of trees, each on its own random resample of the data, and then letting them vote (for a category) or averaging their predictions (for a number).

There's a subtle but important extra trick beyond just averaging many trees: at every single split, each tree is only allowed to consider a RANDOM SUBSET of the predictors, not all of them. Without this, a strong, dominant predictor would top nearly every tree, making the trees correlated with each other and largely canceling out the benefit of averaging many of them. By forcing each split to draw from a random subset, no single predictor can dominate every tree, the trees become genuinely more independent of each other, and the averaging actually pays off in reduced variance.

Because each tree is grown on a resampled subset that leaves out roughly a third of the data by chance, every original row can be scored by the specific trees that never saw it during training, the 'out-of-bag' score. This gives you a genuinely free, built-in honesty check that should roughly agree with the more deliberate cross-validated score reported alongside it; if the two disagree substantially, that disagreement itself is a warning sign worth investigating rather than a number to average away.

A random forest extends bagging, which fits many trees on bootstrap resamples and averages them, by also picking a random subset of columns at each split. The OOB score tests each tree on the rows its resample left out, giving a built-in estimate of accuracy on new data. Permutation importance shuffles one column at a time and measures how much the accuracy drops.

Practitioner explanation

KernelStats grows B trees on bootstrap resamples with a random predictor subset per split (typically sqrt(p) for classification), reporting BOTH the out-of-bag (OOB) score (each row scored only by trees that never trained on it, essentially free) and k-fold cross-validated performance as the headline; the product states these should roughly agree, and a bad disagreement is itself a signal to distrust both and look for leakage or tiny-sample noise rather than to average them away. As with the other tree-based models, in-sample accuracy is shown only as an explicit warning label, since a fully grown forest can memorize training data just as a single unpruned tree can.

TWO feature-importance measures are reported and can disagree: impurity-based (fast, but biased toward high-cardinality predictors, per Strobl et al. 2007) and permutation importance (the card's HEADLINE ranking), computed OUT OF SAMPLE inside each cross-validation fold: refit on the training part, permuted on the held-out part, averaged across folds, with error bars reflecting the spread across folds. The training-set version is retained separately (permutation importance on the training data) specifically so the gap between memorization-driven and genuinely out-of-sample importance is visible; a noise predictor sitting near zero out-of-sample while showing up well above zero in-sample is described as 'the whole lesson in one row'. When every importance is exactly zero (the forest never split, predicting a constant, often from the minimum leaf size set too large), the card states this plainly rather than naming an arbitrary 'most influential' predictor from tie-breaking order.

A specific, concrete data-quality trap is named directly: a genuinely numeric measurement column that arrived as TEXT (often because a couple of cells hold 'N/A', 'unknown', or a stray unit) gets treated as a category, turning 300 distinct measurements into 300 unordered 0/1 indicator columns; the trees then lose every threshold split they would otherwise have made on that column, and the card flags this by name (as mistyped number predictors) rather than silently producing a degraded model with no explanation. Classification models are additionally checked via a cross-validated calibration curve and Brier score, with probability bins holding only a handful of held-out rows deliberately left OFF the chart: a bin of one row can only show an observed frequency of exactly 0 or 1, which would otherwise draw dramatic-looking but meaningless points at the floor and ceiling.

When to use it

Consider it when

Predicting a category or number from a mix of numeric and categorical predictors when the relationship may be non-linear or involve interactions, prediction accuracy matters more than an interpretable equation, and a built-in honesty check (OOB) alongside cross-validation is valuable.

Use caution when

Interpretability of individual effects is required for stakeholders or regulators (a regression or a single tree is more appropriate), predictions are needed outside the range of the training data for a regression outcome (forests cannot extrapolate; predictions flatten at the edges), or a genuinely numeric column has been mistyped as text, which silently degrades the model unless the card's specific flag for this is checked.

Formulas and symbols

Random forest prediction

f^RF(x)=1B∑b=1Bf^(b)(x)\hat f_{\text{RF}}(x) = \dfrac{1}{B}\sum_{b=1}^{B} \hat f^{(b)}(x)

Each of B trees grown on its own bootstrap resample with a random predictor subset per split; votes (classification) or averages (regression) are combined.

Out-of-bag (OOB) score

OOB score≈expected because each bootstrap leaves out≈e−1≈36.8% of rows\text{OOB score} \approx \text{expected because each bootstrap leaves out} \approx e^{-1} \approx 36.8\%\ \text{of rows}

Each row is scored only by the trees that never trained on it, giving a free honesty check that should roughly agree with the cross-validated score.

Correlated-trees variance

Var⁡(fˉ)=ρσ2+1−ρBσ2\operatorname{Var}(\bar f) = \rho\sigma^2 + \dfrac{1-\rho}{B}\sigma^2

rho the pairwise correlation between trees; random forests reduce rho (versus plain bagging) by restricting each split to a random predictor subset, so the averaging actually pays off.

Assumptions and checks

  • Random forest's in-sample accuracy or RMSE can look excellent even when the forest has badly memorized the training data; a large gap between in-sample and cross-validated (or out-of-bag) performance is the direct evidence of how much the in-sample numbers overstate real predictive performance.

    In KernelStats: Checked directly: every headline metric is k-fold cross-validated, with the train-vs-cross-validated gap and the out-of-bag-vs-cross-validated agreement each reported as their own checks.

  • With too few trees, both the out-of-bag score and the permutation-importance ranking are noisy estimates that can shift meaningfully if the forest were refit with a different random seed.

    In KernelStats: Checked directly: the card flags fewer than 100 trees as an 'Enough trees for stable estimates' warning.

  • With too few rows per encoded feature (including one-hot-encoded categorical levels), split choices and the permutation-importance ranking become unstable, and if no tree in the forest ever manages to split at all, every prediction degenerates to a constant.

    In KernelStats: Checked directly: the card reports rows-per-encoded-feature (flagged below 10:1) and separately checks whether the forest actually split at all.

  • With a severely imbalanced classification target, high overall accuracy can be achieved by mostly predicting the majority class, understating how useful the model actually is for the minority class.

    In KernelStats: Checked directly for classification: the card reports the smallest class's share of rows and flags it below 10%.

Alternatives

  • Gradient Boosting (Trees). You want sequential bias reduction rather than variance reduction through averaging, often achieving somewhat higher accuracy with careful tuning.
  • Decision Tree (CART). Interpretability (a single readable flowchart) matters more than the accuracy gain from averaging many trees.
  • Linear Regression. A simpler, interpretable model achieves comparable cross-validated performance.

Worked example

Scenario

Classifying penguin species from four body measurements with 500 trees, comparing OOB score against 5-fold cross-validated accuracy.

Result

OOB score = 97.7%, 5-fold cross-validated accuracy = 97.7% (in-sample 100%); out-of-sample permutation importance ranks bill length highest (0.33) with flipper length second, and the impurity-based ranking also puts bill length first and flipper length second.

Interpretation

The close agreement between OOB and cross-validated accuracy supports trusting both as honest estimates of real-world performance, and the agreement between the two importance measures here (rather than a disagreement) suggests bill length's leading role is a genuine signal rather than an artifact of high cardinality: bill length is what separates Chinstrap from Adelie, which body-size measures cannot.

Dataset: penguins.csv

Common misconceptions

Misconception

The out-of-bag score and the cross-validated score are two independent checks, so if they disagree you should just trust whichever one looks better.

Correction

OOB and cross-validated performance are both honest estimates of the SAME underlying quantity (out-of-sample accuracy) and should roughly agree. A meaningful disagreement between them is itself a warning sign (of data leakage, a tiny-sample artifact, or something else amiss), and the correct response is to distrust BOTH numbers and investigate, not to pick whichever one is more flattering.

Misconception

A genuinely numeric measurement column being treated as text/categorical by the model just means it loses a little precision, nothing to worry much about.

Correction

When a numeric column is mistyped as text (often from a stray 'N/A' or unit label in a few cells), hundreds of distinct measurements become hundreds of unordered 0/1 indicator columns, and the trees lose EVERY threshold split they would otherwise have made on that variable; this can severely degrade the model's use of that predictor, not merely reduce precision slightly, which is exactly why the card flags this condition by name rather than treating it as a minor detail.

References

  1. Random Forests, Breiman, L. (2001), Machine Learning, 45(1), 5-32.
  2. An Introduction to Statistical Learning with Applications in R (2nd ed.), Chapter 8, James, G., Witten, D., Hastie, T. and Tibshirani, R. (2021).