TExcelTAD

Random Forests

Bagged trees are still correlated: when one feature is very strong, nearly every tree puts it at the root, and the trees make similar mistakes. A random forest (Breiman, 2001) adds one more source of randomness: at every split, a tree may only choose among a random subset of max_features features. The trees get individually weaker but much less alike, and their average gets better. With almost no tuning, random forests are among the most reliable models for tabular data. The Machine Learning course introduces them with scikit-learn; here you build one from bootstrap samples and feature-restricted trees.

The algorithm

For b=1,…,Bb = 1, \dots, B:

  1. draw a bootstrap sample of the training rows;
  2. grow a deep tree on it, but at each split consider only mm features drawn at random (max_features);

then predict by averaging the trees' class probabilities (classification) or predictions (regression). Typical defaults are m=dm = \sqrt{d} for classification and m=dm = d (no feature sampling, so plain bagging) for regression in scikit-learn.

Recall the variance of an average of BB models with variance σ2\sigma^2 and pairwise correlation ρ\rho from Bagging:

ρ σ2+1−ρBσ2.\rho \, \sigma^2 + \frac{1 - \rho}{B} \sigma^2 .

With many trees only ρσ2\rho\sigma^2 remains. A smaller mm lowers ρ\rho (trees cannot all pick the same feature) but raises each tree's error. The best mm balances the two.

A forest from scratch

The ensemble logic is a dozen lines; each tree is scikit-learn's DecisionTreeClassifier with max_features set, which is exactly the per-split feature sampling from the CART lesson. On the same generated data as the bagging lesson, the example measures how accurate one tree is on average, how correlated the trees' test predictions are, and how accurate the forest of 200 trees is, for several values of mm:

python · try it yourself
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier

X, y = make_classification(n_samples=600, n_features=20, n_informative=6, flip_y=0.05, random_state=0)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)

def forest_fit(X, y, n_trees, max_features, seed=0):
    rng = np.random.default_rng(seed)
    trees = []
    for b in range(n_trees):
        idx = rng.integers(0, len(y), len(y))          # bootstrap rows
        tree = DecisionTreeClassifier(max_features=max_features,   # random feature subset at every split
                                      random_state=int(rng.integers(1_000_000)))
        trees.append(tree.fit(X[idx], y[idx]))
    return trees

def forest_proba(trees, X):
    return np.mean([t.predict_proba(X) for t in trees], axis=0)   # average the trees' class probabilities

for mf in [20, 8, 4, 1]:
    trees = forest_fit(X_tr, y_tr, 200, mf)
    preds = np.array([t.predict(X_te) for t in trees])
    corr = np.corrcoef(preds)[np.triu_indices(len(trees), 1)].mean()   # how alike the trees' test predictions are
    strength = np.mean([np.mean(p == y_te) for p in preds])               # accuracy of one tree on average
    acc = np.mean(forest_proba(trees, X_te).argmax(axis=1) == y_te)
    print(f"max_features {mf:2d}: one tree {strength:.3f}  correlation {corr:.2f}  forest of 200 {acc:.3f}")

sk = RandomForestClassifier(n_estimators=200, max_features="sqrt", oob_score=True, random_state=0).fit(X_tr, y_tr)
print("RandomForestClassifier (sqrt(20) = 4 features): test", round(sk.score(X_te, y_te), 3), " OOB", round(sk.oob_score_, 3))
max_features 20: one tree 0.771  correlation 0.50  forest of 200 0.861
max_features  8: one tree 0.747  correlation 0.41  forest of 200 0.861
max_features  4: one tree 0.715  correlation 0.32  forest of 200 0.861
max_features  1: one tree 0.624  correlation 0.14  forest of 200 0.806
RandomForestClassifier (sqrt(20) = 4 features): test 0.839  OOB 0.833

Going from 20 features per split (plain bagging) to 4, single trees get weaker (0.771 to 0.715) but much less correlated (0.50 to 0.32), and the forest holds its accuracy at 0.861. With one feature per split, the trees are nearly independent but too weak, and the forest drops to 0.806. On this data the gain from decorrelation just offsets the loss in strength; on data with a few dominant features it is usually a clear gain. scikit-learn's forest uses its own random draws and lands at 0.839 on the same 180 test rows, a difference of four rows, within the noise; its OOB estimate (0.833) is close.

Feature importance, two ways

Forests report feature_importances_: the total impurity decrease each feature produced, averaged over trees. It is computed on training data and is biased towards features with many possible split points. Permutation importance is the honest alternative: shuffle one feature's column in held-out data and measure how much the score drops. Two pure-noise columns are added to the breast-cancer data to see how each method treats them:

python · try it yourself
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.inspection import permutation_importance

data = load_breast_cancer()
X, y = data.data, data.target
rng = np.random.default_rng(0)
X = np.column_stack([X, rng.normal(size=len(y)), rng.integers(0, 500, len(y))])   # two pure-noise columns
names = list(data.feature_names) + ["noise (normal)", "noise (500 ids)"]
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)

rf = RandomForestClassifier(n_estimators=300, random_state=0, n_jobs=1).fit(X_tr, y_tr)
print("test accuracy:", round(rf.score(X_te, y_te), 3))
imp = rf.feature_importances_                         # mean impurity decrease, from training data
perm = permutation_importance(rf, X_te, y_te, n_repeats=10, random_state=0).importances_mean
order = np.argsort(imp)[::-1]
print("feature                   impurity  permutation (test)")
for j in list(order[:5]) + [len(names) - 2, len(names) - 1]:
    print(f"{names[j]:24s}  {imp[j]:.3f}     {perm[j]:+.3f}")
test accuracy: 0.953
feature                   impurity  permutation (test)
worst perimeter           0.142     +0.012
worst concave points      0.123     +0.015
worst radius              0.114     +0.014
worst area                0.104     +0.021
mean concave points       0.086     +0.014
noise (normal)            0.003     +0.001
noise (500 ids)           0.002     +0.003

Both methods put the noise columns near zero here, and both agree that size and concavity measurements matter. They disagree on the order: impurity ranks "worst perimeter" first, permutation ranks "worst area". Perimeter, radius and area of the same nucleus are almost the same information, so when one is shuffled the forest falls back on the others, and every member of the group looks less important than the group is. Read importances of correlated features as importances of the group.

Hyperparameters

Hyperparameter Typical values Effect
n_estimators 200 to 1000 more trees, lower variance, never more overfitting; stop when OOB flattens
max_features "sqrt" (classification), 1.0 or 0.33 (regression) the strength/correlation trade-off
min_samples_leaf 1 to 5 larger values smooth probabilities, help noisy regression
max_depth None usually left unlimited; trees are meant to be deep
class_weight "balanced", "balanced_subsample" imbalanced classes
oob_score, n_jobs free validation estimate; parallel training

Strengths, weaknesses, when to use it

Strengths Weaknesses
strong accuracy with default settings large models: hundreds of deep trees in memory, slower predictions
hard to overfit by adding trees usually a little less accurate than well-tuned gradient boosting
no scaling, handles mixed features and interactions cannot extrapolate (an average of piecewise constants)
OOB estimate and importances included probabilities are not well calibrated near 0 and 1

Use a random forest as the first strong model on any tabular problem: it needs little tuning and rarely fails badly. When the last bit of accuracy matters, compare it with gradient boosting.

Pitfalls

  • Trusting impurity importance. It is measured on training data and favours high-cardinality features; prefer permutation importance on held-out data.
  • Expecting more trees to fix a bias. Adding trees lowers variance only.
  • Very many noise features with small max_features. If most features are noise, a random subset often contains no useful feature at all, and trees split on noise.

Practice

  1. A data set has 100 features. What max_features does scikit-learn's RandomForestClassifier use by default, and how many features does each split see?
Answer

"sqrt": 100=10\sqrt{100} = 10 features drawn at random at every split.

  1. In the first output, the forest with m=20m = 20 and m=4m = 4 have the same accuracy although single trees with m=4m = 4 are weaker. Explain with the variance formula.
Answer

The forest's error depends on the trees' average error and on how much of their variance survives averaging, ρσ2\rho\sigma^2. Lowering mm from 20 to 4 raised single-tree error but cut ρ\rho from 0.50 to 0.32; on this data the two effects balance.

Test yourself

What does a random forest add to bagged trees?

  1. Boosting of residuals
  2. A random subset of features considered at each split
  3. Pruning of every tree
  4. Linear models in the leaves

Why does lowering max_features help even though each tree gets worse?

  1. It makes trees deeper
  2. It lowers the correlation between trees, so averaging removes more variance
  3. It reduces the bias of each tree
  4. It speeds up training only

Which importance measure is computed on held-out data by shuffling one feature at a time?

  1. impurity (Gini) importance
  2. permutation importance
  3. coefficient size
  4. OOB score