Sub topic 8
The complete random forest algorithm
This chapter assumes you know how a single decision tree is grown, why unpruned trees overfit, and how bootstrap sampling and bagging work. It joins those pieces into the full algorithm and builds a small forest by hand.
The algorithm
A random forest of B trees is built like this:
- For each tree b = 1, ..., B, draw a bootstrap sample of the training set. The sample has n rows, drawn with replacement.
- Grow a decision tree on that sample. At every node, pick m features at random from the p available. Search only those m features for the best split, using the usual impurity criterion.
- Grow the tree deep, with little or no pruning. Stop only at the limits you set, such as
max_depthormin_samples_leaf. - To predict, send a new row through every tree. For classification, take a majority vote. For regression, take the mean.
The only changes from plain bagging are the random feature subset in step 2 and the deep trees in step 3.
Why both sources of randomness matter
Suppose each tree has prediction variance σ², and any two trees have correlation ρ. The variance of their average is:
ρσ² + (1 − ρ)σ² / B
Adding trees shrinks the second term toward zero. The first term, ρσ², stays. Bootstrap sampling alone leaves ρ high. If one feature is very strong, every tree splits on it near the root, and the trees look alike. Restricting each split to m random features forces some trees to use other features. This lowers ρ, and with it the floor on the variance.
Deep trees keep the bias of each tree low. Averaging then removes most of the variance that deep trees would otherwise carry.
Choosing m
| Task | Common default for m | scikit-learn default |
|---|---|---|
| Classification | square root of p | `max_features="sqrt"` |
| Regression | about p / 3 | `max_features=1.0` (all features) |
For regression, scikit-learn's default of all features makes the forest plain bagging. Try lower values such as 0.33 and compare.
A forest built by hand
The code below implements steps 1 to 4 with scikit-learn's DecisionTreeClassifier. Setting max_features="sqrt" on the tree gives the per-split feature subset.
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_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=0, stratify=y
)
rng = np.random.default_rng(0)
trees = []
for i in range(25):
idx = rng.integers(0, len(X_train), size=len(X_train)) # bootstrap sample
tree = DecisionTreeClassifier(max_features="sqrt", random_state=i)
trees.append(tree.fit(X_train[idx], y_train[idx]))
votes = np.stack([t.predict(X_test) for t in trees])
pred = (votes.mean(axis=0) > 0.5).astype(int) # majority vote for 0/1 labels
print("Hand-built forest accuracy:", (pred == y_test).mean())The averaging line works because labels are 0 and 1. A mean above 0.5 means most trees voted for class 1.
Common errors
- Expecting more trees to overfit. Adding trees does not cause overfitting. Accuracy levels off, and extra trees only cost time and memory.
- Setting m to all features by habit. The trees become highly correlated and the forest behaves like bagging.
- Assuming scikit-learn uses hard voting.
RandomForestClassifieraverages the trees' predicted class probabilities and picks the largest. This usually matches the majority vote, but it can differ on close calls. - Forgetting that rows repeat. A bootstrap sample holds about 63% of the distinct training rows. The rest are left out of that tree, which the out-of-bag chapter uses.
Exercise
A forest has B = 100 trees. Each tree has prediction variance σ² = 1, and any two trees have correlation ρ = 0.5. What is the variance of the averaged prediction? What does it approach as B grows?
Show answer
Variance = ρσ² + (1 − ρ)σ² / B = 0.5 + 0.5 / 100 = 0.505. As B grows it approaches ρσ² = 0.5. More trees cannot push it lower, so the next gain has to come from reducing ρ, for example with a smaller m.