Overview
A single decision tree asks a chain of yes or no questions about the features and is easy to follow, but it is unstable: change a few training rows and the tree can look completely different. A random forest grows many trees, each on a slightly different version of the data, and averages their answers. Each tree makes its own errors, and because the trees differ, many of those errors cancel in the average. Two sources of randomness keep the trees different: each sees a random resample of the rows, and each split may only choose among a random handful of features.
A short history
Leo Breiman published random forests in 2001, combining his own bagging method of 1996 with random feature selection at each split, an idea explored earlier by Tin Kam Ho in 1995 and by Amit and Geman. Averaging many decorrelated trees cuts the high variance of a single tree while keeping its flexibility. The method needs little tuning and gives a built-in error estimate from the rows each tree did not see, which made it a default for tabular data.
How it works
- For each tree, draw rows from the training data with replacement. This is a bootstrap sample, and about a third of the rows are left out of it.
- Grow a tree on that sample. At each node, look at a random subset of the features and find the split point that most reduces impurity.
- Send rows left or right of the threshold and repeat on each side, until max_depth is reached, a node is too small, or no split helps.
- Each leaf stores the mean target of its rows: the class shares for classification, the mean value for regression.
- To predict, pass a row down every tree and average the leaf values. For classification take the class with the highest average share.
- Score each row using only the trees that did not see it, giving oob_score_, an estimate of test performance that needs no held-out set.
Watch out for
- A forest cannot predict outside the range of targets it saw in training, because every prediction is an average of training values. Trends that continue beyond the data are flattened.
- Impurity-based feature_importances_ favour features with many distinct values, and split credit arbitrarily between correlated features.
- Adding trees never hurts accuracy but each one costs memory and prediction time, and the gain levels off.
- This is a small exact version that sorts each feature at each node. It is slow on large data compared with library implementations.
Use cases
When to use it
Tabular data with mixed feature types and little time for tuning. It is a strong default that needs no feature scaling and gives a built-in error estimate and feature ranking.
In industry
- Consumer electronics
- Body part recognition from depth images in Microsoft's Kinect, a published use of randomised decision forests.
- Banking
- Fraud and credit risk scoring on tabular features, often as a strong baseline that needs little tuning.
- Ecology and remote sensing
- Classifying land cover from satellite bands, and modelling where a species is likely to occur.
Choosing it: what must hold
- Tabular data with a class or number to predict.
- Enough memory and time to grow a few hundred trees.
- No need to predict beyond the range of the training targets, since trees cannot extrapolate.
When to choose something else
| If | Use instead |
|---|---|
| You want the best accuracy and can tune carefully | XGBoost, LightGBM or CatBoost |
| You need a single readable set of rules | A decision tree |
| The features are very sparse and high-dimensional, such as word counts | Logistic regression or Naive Bayes |
Math foundations
Gini impurity
How mixed a node is. It is 0 when all rows share one class and largest when the classes are evenly mixed. For regression the variance of the targets plays the same role.
Impurity decrease of a split
The tree picks the feature and threshold with the largest : the split whose two sides are purest on average, weighted by their sizes.
The form the template computes
With targets stored as one-hot rows (or as the value itself for regression), is their column sum. The same expression covers Gini and variance, so one tree builder serves both tasks.
The bootstrap leaves rows out
Drawing rows with replacement misses each given row about 37 percent of the time. Those out-of-bag rows act as a free test set for that tree.
The forest prediction
The average of the trees' leaf values. For classification these are class shares, and the predicted class is the one with the largest average.
Why averaging helps
If each tree has variance and any two trees have correlation , more trees shrink the second term toward zero. Only the first remains, which is why random feature subsets, which lower , matter.
Symbols
- share of a node's rows that belong to class k
- number of classes
- rows in the node, in its left child and in its right child
- Gini impurity of the left and right child
- column sums of the target matrix over the node and its children
- number of trees, n_estimators
- the prediction function of tree b
- variance of a single tree's prediction
- correlation between the predictions of two trees
Worked by hand
A node holds 8 rows: 4 of class A and 4 of class B. A split sends 3 A and 1 B to the left and 1 A and 3 B to the right.
The split lowers the impurity by 0.125. The template's form gives 1, which is the same number multiplied by the 8 rows in the node, so both rank splits identically.
Visual example
Loading the example.
Try this
- One tree is jagged. Raise the tree count and watch the edge smooth out.
- Compare with the decision tree lesson at the same depth.
Code sample
import numpy as np
from impl import RandomForest
from config import RandomForestConfig
rng = np.random.default_rng(0)
X = rng.uniform(-1, 1, size=(400, 4))
y = (X[:, 0] * X[:, 1] > 0).astype(int) # XOR-like rule on two of four features
forest = RandomForest(RandomForestConfig(n_estimators=30, max_features="all", seed=0)).fit(X, y)
print(forest.score(X, y)) # training accuracy, 1.0
print(forest.oob_score_) # out-of-bag accuracy, about 0.98
print(forest.feature_importances_.round(2)) # the first two features carry most of it
print(forest.predict_proba(X[:2])) # (2, 2), rows sum to 1Read the implementation (193 lines)
"""Random forest: bagged CART trees with random feature subsets, for classification and regression.
NumPy only. Both tasks share one tree builder. Targets are stored as a matrix Y of shape (n, k): one-hot class
indicators for classification (k = number of classes), the value itself for regression (k = 1). A leaf predicts
the mean of its rows of Y, which is the class distribution or the mean target. Minimising Gini impurity and
minimising variance are then the same computation: maximise sum(S_left^2) / n_left + sum(S_right^2) / n_right,
where S is the column sum of Y on each side.
"""
from __future__ import annotations
import math
import numpy as np
try:
from .config import RandomForestConfig
except ImportError: # run from the template's own folder
from config import RandomForestConfig
class _Tree:
"""One CART tree stored as flat lists. Node i is a leaf when `feature[i]` is -1."""
def __init__(self, max_depth, min_samples_split, min_samples_leaf, n_try, rng) -> None:
self.max_depth = max_depth
self.min_samples_split = min_samples_split
self.min_samples_leaf = min_samples_leaf
self.n_try = n_try # features examined at each split
self.rng = rng
self.feature: list[int] = []
self.threshold: list[float] = []
self.left: list[int] = []
self.right: list[int] = []
self.value: list[np.ndarray] = []
self.importance: np.ndarray | None = None
def fit(self, X: np.ndarray, Y: np.ndarray) -> "_Tree":
"""Grow the tree. X: (n, d). Y: (n, k) target matrix."""
self.importance = np.zeros(X.shape[1])
self._grow(X, Y, depth=0)
return self
def _new_node(self, Y: np.ndarray) -> int:
self.feature.append(-1)
self.threshold.append(0.0)
self.left.append(-1)
self.right.append(-1)
self.value.append(Y.mean(axis=0))
return len(self.feature) - 1
def _grow(self, X: np.ndarray, Y: np.ndarray, depth: int) -> int:
node = self._new_node(Y)
n = len(X)
if n < self.min_samples_split or (self.max_depth is not None and depth >= self.max_depth):
return node
split = self._best_split(X, Y)
if split is None:
return node
feature, threshold, gain = split
go_left = X[:, feature] <= threshold
self.feature[node], self.threshold[node] = feature, threshold
self.importance[feature] += gain
self.left[node] = self._grow(X[go_left], Y[go_left], depth + 1)
self.right[node] = self._grow(X[~go_left], Y[~go_left], depth + 1)
return node
def _best_split(self, X: np.ndarray, Y: np.ndarray):
"""Best (feature, threshold, impurity decrease) over a random feature subset, or None if no split helps."""
n, d = X.shape
total = Y.sum(axis=0)
parent = float(total @ total) / n
best_gain, best = 1e-10, None
for feature in self.rng.permutation(d)[: self.n_try]:
order = np.argsort(X[:, feature], kind="stable")
x = X[order, feature]
left_sum = np.cumsum(Y[order], axis=0)[:-1] # (n - 1, k): sums of the first 1 .. n-1 rows
n_left = np.arange(1, n)
n_right = n - n_left
score = (left_sum**2).sum(axis=1) / n_left + ((total - left_sum) ** 2).sum(axis=1) / n_right
valid = (x[1:] > x[:-1]) & (n_left >= self.min_samples_leaf) & (n_right >= self.min_samples_leaf)
if not valid.any():
continue
score = np.where(valid, score, -np.inf)
pos = int(np.argmax(score))
gain = float(score[pos]) - parent
if gain > best_gain:
best_gain, best = gain, (int(feature), float(0.5 * (x[pos] + x[pos + 1])), gain)
return best
def predict(self, X: np.ndarray) -> np.ndarray:
"""Leaf values for every row. X: (n, d). Returns shape (n, k)."""
feature = np.array(self.feature)
threshold = np.array(self.threshold)
left, right = np.array(self.left), np.array(self.right)
node = np.zeros(len(X), dtype=int)
active = np.flatnonzero(feature[node] >= 0)
while len(active):
at = node[active]
go_left = X[active, feature[at]] <= threshold[at]
node[active] = np.where(go_left, left[at], right[at])
active = active[feature[node[active]] >= 0]
return np.array(self.value)[node]
class RandomForest:
"""Random forest. After `fit`: `trees_`, `feature_importances_` (d,), `oob_score_` (when bootstrapping)."""
def __init__(self, config: RandomForestConfig | None = None) -> None:
self.config = config or RandomForestConfig()
self.trees_: list[_Tree] = []
self.classes_: np.ndarray | None = None
self.feature_importances_: np.ndarray | None = None
self.oob_score_: float | None = None
self._single_target = True
def _n_try(self, d: int) -> int:
"""Number of features examined at each split for d input features."""
if self.config.max_features == "sqrt":
return max(1, int(math.sqrt(d)))
if self.config.max_features == "log2":
return max(1, int(math.log2(d)))
return d
def fit(self, X: np.ndarray, y: np.ndarray) -> "RandomForest":
"""Grow the forest.
X: features, shape (n, d). y: shape (n,). Labels of any hashable type for classification, real values
for regression.
"""
cfg = self.config
X = np.asarray(X, dtype=float)
y = np.asarray(y)
if X.ndim != 2 or len(X) != len(y):
raise ValueError("X must have shape (n, d) and y must have n entries")
n, d = X.shape
if cfg.task == "classification":
self.classes_, y_index = np.unique(y, return_inverse=True)
Y = np.eye(len(self.classes_))[y_index]
else:
Y = y.astype(float).reshape(n, 1)
rng = np.random.default_rng(cfg.seed)
self.trees_ = []
oob_sum = np.zeros_like(Y)
oob_count = np.zeros(n)
for _ in range(cfg.n_estimators):
rows = rng.integers(0, n, size=n) if cfg.bootstrap else np.arange(n)
tree = _Tree(cfg.max_depth, cfg.min_samples_split, cfg.min_samples_leaf, self._n_try(d), rng)
tree.fit(X[rows], Y[rows])
self.trees_.append(tree)
if cfg.bootstrap:
unseen = np.setdiff1d(np.arange(n), rows)
oob_sum[unseen] += tree.predict(X[unseen])
oob_count[unseen] += 1
importance = np.sum([t.importance for t in self.trees_], axis=0)
self.feature_importances_ = importance / importance.sum() if importance.sum() > 0 else importance
self.oob_score_ = None
seen = oob_count > 0
if cfg.bootstrap and seen.any():
oob_mean = oob_sum[seen] / oob_count[seen, None]
if cfg.task == "classification":
self.oob_score_ = float((oob_mean.argmax(axis=1) == Y[seen].argmax(axis=1)).mean())
else:
ss_res = np.sum((Y[seen] - oob_mean) ** 2)
self.oob_score_ = float(1.0 - ss_res / np.sum((Y[seen] - Y[seen].mean()) ** 2))
return self
def _average(self, X: np.ndarray) -> np.ndarray:
"""Mean of the trees' leaf values. X: (n, d). Returns shape (n, k)."""
if not self.trees_:
raise RuntimeError("call fit before predicting")
X = np.asarray(X, dtype=float)
return np.mean([tree.predict(X) for tree in self.trees_], axis=0)
def predict_proba(self, X: np.ndarray) -> np.ndarray:
"""Class probabilities (classification only). X: (n, d). Returns (n, C); columns follow `classes_`."""
if self.config.task != "classification":
raise RuntimeError("predict_proba is for classification forests")
return self._average(X)
def predict(self, X: np.ndarray) -> np.ndarray:
"""Predicted labels (classification) or values (regression). X: (n, d). Returns shape (n,)."""
out = self._average(X)
if self.config.task == "classification":
return self.classes_[out.argmax(axis=1)]
return out[:, 0]
def score(self, X: np.ndarray, y: np.ndarray) -> float:
"""Accuracy for classification, R^2 for regression."""
y = np.asarray(y)
pred = self.predict(X)
if self.config.task == "classification":
return float((pred == y).mean())
return float(1.0 - np.sum((y - pred) ** 2) / np.sum((y - y.mean()) ** 2))- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 8, run with
python3 -m unittest -v
Practice
Take a classification data set with a few informative features and several pure noise features. Fit RandomForest with RandomForestConfig n_estimators 1, 10 and 100, and for each compare oob_score_ with score on a held-out set. Print feature_importances_ and check that the noise features rank low. Then set max_features to all and see whether the scores change.
Check on learning
- Each tree in the forest is grown deep and overfits its sample. Why does averaging many overfit trees give a model that does not overfit?
A way to think about it
Split the error into a part shared by all trees and a part that differs from tree to tree. Averaging removes one of them. Look at the variance formula.
- Why does restricting each split to a random subset of features improve the forest, even though it makes every single tree worse?
A way to think about it
Suppose one feature is very strong. Without the restriction every tree splits on it first and the trees look alike. Consider what that does to .
- The out-of-bag score is computed on training rows. Why is it still an honest estimate of performance on new data?
A way to think about it
For any one row, look at which trees are allowed to vote. Ask whether those trees ever saw that row.
- A forest is trained on house prices up to one million. What will it predict for a house that is clearly worth three million, and why?
A way to think about it
Every leaf stores a mean of training targets, and the forest averages leaves. Think about the largest value such an average can take.