Sub topic 9
Random forests
This chapter assumes you know how a single decision tree splits data and how to run cross-validation in scikit-learn. It also assumes you have built a preprocessing pipeline like the one earlier in this tutorial.
The idea: many noisy trees, averaged
A single deep decision tree fits its training data closely and changes a lot when the data changes slightly. That is high variance. A random forest reduces the variance by training many trees and averaging their predictions. Two sources of randomness keep the trees different from each other:
- Bagging (bootstrap aggregating). Each tree trains on a bootstrap sample, which is a random draw of rows with replacement. Each sample leaves out roughly a third of the rows.
- Feature subsampling. At each split, the tree considers only a random subset of columns (
max_features). This stops one strong column from dominating every tree.
For classification, the forest averages the class probabilities from all trees. For regression, it averages the numeric predictions.
Comparing a tree and a forest
The example below builds the synthetic table from the baseline chapter. It scores one decision tree and one forest on identical folds. Trees do not need feature scaling, so the pipeline only imputes missing values and one-hot encodes the city column.
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import RandomForestClassifier
from sklearn.impute import SimpleImputer
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder
from sklearn.tree import DecisionTreeClassifier
rng = np.random.default_rng(0)
n = 500
X = pd.DataFrame({
"age": rng.integers(18, 80, n).astype(float),
"income": rng.normal(50000, 15000, n),
"city": rng.choice(["a", "b", "c"], n),
})
X.loc[rng.choice(n, 25, replace=False), "income"] = np.nan
y = ((X["age"] > 45) ^ (X["city"] == "a")).astype(int)
preprocess = ColumnTransformer([
("num", SimpleImputer(strategy="median"), ["age", "income"]),
("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), ["city"]),
])
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
models = {
"tree": make_pipeline(preprocess, DecisionTreeClassifier(random_state=0)),
"forest": make_pipeline(
preprocess, RandomForestClassifier(n_estimators=200, random_state=0)
),
}
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 forest to score higher than the single tree, and to vary less from fold to fold. The gap shows how much of the tree's error came from variance.
Settings that matter
| Setting | Effect |
|---|---|
| `n_estimators` | More trees give a steadier average. Gains flatten after a few hundred, and cost grows linearly. |
| `max_features` | Smaller values make trees more different from each other. Larger values make each tree stronger. |
| `min_samples_leaf` | Larger values smooth predictions and reduce overfitting on noisy data. |
| `max_depth` | Limits tree size. The default is unlimited, which is usually fine in a forest. |
| `n_jobs` | Set to `-1` to train trees in parallel. |
Adding trees does not cause overfitting. The settings that control complexity are the leaf size and depth.
Strengths and common errors
Forests need little tuning, handle mixed feature types after encoding, and capture interactions without manual feature work. They make a strong second baseline after a linear model.
Watch for these problems:
- Reading
feature_importances_as truth. The default impurity-based importance favors high-cardinality and continuous columns. Usesklearn.inspection.permutation_importanceon held-out data for a more reliable view. - Expecting extrapolation. A forest predicts averages of training targets, so it never predicts outside the range it saw. This matters for regression with trends.
- Ignoring size and latency. Hundreds of deep trees take memory and slow down prediction. Check this before deployment.
- Skipping the pipeline. Imputation fitted outside the folds leaks information, even for tree models.
Exercise
A forest of 500 trees scores slightly better than one of 100 trees, but prediction is five times slower. Which setting would you change first, and what would you check before deciding?
Show answer
Reduce n_estimators. Compare cross-validated scores for several tree counts, such as 50, 100, 200 and 500, on the same folds. If the score gap is smaller than the fold-to-fold standard deviation, choose the smaller forest. Then measure prediction time against your latency limit.