Sub topic 8
The Complete Random Forest Algorithm
This chapter assembles the pieces from earlier chapters into one algorithm. It assumes you know how a decision tree picks splits, what bootstrap sampling is, and how bagging averages models. It also assumes you can read basic NumPy and scikit-learn code. Here you will see the full training and prediction procedure, why each ingredient is there, and where implementations differ from the textbook description.
The algorithm in one pass
A random forest is a collection of decision trees. Each tree is trained on a different bootstrap sample of the training set. At every split, each tree considers only a random subset of the features. Predictions from all trees are combined by voting (classification) or averaging (regression).
Given a training set of N rows and p features, and a forest size of B trees, training works like this:
- For each tree b = 1 to B, draw a bootstrap sample of N rows, sampling with replacement.
- Grow a decision tree on that sample. At every node, choose m features at random from the p available. Find the best split using only those m features and the usual impurity criterion.
- Split the node into two children and repeat step 2 on each child.
- Stop growing a branch when a stopping rule applies, such as a pure node, a minimum leaf size, or a maximum depth.
- Keep the tree. Do not prune it.
To predict for a new row, pass it through all B trees and combine their outputs.
Two sources of randomness
The forest uses two separate random mechanisms. They do different jobs.
- Bootstrap sampling changes which rows each tree sees. A bootstrap sample of N rows contains about 63% of the distinct original rows. The rest are left out, and some rows appear more than once.
- Feature subsampling changes which columns each split can use. It is applied at every node, not once per tree.
The second mechanism is what separates a random forest from plain bagging of trees. Suppose one feature is much stronger than the others. In bagged trees, almost every tree uses that feature at the root, so the trees look alike and their errors are correlated. Averaging correlated predictions removes less variance. Restricting each split to a random subset forces some splits to use weaker features, so the trees become more different from each other.
Why decorrelation matters
If you average B predictions, each with variance σ² and pairwise correlation ρ, the variance of the average is:
ρσ² + (1 − ρ)σ² / B
As B grows, the second term vanishes. The first term, ρσ², does not. Adding more trees cannot push the variance below that floor. Only lowering the correlation ρ does.
Feature subsampling lowers ρ. The price is that each tree is a little weaker, because it is sometimes denied its best split. This raises the tree's bias slightly. The forest works when the drop in ρ outweighs that cost, which it usually does.
The number of features per split
The parameter m, called max_features in scikit-learn, controls the trade-off between tree strength and tree correlation.
| Setting | Effect |
|---|---|
| m = p (all features) | Equivalent to bagged trees. Strongest individual trees, highest correlation. |
| m = 1 | Each split uses a single random feature. Very different trees, but each one is weak. |
| m = sqrt(p) | Common default for classification. |
| m = p / 3 | Common textbook default for regression. |
In scikit-learn, RandomForestClassifier defaults to max_features="sqrt". RandomForestRegressor defaults to max_features=1.0, which means all features. A regression forest with that default is therefore bagged trees unless you change it. This surprises many people, so set the value deliberately for regression.
One more detail. If no valid split exists among the m sampled features, scikit-learn keeps looking at further features until it finds a valid split or runs out. So the subset is a starting point, not a hard wall.
Building a forest by hand
The following code implements the algorithm directly from scikit-learn trees. Each tree is fit on a bootstrap sample, and max_features="sqrt" makes each split consider a random subset of features.
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())Three points in this code map to the algorithm:
rng.integers(0, len(X_train), size=len(X_train))draws row indices with replacement. That is the bootstrap.max_features="sqrt"applies feature subsampling inside each tree, at every split.- No
max_depthis set, so each tree grows until its leaves are pure. This is deliberate. The trees are low-bias and high-variance, and averaging handles the variance.
The vote line only works for labels 0 and 1. For more classes, you would count votes per class, or better, average the class probabilities.
How the prediction is combined
The two output types are combined differently.
- Regression: the forest prediction is the mean of the tree predictions.
- Classification: there are two options. Hard voting takes the most common class label. Soft voting averages each tree's class probabilities and picks the class with the highest mean.
scikit-learn uses soft voting. Each tree's predict_proba returns the fraction of training samples of each class in the leaf, and the forest averages those. Because fully grown leaves are usually pure, individual trees output almost only 0 or 1 probabilities. The forest probability is then close to the fraction of trees that voted for a class.
Be careful reading these numbers as calibrated probabilities. A forest tends to be underconfident at the extremes. For example, it rarely outputs exactly 0 or 1, because a few trees nearly always disagree. If you need well-calibrated probabilities, calibrate the output afterward.
Training with scikit-learn
In practice you use the library class. It does the same work, adds parallelism, and tracks out-of-bag information.
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
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
)
clf = RandomForestClassifier(
n_estimators=300, oob_score=True, n_jobs=-1, random_state=0
)
clf.fit(X_train, y_train)
print("OOB accuracy: ", clf.oob_score_)
print("Test accuracy:", clf.score(X_test, y_test))The parameter n_estimators is B. n_jobs=-1 trains trees in parallel on all CPU cores. This works because the trees are independent of each other. No tree needs the result of another. That independence is also why forest training scales well with cores, unlike boosting, where each tree depends on the previous ones.
Seeing the variance reduction
The claim that averaging reduces variance can be checked. This code compares a single fully grown tree with a forest, using 5-fold cross-validation.
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
from sklearn.tree import DecisionTreeClassifier
X, y = load_breast_cancer(return_X_y=True)
tree = DecisionTreeClassifier(random_state=0)
forest = RandomForestClassifier(n_estimators=200, random_state=0, n_jobs=-1)
for name, model in [("single tree", tree), ("random forest", forest)]:
scores = cross_val_score(model, X, y, cv=5)
print(f"{name}: mean={scores.mean():.3f}, std={scores.std():.3f}")Expect the forest to have a higher mean accuracy and, usually, a smaller standard deviation across folds. The exact numbers depend on your scikit-learn version, but the direction is stable.
Common mistakes and edge cases
- Expecting more trees to cause overfitting. Adding trees does not overfit in the usual sense. Test error flattens as B grows. Extra trees only cost time and memory. The floor ρσ² explains why the curve levels off.
- Pruning or limiting depth by habit. Unlike a single tree, a forest tolerates deep trees. Limit depth when you need smaller models, faster prediction, or when noisy labels make leaves fit noise. Treat it as a tuning choice, not a requirement.
- Forgetting that features need no scaling. Splits compare a feature to a threshold, so monotonic rescaling does not change the trees. You can skip standardization.
- Passing categorical text columns. The algorithm splits on numeric thresholds. Encode categories first. Recent scikit-learn versions handle missing values in some tree estimators, but check the documentation for your installed version before relying on that.
- Extrapolating in regression. A tree predicts an average of training targets in a leaf. A forest therefore never predicts outside the range of the training targets, and it cannot continue a trend beyond the training data.
- Imbalanced classes. Bootstrap samples inherit the imbalance, and a rare class may be nearly absent from some samples. Consider
class_weight="balanced"or"balanced_subsample", which reweights classes within each bootstrap sample. - Reproducibility. Set
random_state. Withn_jobs, results stay reproducible for a fixed seed, because each tree gets its own seed before the parallel work starts.
Summary of the algorithm's design
Each ingredient has one purpose.
| Ingredient | Purpose |
|---|---|
| Deep, unpruned trees | Keep bias low |
| Bootstrap samples | Make trees see different data |
| Random features per split | Lower correlation between trees |
| Averaging or voting | Reduce variance |
Exercise
A forest of B trees has per-tree prediction variance σ² = 4 and pairwise correlation ρ = 0.5. (a) What is the variance of the averaged prediction for B = 100? (b) What is the lowest variance any number of trees could reach? (c) What would you change to get below that floor?
Show answer
(a) Variance = ρσ² + (1 − ρ)σ²/B = 0.5 × 4 + 0.5 × 4 / 100 = 2 + 0.02 = 2.02. (b) The floor is ρσ² = 2, reached as B grows without limit. (c) Adding trees cannot go below 2. You must lower the correlation ρ, for example by reducing max_features so that splits are more varied between trees.
Exercise
You train a RandomForestRegressor with default settings and find that its trees look very similar to each other. Why might that happen, and what is the fix?
Show answer
The regressor's default is maxfeatures=1.0, so every split considers all features. The forest is then plain bagging, and a strong feature dominates the top splits in every tree. Set maxfeatures to a smaller value, such as 0.33 (about p / 3), to decorrelate the trees, and tune it with cross-validation.