TExcelTAD
Home › Machine Learning › Random Forests

Random Forests

A random forest is a bag of decision trees with one extra twist. In the Bootstrap Aggregation lesson each tree was trained on a different bootstrap sample. A random forest additionally lets every split consider only a random subset of the features. That forces the trees to be different from one another — if one feature is very strong, plain bagging would put it at the root of nearly every tree, making the trees similar and their errors correlated. Diverse trees make the vote much more reliable.

Random forests are accurate, need little tuning, don't need feature scaling and handle mixed feature types well. They are one of the best "first serious model" choices for tabular data.

A first forest

python · try it yourself
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier

X, y = load_breast_cancer(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, random_state=5, stratify=y)

tree = DecisionTreeClassifier(random_state=0).fit(X_tr, y_tr)
forest = RandomForestClassifier(n_estimators=100, random_state=0).fit(X_tr, y_tr)

print(f"single tree   test accuracy: {tree.score(X_te, y_te):.3f}")
print(f"random forest test accuracy: {forest.score(X_te, y_te):.3f}")
print("trees in the forest:", len(forest.estimators_))
single tree   test accuracy: 0.942
random forest test accuracy: 0.982
trees in the forest: 100

Important hyperparameters

Parameter Meaning Typical values
n_estimators number of trees 100–500 (more is rarely worse, only slower)
max_features features considered at each split "sqrt" (default for classification), 1.0 = plain bagging
max_depth maximum depth of each tree None (grow fully) or 5–20
min_samples_leaf minimum samples in a leaf 1–10; higher = smoother
n_jobs CPU cores to use -1 = all cores (on a normal machine)

Let's see what max_features does, using the out-of-bag score as a free validation estimate:

python · try it yourself
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier

X, y = load_breast_cancer(return_X_y=True)
for mf in [1, "sqrt", 0.5, 1.0]:
    forest = RandomForestClassifier(n_estimators=100, max_features=mf,
                                    oob_score=True, random_state=0).fit(X, y)
    print(f"max_features={str(mf):5}  OOB accuracy={forest.oob_score_:.3f}")
max_features=1      OOB accuracy=0.968
max_features=sqrt   OOB accuracy=0.968
max_features=0.5    OOB accuracy=0.958
max_features=1.0    OOB accuracy=0.958

max_features=1.0 (all features) is plain bagging; the default "sqrt" usually does at least as well and trains faster.

Feature importance

A forest can tell you which features it relied on. feature_importances_ measures how much each feature reduced impurity, averaged over all trees (the values sum to 1):

python · try it yourself
import pandas as pd
from sklearn.datasets import load_wine
from sklearn.ensemble import RandomForestClassifier

data = load_wine()
forest = RandomForestClassifier(n_estimators=200, random_state=0).fit(data.data, data.target)

importance = pd.Series(forest.feature_importances_, index=data.feature_names)
print(importance.sort_values(ascending=False).round(3).head(6))
proline                         0.189
flavanoids                      0.160
color_intensity                 0.156
od280/od315_of_diluted_wines    0.113
alcohol                         0.108
hue                             0.084
dtype: float64

Note: Impurity-based importance favours features with many distinct values and is computed on training data. For a more trustworthy measure, use permutation importance (sklearn.inspection.permutation_importance) on a validation set: shuffle one feature and see how much the score drops.

python · try it yourself
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.inspection import permutation_importance

data = load_wine()
X_tr, X_te, y_tr, y_te = train_test_split(data.data, data.target, test_size=0.3, random_state=0, stratify=data.target)
forest = RandomForestClassifier(n_estimators=100, random_state=0).fit(X_tr, y_tr)

result = permutation_importance(forest, X_te, y_te, n_repeats=10, random_state=0)
order = result.importances_mean.argsort()[::-1][:4]
for i in order:
    print(f"{data.feature_names[i]:30} {result.importances_mean[i]:.3f} +/- {result.importances_std[i]:.3f}")
color_intensity                0.120 +/- 0.031
proline                        0.094 +/- 0.024
flavanoids                     0.041 +/- 0.014
alcohol                        0.028 +/- 0.017

Random forest regression

RandomForestRegressor averages the trees' numeric predictions. Unlike a single tree's step-shaped output, the average of many trees gives a smoother curve:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor

rng = np.random.default_rng(2)
x = np.sort(rng.uniform(0, 10, 80)).reshape(-1, 1)
y = np.sin(x).ravel() + rng.normal(0, 0.3, 80)
grid = np.linspace(0, 10, 300).reshape(-1, 1)

tree = DecisionTreeRegressor(random_state=0).fit(x, y)
forest = RandomForestRegressor(n_estimators=100, min_samples_leaf=3, random_state=0).fit(x, y)

plt.scatter(x, y, s=12, color="gray")
plt.plot(grid, tree.predict(grid), label="single tree", alpha=0.7)
plt.plot(grid, forest.predict(grid), label="random forest", linewidth=2)
plt.legend()
plt.show()
print(f"forest prediction at x=1.5: {forest.predict([[1.5]])[0]:.3f} (true sin: {np.sin(1.5):.3f})")
forest prediction at x=1.5: 0.981 (true sin: 0.997)

The single tree jumps to hit every noisy point; the forest follows the underlying wave.

Tip: Trees (and forests) can't extrapolate: outside the range of the training data they predict a constant, the value of the outermost leaf. If your inputs may go beyond what was seen in training, a linear model might be safer.

Go further: Random Forests grows a forest from scratch and compares two ways of measuring feature importance.

Test yourself

What does a random forest add on top of bagging decision trees?

  1. It uses a single deeper tree
  2. Each split considers only a random subset of features
  3. It removes bootstrapping
  4. It scales the features

Do random forests need feature scaling?

  1. Yes, always
  2. No, tree splits are not affected by scale
  3. Only for regression
  4. Only with more than 100 trees

Which attribute of a fitted forest gives impurity-based feature importances?

  1. coef_
  2. feature_importances_
  3. importances_mean
  4. support_