In the previous article we built a decision tree: a flowchart of yes/no questions learned from data. It is easy to read, needs almost no preparation and handles non-linear problems, but it has one serious weakness. A tree grown deep enough memorises the noise in its training data, and a small change in that data can produce a very different tree. The random forest is the most popular cure. Instead of trusting a single tree, it grows hundreds of slightly different ones and lets them vote. It was introduced by Leo Breiman in 2001 and is still one of the strongest general-purpose models for tabular data, usually accurate with very little tuning.
This article explains the two ideas that make a forest work, builds one from scratch in Python by extending the tree code of the previous article, and tests it on the examples we already know: a classification problem, the wind-turbine power curve and the strength of concrete.
Where we left off: the problem with a single tree
A fully grown tree classifies every training example correctly, so its training accuracy is 100%, but how well it does on new data depends a lot on which examples it happened to see. This instability is called high variance: the model changes a lot when the data change a little. Figure 2 below makes it visible. Three trees were grown on three different resamples of the same 150 points, and their decision regions disagree in many places; each one has captured some of the noise, and each gets 79–85% of the test points right.
The remedy suggested by statistics is simple: averaging reduces variance. If you could train many independent models and average their predictions, the random errors would partly cancel while the signal would stay. A random forest does exactly this with trees, which are an ideal ingredient: a deep tree has low bias (it can fit almost anything) and high variance, and variance is the part that averaging removes.
The idea: a crowd of trees
A random forest repeats three steps, shown in Figure 1: draw a random resample of the training data, grow a tree on it, and finally combine all the trees: a majority vote for classification, or the average of the predictions for regression.
Two ingredients make the trees different from one another, and both are essential.
Ingredient 1: bagging
The resampling is a bootstrap: from a training set of $n$ rows, draw $n$ rows with replacement. Some rows are drawn several times and others not at all. The chance that a given row is never drawn is $(1 - 1/n)^n$, which tends to $1/e \approx 0.368$, so each tree is trained on about 63% of the distinct rows and the remaining 37% are left out. Growing one tree per bootstrap sample and aggregating the results is called bagging (bootstrap aggregating).
Ingredient 2: random subsets of features
Bagging alone has a limit. If one feature is much stronger than the others, every tree will choose it at the top, and the trees will look alike even though they were trained on different samples. Averaging very similar predictions removes little variance. Statistically, for $B$ trees whose predictions each have variance $\sigma^2$ and pairwise correlation $\rho$, the variance of their average is
Adding more trees makes the second term vanish, but the first term stays: the only way to go lower is to make the trees less correlated. The random forest does this by restricting the search at every split: instead of trying all $p$ features, each node looks at a random subset of $m$ features and chooses the best split among those. Breiman's rule of thumb is $m \approx \sqrt{p}$ for classification and $m \approx p/3$ for regression. (scikit-learn follows the first rule, but by default a regression forest considers all features.) A smaller $m$ gives more diverse trees, each slightly weaker; $m$ is the main tuning knob of the method.
The algorithm
- For $b = 1, \dots, B$:
- draw a bootstrap sample of the training data;
- grow a tree on it, normally without pruning and to full depth, choosing the best split at each node from a random subset of $m$ features.
- To predict a new example, pass it through all $B$ trees and take the majority class (classification) or the mean (regression).
Out-of-bag error: validation for free
Each tree never saw about 37% of the rows. For every training row we can therefore collect the votes of only those trees that did not have it in their sample, and compare the result to the true label. This out-of-bag (OOB) error is an honest estimate of the error on unseen data, obtained from the training set alone, without a separate validation set and without cross-validation. It is one of the practical advantages of the method, and we will check below that it is close to the real test error.
Implementation in Python
The forest needs only two small changes to the tree code of the previous article (the functions gini, variance, majority, mean and predict stay exactly as they were). best_split accepts a list of candidate features, build draws a random subset of the features at every node, and a RandomForest class does the bootstrapping, keeps track of the out-of-bag rows and combines the predictions. The same class works for classification and regression, through the same two parameters as before: the impurity function and the way a leaf value (here, also the aggregated prediction) is computed.
import random
def best_split(X, y, impurity=gini, features=None):
"""Best split among the given candidate features (all of them when features is None)."""
n = len(y)
best = (None, None, impurity(y))
for j in (range(len(X[0])) if features is None else features):
values = sorted({row[j] for row in X})
for lo, hi in zip(values, values[1:]):
t = (lo + hi) / 2
left = [y[i] for i in range(n) if X[i][j] <= t]
right = [y[i] for i in range(n) if X[i][j] > t]
score = (len(left) * impurity(left) + len(right) * impurity(right)) / n
if score < best[2] - 1e-12:
best = (j, t, score)
return best
def build(X, y, depth=0, max_depth=None, min_samples=2, impurity=gini, leaf_value=majority,
max_features=None, rng=random):
"""The tree from the previous article, plus one change: every node looks at a random subset of the features."""
node = {"n": len(y), "impurity": impurity(y), "value": leaf_value(y)}
if depth == max_depth or len(y) < min_samples or node["impurity"] == 0:
return node
features = rng.sample(range(len(X[0])), max_features) if max_features else None
j, t, _ = best_split(X, y, impurity, features)
if j is None:
return node
L = [i for i in range(len(y)) if X[i][j] <= t]
R = [i for i in range(len(y)) if X[i][j] > t]
kw = dict(max_depth=max_depth, min_samples=min_samples, impurity=impurity,
leaf_value=leaf_value, max_features=max_features, rng=rng)
return {**node, "feature": j, "threshold": t,
"left": build([X[i] for i in L], [y[i] for i in L], depth + 1, **kw),
"right": build([X[i] for i in R], [y[i] for i in R], depth + 1, **kw)}
class RandomForest:
def __init__(self, n_trees=100, max_features=None, impurity=gini, leaf_value=majority, seed=0, **tree_args):
self.n_trees, self.max_features = n_trees, max_features
self.impurity, self.leaf_value = impurity, leaf_value
self.rng, self.tree_args = random.Random(seed), tree_args
def fit(self, X, y):
n = len(y)
self.X, self.y, self.trees, self.oob = X, y, [], []
for _ in range(self.n_trees):
idx = [self.rng.randrange(n) for _ in range(n)] # bootstrap: n draws with replacement
self.trees.append(build([X[i] for i in idx], [y[i] for i in idx],
impurity=self.impurity, leaf_value=self.leaf_value,
max_features=self.max_features, rng=self.rng, **self.tree_args))
self.oob.append(set(range(n)) - set(idx)) # rows this tree has never seen
return self
def predict(self, x):
return self.leaf_value([predict(t, x) for t in self.trees]) # majority vote, or the mean
def oob_predict(self, i):
votes = [predict(t, self.X[i]) for t, out in zip(self.trees, self.oob) if i in out]
return self.leaf_value(votes) if votes else None
As a test, we generate the classic “two moons” data (two interleaving half-circles with noise), train a single fully grown tree and a forest of 100 trees on 150 points, and measure the accuracy on 150 unseen points:
import math
import random
def make_moons(n, noise, seed):
"""Two interleaving half-circles: a classic non-linear two-class problem."""
rnd = random.Random(seed)
pts = []
for _ in range(n // 2):
t = math.pi * rnd.random()
pts.append(((math.cos(t) + rnd.gauss(0, noise), math.sin(t) + rnd.gauss(0, noise)), 0))
t = math.pi * rnd.random()
pts.append(((1 - math.cos(t) + rnd.gauss(0, noise), 0.5 - math.sin(t) + rnd.gauss(0, noise)), 1))
rnd.shuffle(pts)
return [p for p, _ in pts], [c for _, c in pts]
X, y = make_moons(300, noise=0.3, seed=3)
X_train, y_train, X_test, y_test = X[:150], y[:150], X[150:], y[150:]
tree = build(X_train, y_train) # one fully grown tree
forest = RandomForest(n_trees=100, max_features=1, seed=1).fit(X_train, y_train)
def accuracy(model, X, y):
return sum(model(x) == t for x, t in zip(X, y)) / len(y)
print(f"single tree : {accuracy(lambda x: predict(tree, x), X_test, y_test):.3f}")
print(f"random forest: {accuracy(forest.predict, X_test, y_test):.3f}")
oob = [(forest.oob_predict(i), y_train[i]) for i in range(len(y_train))]
print(f"out-of-bag : {sum(p == t for p, t in oob) / len(oob):.3f} (estimated from the training data alone)")
single tree : 0.853
random forest: 0.887
out-of-bag : 0.893 (estimated from the training data alone)
The forest is a few percentage points better than the single tree, and the out-of-bag estimate, which never touched the test points, lands close to the actual test accuracy.
Does it work? Classification
One split of 150 test points is a small sample, so we repeat the experiment on 20 different random datasets of the same kind:
| Problem | Metric | One fully grown tree | Random forest (100 trees) |
|---|---|---|---|
| Moons (classification), mean of 20 splits | test accuracy | 85.9% | 89.5% |
| Wind-turbine power (regression) | test RMSE | 122 kW | 100 kW |
| Concrete strength (regression) | test RMSE | 4.0 MPa | 3.0 MPa |
On the moons problem, the forest is better in 18 of the 20 runs: its mean accuracy is 89.5% (standard deviation 2.6 points) against 85.9% (3.7 points) for a single tree. It is not only more accurate on average but also more stable from one dataset to the next, which is what the variance argument predicts.
How many trees?
A forest does not overfit as more trees are added: the error simply levels off. Figure 3 shows the test error and the out-of-bag error of the forest as the number of trees grows from 1 to 100. The error is erratic for the first few trees, then drops below the 14.7% of the single tree and settles near 11% after 20 to 50 trees. Adding trees costs time and memory but cannot hurt accuracy, so 100 to 500 trees is the usual range.
Random forests for regression
For a numerical target the trees are regression trees (variance as impurity, the mean as leaf value) and the forest averages their predictions. This has a visible smoothing effect. The staircase of a single tree becomes a much finer staircase, because averaging 100 trees whose steps are in slightly different places produces many small steps.
Figure 4 repeats the wind-turbine example of the previous article. A single fully grown tree follows the noise in the training data, with a test RMSE of 122 kW. The forest, grown on the same 60 readings, smooths most of it away and gets down to 100 kW. Its out-of-bag RMSE, computed from the training readings alone, is 104 kW, again close to the test value.
The same happens for the concrete-strength example: the forest, with the water–cement ratio and age as features, reaches a test error of 3.0 MPa, against 4.0 MPa for a single fully grown tree. The out-of-bag estimate is 3.1 MPa, and the noise floor of the data, the smallest error any model could reach, is 2.3 MPa.
Which features matter?
A forest offers two ways to rank the inputs. The impurity-based importance adds up, over all trees, how much each feature reduced the impurity at the splits where it was used; it is free, but it is computed on the training data and tends to favour features with many distinct values. The permutation importance shuffles one feature at a time on held-out data and records how much the error grows: a feature that the model relies on will hurt a lot when its values are scrambled.
For the concrete data the two measures tell a different story: by impurity the water–cement ratio accounts for 71% and age for 29%, while shuffling the values on test data increases the error by about the same amount for both (by 5.8 MPa for the ratio and 5.4 MPa for age, about 52% and 48%). Neither number is wrong; they answer different questions, which is why it is worth looking at both.
Using it in practice
In practice you would use scikit-learn rather than your own code:
from sklearn.ensemble import RandomForestClassifier
clf = RandomForestClassifier(n_estimators=100, max_features="sqrt", oob_score=True,
n_jobs=-1, random_state=0)
clf.fit(X_train, y_train)
print(clf.oob_score_, clf.score(X_test, y_test)) # OOB accuracy and test accuracy
print(clf.feature_importances_) # impurity-based importances
For a numerical target, use RandomForestRegressor. The settings that matter are few:
| Setting | What it does |
|---|---|
n_estimators | Number of trees. More is better, with diminishing returns after a few hundred. |
max_features | Features tried at each split: the main knob. Smaller values give more diverse (and individually weaker) trees. |
min_samples_leaf | Minimum size of a leaf. Larger values give smoother predictions, which helps on noisy regression data. |
max_depth | Usually left unlimited: the averaging takes care of the variance of deep trees. |
oob_score | Computes the out-of-bag estimate of the accuracy, a free validation score. |
n_jobs, random_state | Parallel training (the trees are independent) and reproducible results. |
Strengths and limitations
| Strengths | Limitations |
|---|---|
| Accurate with very little tuning. | Much less interpretable than a single tree: hundreds of trees cannot be read as rules. |
| Does not overfit as trees are added; the error levels off. | Larger models, and slower training and prediction than one tree. |
| Handles non-linear effects, interactions and mixed feature types; no scaling needed. | Predictions stay within the range of the training targets, so a forest cannot extrapolate. |
| Built-in out-of-bag error estimate and feature importances. | Impurity-based importances can be misleading; probabilities from the vote share are not well calibrated. |
| Trees are independent, so training parallelises easily. | On many tabular problems, a carefully tuned gradient-boosting model is a little more accurate. |
Beyond random forests
The forest belongs to a family of tree ensembles. Extremely randomised trees (“extra trees”) go one step further and also choose the split thresholds at random, which makes the trees even more different and training faster. Gradient boosting, in libraries such as XGBoost and LightGBM, takes the opposite approach: it grows shallow trees one after another, each trained to correct the errors of the previous ones. The two strategies attack different parts of the error: bagging, as in the random forest, reduces variance, while boosting reduces bias. Boosting often wins on accuracy but needs more careful tuning; a random forest is the one you can rely on to work well the first time.
Summary
- A random forest averages many deep decision trees, each grown on a bootstrap resample of the data, to cancel out the variance of any single tree.
- Choosing the best split from a random subset of the features at each node keeps the trees diverse, which makes the averaging effective.
- Classification forests vote; regression forests average. About 37% of the rows are left out of every tree, which gives a free out-of-bag estimate of the error.
- In our experiments the forest beat the single tree on all three problems, and its out-of-bag error matched the test error.
- Its price is interpretability: a forest is a good predictor but not a set of readable rules.
References
- L. Breiman, “Random Forests”, Machine Learning 45 (2001), 5–32.
- L. Breiman, “Bagging Predictors”, Machine Learning 24 (1996), 123–140.
- T. Hastie, R. Tibshirani, J. Friedman, The Elements of Statistical Learning, 2nd ed., Springer (2009), chapter 15.