A single decision tree is easy to understand but unreliable: change a few training rows and you can get a completely different tree, and an unlimited tree overfits badly. A random forest fixes both problems with a simple idea: train hundreds of different trees and let them vote.
It's the "wisdom of the crowd". One person guessing the number of sweets in a jar is often far off; the average of a hundred guesses is usually close, because individual errors cancel out. Random forests are accurate, hard to break, need little tuning, and work well out of the box on almost any table of data, which is why they're one of the most widely used models in industry. This lesson explains how they work, shows them beating a single tree, and covers tuning, the out-of-bag score and feature importance.
How a random forest works
A random forest makes its trees different from each other in two ways:
- Bootstrap samples (bagging). Each tree trains on a random sample of the training rows, drawn with replacement: some rows appear twice, others not at all. About 63% of the distinct rows end up in each sample.
- Random features at each split. At every split, a tree may only choose from a random subset of the features (by default √(number of features) for classification). This stops every tree from starting with the same strong feature.
Then, to predict:
- Classification: every tree votes, and the majority wins. (Scikit-learn actually averages the trees' probabilities, which works the same way.)
- Regression: the trees' predictions are averaged.
Each tree is grown deep and overfits in its own way. Because the trees are different, their errors point in different directions and cancel out in the vote, while the real pattern, which all trees share, remains. The combined bagging vs boosting lesson explains this "variance reduction" in more detail.
One tree vs a forest
We'll use the Spambase data: 4,601 emails, each described by 57 word and character frequencies, labelled spam or not spam.
Download the data: spambase.csv (1.1 MB), or from the original source, the UCI Machine Learning Repository. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with
pd.read_csv("spambase.csv").
from sklearn.datasets import fetch_openml
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
X, y = fetch_openml(data_id=44, as_frame=True, return_X_y=True) # Spambase
y = y.astype(int) # 1 = spam, 0 = not spam
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42)
tree = DecisionTreeClassifier(random_state=0)
forest = RandomForestClassifier(n_estimators=300, random_state=0, n_jobs=-1)
for name, model in [("One tree", tree), ("Random forest", forest)]:
scores = cross_val_score(model, X_train, y_train, cv=5)
print(f"{name:14}: {scores.mean():.3f} (± {scores.std():.3f})")
One tree : 0.904 (± 0.020)
Random forest : 0.953 (± 0.014)
The forest is clearly more accurate: 95.3% against 90.4% for one tree. (The ± shows how much the score varied between the five folds.) n_estimators=300 is the number of trees; n_jobs=-1 trains them in parallel on all CPU cores. No scaling was needed: trees don't care about feature scale.
forest.fit(X_train, y_train)
print("Test accuracy:", round(forest.score(X_test, y_test), 3))
Test accuracy: 0.949
How many trees?
More trees never makes a random forest overfit; it just gets more stable, with diminishing returns:
import numpy as np
import matplotlib.pyplot as plt
sizes = [1, 5, 10, 25, 50, 100, 200, 400]
scores = [cross_val_score(RandomForestClassifier(n_estimators=n, random_state=0, n_jobs=-1),
X_train, y_train, cv=5).mean() for n in sizes]
fig, ax = plt.subplots()
ax.plot(sizes, scores, marker="o")
ax.set_xscale("log")
ax.set_xlabel("Number of trees (log scale)")
ax.set_ylabel("Cross-validated accuracy")
ax.set_title("More trees help, then level off")
plt.show()
Accuracy climbs quickly and then flattens. A few hundred trees is usually plenty; beyond that, you only pay in training time and memory.
The out-of-bag score: free validation
Each tree never sees about a third of the training rows (those left out of its bootstrap sample). Those out-of-bag (OOB) rows can test that tree. Combining these gives a validation score without a separate validation set:
oob_forest = RandomForestClassifier(n_estimators=300, oob_score=True, random_state=0, n_jobs=-1)
oob_forest.fit(X_train, y_train)
print("OOB accuracy:", round(oob_forest.oob_score_, 3))
OOB accuracy: 0.955
Very close to the cross-validated score, for the cost of one training run. It's handy for large datasets where cross-validation is slow.
Important settings
| Setting | Default | Effect |
|---|---|---|
n_estimators | 100 | Number of trees. More is more stable but slower |
max_features | "sqrt" (classification) | Features to choose from at each split. Lower means more diverse trees |
max_depth | None | Depth of each tree. Usually left unlimited; limit it to save memory or reduce overfitting on noisy data |
min_samples_leaf | 1 | Minimum rows per leaf. Raising it (e.g. 3–10) smooths predictions |
class_weight | None | "balanced" for imbalanced data |
n_jobs | None | -1 uses all CPU cores |
Random forests are famously forgiving: the defaults are often within a percent or two of the best settings. If you tune, start with max_features and min_samples_leaf.
Feature importance
A forest averages each tree's impurity-based importances:
import pandas as pd
importance = pd.Series(forest.feature_importances_, index=X.columns)
print(importance.sort_values(ascending=False).head(6).round(3))
char_freq_%21 0.121
word_freq_remove 0.088
char_freq_%24 0.082
capital_run_length_average 0.065
word_freq_free 0.059
capital_run_length_longest 0.058
dtype: float64
The frequency of "!" matters most, then the word "remove", the "$" sign, and the length of runs of capital letters: the classic signs of spam. Impurity-based importance is fast but biased towards features with many distinct values, and it splits credit between correlated features. Permutation importance is more trustworthy: it shuffles one feature at a time on test data and measures how much the score drops:
from sklearn.inspection import permutation_importance
result = permutation_importance(forest, X_test, y_test, n_repeats=10, random_state=0)
perm = pd.Series(result.importances_mean, index=X.columns)
print(perm.sort_values(ascending=False).head(5).round(3))
word_freq_remove 0.027
char_freq_%21 0.018
word_freq_hp 0.017
capital_run_length_average 0.010
char_freq_%24 0.006
dtype: float64
The order changes: "remove" is now top, and "hp" appears, a word that marks the genuine emails in this dataset (they came from staff at HP Labs). The values are small because many features carry overlapping information: shuffle "!" and the forest can still lean on "$" and the capital letters. That's a useful lesson in itself: "importance" depends on which other features are present.
Random forests for regression
RandomForestRegressor works the same way, averaging the trees' predictions. On the California housing data from the house price project, a default random forest achieves an error close to gradient boosting's, with no tuning.
Strengths and weaknesses
| Strengths | Weaknesses |
|---|---|
| Accurate out of the box, little tuning | Slower and larger than a single tree or linear model |
| Hard to overfit by adding trees | Less interpretable than one tree |
| No scaling; handles non-linear patterns and interactions | Can't extrapolate beyond the training range |
| OOB score and importances built in | Usually slightly less accurate than well-tuned gradient boosting |
Practice
- Train a forest with
max_features=1(each split considers one random feature). Is it better or worse than the default?
Show the answer
m = RandomForestClassifier(max_features=1, n_estimators=300, random_state=0, n_jobs=-1)
print(round(cross_val_score(m, X_train, y_train, cv=5).mean(), 3))
0.956
0.956, about the same as the default's 0.953. With 57 features, many of them useful, even a randomly chosen single feature at each split is often informative, and the trees become more varied. On data with only a few useful features among many useless ones, max_features=1 is usually worse, because most splits are forced onto useless features.
- Why can't adding more trees cause a random forest to overfit?
Show the answer
Each tree is trained independently and the forest averages them. More trees only make the average more stable; they don't make the model more flexible. Overfitting comes from the individual trees, controlled by settings such as min_samples_leaf.
- What fraction of rows does each bootstrap sample leave out, on average?
Show the answer
About 37%: the chance a given row is never picked in n draws is (1 − 1/n)ⁿ ≈ 1/e ≈ 0.368. Those are the out-of-bag rows.
Interview questions
How does a random forest work?
It trains many decision trees, each on a bootstrap sample of the rows and considering a random subset of features at each split, then combines them by majority vote (classification) or averaging (regression). The randomness decorrelates the trees so their errors cancel.
What is the out-of-bag score?
An estimate of generalisation performance computed by predicting each training row using only the trees that didn't see it in their bootstrap sample. It acts as built-in validation.
Why is a random forest better than a single decision tree?
Single deep trees have high variance: small data changes give very different trees. Averaging many decorrelated trees greatly reduces variance while keeping low bias, giving better and more stable accuracy.
What to learn next
- Understand the two big ensemble strategies in bagging vs boosting.
- Revisit decision trees explained.