Sub topic 9
Random forests
This chapter assumes you know how a single decision tree is grown and why deep trees overfit. It also assumes you have run a scikit-learn pipeline with cross-validation, as in the earlier chapters. Here you will learn how a random forest reduces a tree's variance, which settings matter, and which mistakes to avoid.
The working model
A random forest is an average of many decision trees. Each tree is trained to be different from the others in two ways:
- Bootstrap sampling (bagging). Each tree trains on a sample of the rows drawn with replacement, the same size as the training set. About 63% of the distinct rows appear in any one sample.
- Random feature subsets. At every split, the tree considers only a random subset of the columns, not all of them. In scikit-learn this is
max_features.
A fully grown tree has low bias and high variance. Its predictions change a lot if the training rows change a little. Averaging many trees that make different errors cancels much of that variance, while the bias stays low. The random feature subsets matter because they keep the trees from being near copies of each other. If one strong column dominated every tree's first split, the trees would be highly correlated, and averaging correlated predictions removes less variance.
For classification, scikit-learn averages each tree's class probabilities and picks the class with the highest average. For regression, it averages the predicted values.
A first comparison
The code below compares a single tree with two forests on the same folds. It uses synthetic data so that it runs on its own.
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.tree import DecisionTreeClassifier
X, y = make_classification(
n_samples=1000, n_features=20, n_informative=6,
n_redundant=4, flip_y=0.05, random_state=0,
)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
models = {
"tree": DecisionTreeClassifier(random_state=0),
"forest": RandomForestClassifier(n_estimators=300, random_state=0, n_jobs=-1),
"forest_leaf5": RandomForestClassifier(
n_estimators=300, min_samples_leaf=5, random_state=0, n_jobs=-1
),
}
for name, model in models.items():
scores = cross_val_score(model, X, y, cv=cv, scoring="roc_auc")
print(f"{name}: {scores.mean():.3f} +/- {scores.std():.3f}")Expect the single tree to score far below both forests, and its fold-to-fold spread to be larger. That gap is the variance reduction. The difference between the two forests is usually small, which shows that a forest is forgiving of its settings.
Hyperparameters that matter
A forest has many parameters, but a few do most of the work.
| Parameter | Default (classifier) | Effect | Typical direction |
|---|---|---|---|
| `n_estimators` | 100 | Number of trees. More trees reduce noise from randomness and never cause overfitting. | Raise until the score stops improving, then stop for cost reasons |
| `max_features` | `"sqrt"` | Columns considered per split. Lower values decorrelate the trees but make each tree weaker. | Try `"sqrt"`, `"log2"`, and a fraction such as 0.3 |
| `min_samples_leaf` | 1 | Minimum rows in a leaf. Larger values smooth predictions and shrink the model. | Try 1, 3, 5, 10, and more on noisy data |
| `max_depth` | None | Depth limit. Often redundant when `min_samples_leaf` is set. | Leave unset unless you need a smaller model |
| `class_weight` | None | Reweights classes during training. | `"balanced"` or `"balanced_subsample"` for imbalanced data |
Regressors default max_features to 1.0, which means all columns, so the trees are more correlated than in a classifier. Lowering it to something like 0.33 often helps.
Do not tune n_estimators for accuracy the way you tune other settings. A larger value only makes the average more stable and costs more training time and memory.
Out-of-bag estimates
Because each tree sees only about 63% of the distinct rows, the remaining rows are "out of bag" for that tree. For each training row, the forest can average the predictions of only those trees that did not see it. Scoring those predictions gives a validation estimate without a separate split.
Setting oob_score=True computes this. The code below also compares two ways to measure feature importance.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
from sklearn.inspection import permutation_importance
from sklearn.model_selection import train_test_split
X, y = make_classification(
n_samples=1000, n_features=20, n_informative=6,
n_redundant=4, flip_y=0.05, random_state=0,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, stratify=y, random_state=0
)
rf = RandomForestClassifier(
n_estimators=300, min_samples_leaf=3, oob_score=True,
random_state=0, n_jobs=-1,
).fit(X_train, y_train)
print("OOB accuracy:", round(rf.oob_score_, 3))
print("Test accuracy:", round(rf.score(X_test, y_test), 3))
perm = permutation_importance(
rf, X_test, y_test, n_repeats=10, scoring="roc_auc", random_state=0
)
for i in np.argsort(perm.importances_mean)[::-1][:5]:
print(
f"feature {i}: permutation={perm.importances_mean[i]:.3f}, "
f"impurity={rf.feature_importances_[i]:.3f}"
)The OOB accuracy and the test accuracy should be close. OOB is a convenient check during development, but it is not a replacement for the cross-validation scheme you use to compare models. It is also tied to the forest, so it cannot score a gradient-boosted model or a linear model on the same footing. For a fair comparison, use the same folds for every candidate.
Feature importance and its traps
feature_importances_ is the total impurity decrease a column produced across all splits. It is free to compute, but it is computed on training data and it favors columns with many distinct values, such as continuous columns or high-cardinality categories. A random ID column can look important because a deep tree can use it to memorize rows.
Permutation importance shuffles one column in held-out data and measures how much the score drops. It reflects what the model actually relies on for unseen data, and it is the safer default. It has its own limit: when two columns are strongly correlated, shuffling one leaves the other to cover for it, so both can look unimportant. Neither measure shows the direction of an effect, and neither implies causation.
Handling tabular columns
- Scaling is unnecessary. Trees split on thresholds, so monotone transformations of a column change nothing. You can skip
StandardScalerfor a forest, although a shared pipeline for several models may still include it. - Categories must be encoded. Scikit-learn's forests do not accept string columns directly. One-hot encoding works for a handful of levels. For a high-cardinality column, one-hot encoding spreads the signal over many sparse columns, and each is rarely chosen by a split. An ordinal encoding is more compact, but it imposes an arbitrary order. Compare both on your folds.
- Missing values. Since scikit-learn 1.4,
RandomForestClassifierandRandomForestRegressoraccept NaN in the input. On older versions, or when you want a consistent pipeline across models, keep aSimpleImputerin front. Fit it inside the pipeline so each fold learns its own medians.
Failure modes
- No extrapolation. A regression forest predicts averages of training targets, so it never predicts above the largest or below the smallest target it saw. If prices keep rising over time, a forest trained on past data will under-predict. A linear model or a time-aware feature can handle a trend that a forest cannot.
- Probabilities are not calibrated. Averaged votes tend to be pulled away from 0 and 1. If you use the probabilities as risks or thresholds, check a calibration curve and consider
CalibratedClassifierCV. - Large models. Fully grown trees on many rows store a lot of nodes. A 500-tree forest can take hundreds of megabytes, which affects loading time and latency. Raising
min_samples_leafor settingmax_depthshrinks it. - Leakage through preprocessing. Imputing or encoding on the full table before cross-validation gives optimistic scores. Keep preprocessing inside a pipeline, as in the preprocessing chapter.
- Imbalanced classes. Accuracy hides a forest that ignores the rare class. Choose a metric that fits the goal, and try
class_weight="balanced_subsample".
Forest versus the alternatives
A random forest is a strong default. It needs little tuning, it handles nonlinear effects and interactions, and it is hard to break with outliers. Its main competitor on tabular data is gradient boosting, which is the next chapter. Boosting often reaches a higher score after tuning, but a forest gets close with almost no effort and is less sensitive to its settings. When a forest and a boosted model score within noise of each other on the same folds, the forest's simplicity can decide the choice.
Exercise
A regression forest is trained on house prices from 2015 to 2019 and used to predict 2024 prices. Predictions come out consistently too low. Give the cause and one fix.
Show answer
A forest predicts averages of target values it saw in training, so it cannot predict above the highest prices in its training data. When prices trend upward, it under-predicts new data. Fixes include adding a time or inflation-adjusted feature, predicting a detrended target such as price relative to a regional index, or using a model that can extrapolate, such as a linear model on top of the forest's residuals.
Exercise
You set oob_score=True and get 0.91 accuracy. Cross-validation on the same data gives 0.89, and a gradient-boosted model scores 0.90 on cross-validation. Can you conclude the forest is better?
Show answer
No. The OOB score and the cross-validation score come from different procedures, so the two numbers are not comparable. The fair comparison is 0.89 for the forest against 0.90 for the boosted model, on the same folds. That difference is small, so check it against the fold-to-fold standard deviation before declaring a winner.