◆ AI All-in-One

Level 3 In-Depth AI · Classical Machine Learning

Random Forests and Bagging

Train hundreds of deliberately different decision trees on random resamples of the data and let them vote. Their individual mistakes cancel out, giving one of the most reliable out-of-the-box models for tabular data.

Level
●●●●● Easy
Reading
12 min
To learn it well
45 minutes to read, an hour to practise
↗ Plan a path here

Read first

Decision Trees

This leads to

—
The full path from zero — 8 concepts before this one
  1. What Is AI?
  2. Probability Basics
  3. How Machines Learn
  4. Probability Distributions
  5. Supervised, Unsupervised and Reinforcement Learning
  6. Entropy, Cross-Entropy and KL Divergence
  7. Supervised Learning
  8. Decision Trees
  9. Random Forests and Bagging

Read them roughly in this order. See it on the concept map →

Why it matters

A single decision tree is easy to read but a poor predictor. It overfits, and it is unstable: change a handful of training rows and you may get a completely different tree. In 2001 Leo Breiman showed a simple way round this. Grow many trees, make each one a little different on purpose, and average them. The result, the random forest, became the workhorse of applied machine learning.

As of late 2026 random forests remain a standard first model for tabular data (spreadsheets, databases, logs), because they:

  • work well with default settings, often within a few percent of a carefully tuned model;
  • need no feature scaling and are robust to outliers and irrelevant features;
  • come with a free validation estimate (the out-of-bag error) and a measure of which features matter;
  • train in parallel on every CPU core.

Random forests are also your first ensemble: a model built by combining many models. Ensembling is everywhere in AI, from Gradient Boosting: XGBoost and LightGBM to averaging the predictions of several neural networks, and the logic in this chapter explains why it works.

The intuition

At a village fair in 1906, Francis Galton looked at about 800 entries in a competition to guess the weight of an ox once slaughtered and dressed. Individual guesses were all over the place, but their middle value (the median) was within 1% of the true weight. The errors of many independent guessers cancel out. This effect is called the wisdom of crowds.

It only works if the guessers are independent. If everyone copied the same loud neighbour, averaging them would just reproduce his mistake.

A random forest builds a crowd of trees and works hard to make them disagree:

  1. Each tree sees a different random resample of the training data.
  2. At each split, each tree may only choose from a random subset of the features.

Each individual tree is still deep and overfitted, but each overfits in its own way. When they vote, the idiosyncratic mistakes cancel and the shared signal remains.

Training data 10 examples 1 2 3 4 5 6 7 8 9 10 1 1 1 2 2 3 6 9 9 9 out-of-bag: 4, 5, 7, 8, 10 tree 1 random features at each split votes “benign” 1 2 2 3 4 5 5 7 7 8 out-of-bag: 6, 9, 10 tree 2 random features at each split votes “malignant” 2 4 5 5 5 6 6 7 8 9 out-of-bag: 1, 3, 10 tree 3 random features at each split votes “benign” Majority vote: benign 2 of 3 trees (real forests use 100s) bootstrap samples drawn with replacement
Fig. 1 How a random forest is built. Each tree is trained on a bootstrap sample of the training data, drawn with replacement, so some examples appear several times and others (the out-of-bag examples) not at all. Each split also considers only a random subset of features. To predict, the trees vote.

Key idea A random forest averages many deep trees, each trained on a random resample of the rows and allowed only a random subset of features at each split. Averaging keeps the trees' low bias but cancels much of their high variance.

How it works

Step 1: bagging

Bagging is short for bootstrap aggregating. A bootstrap sample is a sample of nn rows drawn with replacement from a training set of nn rows. "With replacement" means each draw puts the row back, so the same row can be drawn again. In the figure, tree 1's sample contains row 1 three times and row 9 three times, and never sees rows 4, 5, 7, 8 or 10.

How many rows does a bootstrap sample miss? Each draw misses a particular row with probability 1−1/n1 - 1/n. Over nn independent draws, it is missed every time with probability:

(1−1n)n≈e−1≈0.368for large n\left(1 - \frac{1}{n}\right)^n \approx e^{-1} \approx 0.368 \quad \text{for large } n

For n=10n = 10 it is 0.349; for n=1,000n = 1{,}000 it is 0.368. So each bootstrap sample contains about 63% of the distinct rows, some of them repeated, and leaves out about 37%.

Bagging trains one model per bootstrap sample and combines them: a majority vote for classification (or an average of predicted probabilities, which is what scikit-learn does), and a plain average for regression.

Why averaging helps: a little arithmetic

Suppose each tree's prediction has variance σ2\sigma^2: it wobbles that much depending on which data it saw. If you average BB trees that are completely independent, the variance of the average is σ2/B\sigma^2 / B. With 100 trees the wobble shrinks a hundredfold.

But trees trained on overlapping data from the same source are not independent. If every pair has correlation ρ\rho ("rho", between 0 and 1), the variance of the average is:

Var(average)=ρ σ2+1−ρB σ2\text{Var}(\text{average}) = \rho\,\sigma^2 + \frac{1 - \rho}{B}\,\sigma^2

The second term shrinks as you add trees. The first does not: correlation sets a floor. Take σ2=1\sigma^2 = 1:

Correlation ρ\rho B=10B = 10 trees B=100B = 100 trees B=1,000B = 1{,}000 trees
0.0 0.100 0.010 0.001
0.3 0.370 0.307 0.301
0.7 0.730 0.703 0.700

With ρ=0.7\rho = 0.7, a thousand trees are barely better than ten. To get the benefit of averaging, you must make the trees less correlated. Bagging alone helps, but trees grown on bootstrap samples of the same data still look alike: if one feature is very strong, every tree puts it at the root.

Step 2: random feature subsets

Breiman's extra idea was feature subsampling: at every split, each tree picks a fresh random subset of mm features and may only choose the best split among those. Common defaults:

  • classification: m=pm = \sqrt{p}, where pp is the number of features (30 features → 5 per split);
  • regression: scikit-learn now defaults to all features (m=pm = p, which is plain bagging), while m=p/3m = p/3 is the classic textbook value.

This forces some trees to build their structure around the second-best, third-best and tenth-best features. Each tree gets a little worse on its own, but the trees become much less correlated, so the forest gets better. The parameter mm (max_features) is the main thing worth tuning.

Step 3: out-of-bag error, a free validation set

Each row is left out of about 37% of the bootstrap samples. So for every training row there are many trees that never saw it. Let only those trees vote on it, and compare the vote with the true label. Averaged over all rows, this is the out-of-bag (OOB) error. It estimates the error on new data almost as well as a separate validation set or Cross-Validation, at no extra cost. In the code below the OOB accuracy is 0.957 and the accuracy on a truly held-out test set is 0.965.

A worked example by hand

Three trees in a small forest classify a tumour. Their predicted probabilities of "malignant" are 0.30, 0.80 and 0.40.

  • Majority vote: two trees say benign (below 0.5), one says malignant. Prediction: benign.
  • Probability averaging (scikit-learn's method): (0.30+0.80+0.40)/3=0.50(0.30 + 0.80 + 0.40)/3 = 0.50. Exactly on the fence. A fourth tree saying 0.20 would make it (1.70)/4=0.425(1.70)/4 = 0.425: benign.

For regression, three trees predicting a house price of 310k, 285k and 340k give $(310 + 285 + 340)/3 = 311.7$k.

The averaging also smooths the model. Each tree has blocky, axis-aligned regions, but averaging hundreds of slightly shifted blocks gives a boundary that changes gradually, with a band of uncertainty where the trees disagree.

one deep tree training accuracy 100% accuracy on new data 87.8% random forest of 300 trees training accuracy 100% accuracy on new data 91.1% shade = share of trees voting each way
Fig. 2 One deep tree (left) against a random forest of 300 deep trees (right), on the same noisy data. Both fit the training data perfectly, but the forest's boundary is smoother, its shading shows where the trees disagree, and it scores 91% on new data against 88% for the single tree.

How many trees?

More trees never cause overfitting in a random forest; they just reduce the noise of the average, with diminishing returns. Error typically flattens somewhere between 100 and 500 trees. The cost is time and memory, both linear in the number of trees. The trees themselves are usually grown deep with no pruning, since the averaging takes care of variance.

Which features matter?

Forests give two common importance measures.

  • Impurity-based importance (feature_importances_): the total Gini decrease from all splits on each feature, averaged over trees. Free and fast, but biased towards features with many distinct values and computed on training data.
  • Permutation importance: shuffle one feature's column in a held-out set and measure how much the score drops. If shuffling a feature barely hurts, the model wasn't relying on it. Slower but more trustworthy.

Both measure what the model uses, not what causes the outcome. When two features are strongly correlated, the forest may split credit between them, or permutation may show each as unimportant because the other covers for it.

In code

Bagging from scratch, reusing scikit-learn's tree as the building block. The loop is the whole idea: bootstrap, grow, repeat, vote.

import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier

X, y = load_breast_cancer(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, random_state=0)
rng = np.random.default_rng(0)

trees = []
for b in range(100):
    idx = rng.integers(0, len(X_tr), len(X_tr))           # bootstrap: draw n rows WITH replacement
    tree = DecisionTreeClassifier(max_features="sqrt",      # random feature subset at every split
                                  random_state=b)
    trees.append(tree.fit(X_tr[idx], y_tr[idx]))

votes = np.mean([t.predict(X_te) for t in trees], axis=0)  # share of trees voting "1"
forest_pred = (votes > 0.5).astype(int)

single = DecisionTreeClassifier(random_state=0).fit(X_tr, y_tr)
print("one deep tree      :", round(single.score(X_te, y_te), 3))
print("first 5 trees alone:", [round(t.score(X_te, y_te), 3) for t in trees[:5]])
print("forest of 100      :", round((forest_pred == y_te).mean(), 3))

# one deep tree      : 0.912
# first 5 trees alone: [0.918, 0.93, 0.942, 0.93, 0.936]
# forest of 100      : 0.959

Each tree on its own scores 92–94%. The vote of 100 of them scores 96%, better than any of the first five. The scikit-learn version adds out-of-bag scoring and parallel training, and here we also ask which features mattered:

from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.inspection import permutation_importance
from sklearn.model_selection import train_test_split

data = load_breast_cancer()
X_tr, X_te, y_tr, y_te = train_test_split(data.data, data.target, test_size=0.3, random_state=0)

forest = RandomForestClassifier(n_estimators=500, oob_score=True, n_jobs=-1, random_state=0)
forest.fit(X_tr, y_tr)
print(f"out-of-bag accuracy: {forest.oob_score_:.3f}")
print(f"test accuracy      : {forest.score(X_te, y_te):.3f}")

imp = permutation_importance(forest, X_te, y_te, n_repeats=10, random_state=0)
for i in imp.importances_mean.argsort()[::-1][:3]:
    print(f"{data.feature_names[i]:22} {imp.importances_mean[i]:.3f}")

# out-of-bag accuracy: 0.957
# test accuracy      : 0.965
# worst area             0.019
# worst perimeter        0.015
# worst radius           0.015

n_jobs=-1 uses every CPU core, since the trees are independent. The permutation importances are small because many of the 30 features carry overlapping information (area, perimeter and radius all describe size), so shuffling any one of them costs little. For regression, use RandomForestRegressor. ExtraTreesClassifier ("extremely randomised trees") goes further and also picks split thresholds at random, which is faster and sometimes just as accurate.

Common pitfalls

  • Expecting extrapolation. Like a single tree, a forest predicts averages of training targets, so its predictions never leave the range seen in training. For trends that grow over time, see Time Series Forecasting.
  • Reading impurity importances as truth. They favour high-cardinality features (an ID column can look "important"). Use permutation importance on held-out data, and remember that importance is not causation.
  • Huge models. 500 fully grown trees on a million rows can take gigabytes of memory and be slow to predict. Limit max_depth or min_samples_leaf, or use fewer trees, if you need to deploy it.
  • Probabilities that aren't calibrated. The share of trees voting "yes" is a score, not a reliable probability. It tends to avoid the extremes near 0 and 1. Calibrate if you need real probabilities.
  • Data leakage still leaks. OOB error is honest about overfitting, but not about leakage. If a feature secretly contains the answer, OOB will happily report 99%. See Training, Validation and Test Sets.

Watch out The out-of-bag score treats rows as independent. If your rows are grouped (several rows per patient) or ordered in time, OOB rows from the same patient or the same week leak information and the estimate is too optimistic. Use grouped or time-based validation instead.

Where it leads

  • Gradient boosting builds trees sequentially, each one correcting the previous ones, rather than independently. It usually edges out random forests when tuned, at the cost of more tuning. See Gradient Boosting: XGBoost and LightGBM.
  • Isolation forests use random trees for Anomaly Detection: outliers get isolated in fewer random splits.
  • Bagging any model. Bagging works with any unstable learner, not just trees. Averaging several neural networks trained from different random starts (a "deep ensemble") is the same idea.
  • Interpretability tools such as SHAP values were made fast for tree ensembles. See Interpretability and Explainability.

A bit of history

Leo Breiman introduced bagging in 1996, showing that averaging models trained on bootstrap samples reduced error for unstable learners such as trees. The bootstrap itself is due to Bradley Efron (1979). Tin Kam Ho proposed "random decision forests" in 1995, building each tree on a random subset of features, and Yali Amit and Donald Geman used random feature selection at each split for shape recognition in 1997. Breiman combined bagging with per-split feature sampling in his 2001 paper Random Forests, which also introduced out-of-bag estimates and permutation importance.

Random forests were among the most successful general-purpose classifiers of the 2000s. A widely cited 2014 study by Fernández-Delgado and colleagues compared 179 classifiers on 121 datasets and found random forests most often at or near the top. Gradient-boosted trees have since overtaken them in competitions, but forests remain a favourite first model because they are so hard to get badly wrong.

Try it

  1. Using the variance formula, how many trees do you need with ρ=0.1\rho = 0.1 to get the variance within 10% of its floor ρσ2\rho\sigma^2?
  2. In the from-scratch code, remove max_features="sqrt" (so each tree sees all features) and re-run. Does the forest get better or worse? Why?
  3. Harder: compute the out-of-bag accuracy of your from-scratch forest. For each tree, keep the indices not in its bootstrap sample, and for each training row average only the predictions of trees that didn't see it.

Hint for 1: you need (1−ρ)/B≤0.1ρ(1-\rho)/B \le 0.1\rho, so B≥0.9/0.01=90B \ge 0.9/0.01 = 90.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. Why does a random forest consider only a random subset of features at each split?

  2. Trees in a forest have pairwise correlation ρ = 0.7. Going from 10 to 1,000 trees, what happens to the variance of the average (σ² = 1)?

  3. What is the out-of-bag (OOB) error?

  4. Your rows include several records per patient. The OOB score is 99%, but a grouped test gives 85%. Why?

  5. An ID column shows up as the most important feature by impurity-based importance. What should you do?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Course

Decision Forests course

Google · Beginner · Free

A short, clear course on decision trees, random forests and gradient-boosted trees, with diagrams.

Video

StatQuest

Josh Starmer · Beginner · Free

Short, cheerful, very clear videos on statistics and nearly every ML algorithm.

Paper

Random Forests

Leo Breiman · 2001 · Advanced · Paid

Breiman's paper introducing random forests.

Paper

Bagging Predictors

Leo Breiman · 1996 · Advanced · Paid

Introduced bootstrap aggregation: train many models on resampled data and average them.

Book

Interpretable Machine Learning

Christoph Molnar · Intermediate · Free

A clear guide to making black-box models explainable: feature importance, SHAP, LIME and more.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/ml/random-forests.md