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
- Builds on
- 8 concepts →
- Quiz
- 5 questions ↓
Read first
Decision TreesThis leads to
—The full path from zero — 8 concepts before this one
- What Is AI?
- Probability Basics
- How Machines Learn
- Probability Distributions
- Supervised, Unsupervised and Reinforcement Learning
- Entropy, Cross-Entropy and KL Divergence
- Supervised Learning
- Decision Trees
- 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:
- Each tree sees a different random resample of the training data.
- 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.
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 rows drawn with replacement from a training set of 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 . Over independent draws, it is missed every time with probability:
For it is 0.349; for 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 : it wobbles that much depending on which data it saw. If you average trees that are completely independent, the variance of the average is . 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", between 0 and 1), the variance of the average is:
The second term shrinks as you add trees. The first does not: correlation sets a floor. Take :
| Correlation | trees | trees | 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 , 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 features and may only choose the best split among those. Common defaults:
- classification: , where is the number of features (30 features → 5 per split);
- regression: scikit-learn now defaults to all features (, which is plain bagging), while 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 (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): . Exactly on the fence. A fourth tree saying 0.20 would make it : 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.
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_depthormin_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
- Using the variance formula, how many trees do you need with to get the variance within 10% of its floor ?
- 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?- 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 , so .
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Decision Forests course
A short, clear course on decision trees, random forests and gradient-boosted trees, with diagrams.
StatQuest
Short, cheerful, very clear videos on statistics and nearly every ML algorithm.
An Introduction to Statistical Learning (with Python)
The friendliest rigorous introduction to classical ML, with Python labs. Free PDF.
scikit-learn: Ensembles (Gradient Boosting, Random Forests, Bagging)
The guide to random forests, bagging, AdaBoost and histogram gradient boosting, including feature importance.
Random Forests
Breiman's paper introducing random forests.
Bagging Predictors
Introduced bootstrap aggregation: train many models on resampled data and average them.
Interpretable Machine Learning
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