Sub topic 10
Tuning the main hyperparameters
A random forest has a handful of settings that matter and many that rarely do. This chapter covers the ones that matter: the number of trees, the number of features tried per split, tree depth, and leaf size. It also covers how to search over them without fooling yourself.
It assumes you can train a forest in scikit-learn and know what bootstrap sampling, feature subsampling and out-of-bag (OOB) error are from earlier chapters. You should also be comfortable with cross-validation.
What tuning can and cannot do
Forests are forgiving. The defaults in scikit-learn are often within a percentage point or two of the best tuned result. Tuning mostly helps in three situations:
- The data is noisy, and the fully grown trees fit the noise.
- There are many features, and most of them are irrelevant.
- Training time or model size is a constraint.
Most hyperparameters fall into two groups. Some control how different the trees are from each other (max_features, max_samples). Others control how complex each tree is (max_depth, min_samples_leaf). The number of trees is a third kind. It does not change the model's bias, only the noise in its averaged prediction.
Hyperparameters at a glance
| Parameter | Default | What it controls | Typical direction |
|---|---|---|---|
| `n_estimators` | 100 | Number of trees averaged | Increase until the curve flattens |
| `max_features` | `"sqrt"` (classifier), `1.0` (regressor) | Features considered at each split | Main lever for decorrelation |
| `max_depth` | `None` | Maximum depth of each tree | Limit if trees overfit or are too large |
| `min_samples_leaf` | 1 | Minimum samples in each leaf | Raise on noisy data |
| `min_samples_split` | 2 | Minimum samples needed to split a node | Usually secondary to `min_samples_leaf` |
| `max_samples` | `None` | Size of each bootstrap sample (needs `bootstrap=True`) | Lower to speed up and decorrelate |
| `class_weight` | `None` | Reweights classes | Use `"balanced"` for imbalanced data |
Number of trees: more is safe, but not free
Adding trees never causes overfitting in the usual sense. Each new tree is another draw from the same randomized procedure, so the averaged prediction only becomes more stable. The error falls quickly at first and then flattens. Past that point, extra trees cost training time, prediction time and memory.
You do not need cross-validation to find the plateau. The OOB score is free, and warm_start=True lets you add trees to an existing forest without refitting the old ones.
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
X, y = load_breast_cancer(return_X_y=True)
clf = RandomForestClassifier(
warm_start=True, oob_score=True, n_jobs=-1, random_state=0
)
for n in [25, 50, 100, 200, 400, 800]:
clf.set_params(n_estimators=n)
clf.fit(X, y) # only the new trees are trained
print(f"{n:>4} trees OOB error = {1 - clf.oob_score_:.4f}")Pick the smallest count after which the OOB error stops improving in a meaningful way. Treat n_estimators as a budget rather than a tuning target. Fix it at a comfortable value such as 300 to 500 while you tune the other settings, then revisit it at the end.
max_features: the main tuning knob
At each split the tree picks the best of max_features randomly chosen candidate features. This setting controls a trade-off.
- A small value makes the trees very different from each other. Averaging then removes more variance. But each split is chosen from weaker candidates, so each tree has higher bias.
- A large value makes each tree stronger and more similar to the others. With
max_featuresequal to the full feature count you get plain bagging.
The usual starting points are "sqrt" (the square root of the feature count) and "log2" for classification. For regression, values around one third of the features are a common heuristic, although scikit-learn defaults to all features.
The best value depends on how many features carry real signal. If only a few of many features are informative, a small max_features often wastes splits on noise features, so a larger value can win. If many features are correlated and informative, a small value works well. Try a few fractions on a log-like scale, such as "sqrt", 0.2, 0.4 and 0.7, rather than every integer.
Depth and leaf size: controlling each tree's complexity
Fully grown trees have low bias and high variance, and averaging handles the variance. That is why the defaults leave depth unlimited. Constraining the trees helps in a few cases:
- Noisy labels. Leaves with one sample memorize noise. Raising
min_samples_leafto 3 to 10 smooths the predictions. In regression it also stops the forest from predicting exact training values for nearby points. - Probability estimates. With
min_samples_leaf=1, each leaf is pure, so each tree votes 0 or 1. The forest's probabilities then come from the vote fraction alone. Larger leaves give each tree a graded probability. - Size and speed. Fully grown trees on large data can have millions of nodes. Limiting
max_depthor raisingmin_samples_leafshrinks the model a lot.
Prefer min_samples_leaf over max_depth as the main complexity control. It adapts to the data: dense regions can still split deeply while sparse regions stop early. A single max_depth cuts every branch at the same level whether or not it needs it. min_samples_split mostly overlaps with min_samples_leaf, so tuning one of them is usually enough.
max_samples and class_weight
By default each tree is trained on a bootstrap sample as large as the training set. Setting max_samples to a fraction such as 0.5 draws smaller samples. The trees become more different from each other and train faster, but each sees less data. On large datasets this is often a good trade.
For imbalanced classes, class_weight="balanced" or "balanced_subsample" reweights the classes. The second option recomputes the weights within each bootstrap sample. Compare the options with a metric that suits the problem, such as recall, F1 or average precision, rather than plain accuracy.
A sensible tuning order
You cannot tune every setting jointly, and you do not need to. Work from the most influential settings to the least.
Searching with cross-validation
Random search is usually more efficient than a full grid. A few of the settings matter much more than the others, and random search tries more distinct values of each one for the same budget. The example below keeps the test set out of the search entirely.
from scipy.stats import randint
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import RandomizedSearchCV, 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
)
param_dist = {
"max_features": ["sqrt", "log2", 0.3, 0.5],
"max_depth": [None, 5, 10, 20],
"min_samples_leaf": randint(1, 11), # integers 1 to 10
}
search = RandomizedSearchCV(
RandomForestClassifier(n_estimators=300, random_state=0, n_jobs=-1),
param_distributions=param_dist,
n_iter=20,
cv=5,
scoring="accuracy",
random_state=0,
)
search.fit(X_train, y_train)
print("Best parameters:", search.best_params_)
print(f"Best CV accuracy: {search.best_score_:.3f}")
print(f"Test accuracy: {search.best_estimator_.score(X_test, y_test):.3f}")Expect the gain over the defaults to be small on a clean dataset like this one. The cross-validation scores of many configurations will differ by less than their fold-to-fold spread. When that happens, choose the simpler or cheaper configuration, such as larger leaves or fewer trees.
Using OOB error instead of cross-validation
Cross-validation refits the forest once per fold, which multiplies the cost. OOB error gives a validation estimate from a single fit. You can tune with it by looping over a small grid and comparing oob_score_. This is much cheaper on large data.
It has limits:
- OOB scoring uses only the trees that did not see each sample, so it is a slightly pessimistic estimate for a forest of the full size.
- It does not support custom splitting such as grouped or time-ordered validation. If rows are correlated, for example repeated measurements of the same patient, OOB error is optimistic because related rows land on both sides of the bootstrap. Use
GroupKFoldor a time-based split instead. - If you pick the best configuration by OOB score, that score is now biased upward. Keep a final test set for the unbiased number.
Common mistakes
- Tuning
n_estimatorsin the search grid. It multiplies the cost and rewards whichever configuration drew the largest value. Fix it, then check it at the end. - Limiting depth too early. A shallow forest has high bias that averaging cannot remove. Check whether the defaults overfit before restricting anything.
- Ignoring
random_statenoise. Rerun a promising configuration with a different seed. If the score changes by as much as the improvement you found, the improvement is not real. - Optimizing the wrong metric. Accuracy hides poor minority-class performance. Set
scoringto match the goal.
Exercise
A forest with default settings has 99% training accuracy and 87% accuracy in cross-validation, and the data has noisy labels. Name two hyperparameters you would change first and the direction of each change. Also say why raising n_estimators is not one of them.
Show answer
Raise minsamplesleaf (for example to 5 or 10) so leaves cannot memorize individual noisy labels. Also consider lowering maxfeatures, or lowering maxsamples, to make the trees more different from each other so averaging removes more variance. Raising n_estimators only reduces the noise from having a finite number of trees. It does not change the bias or the overfitting of each tree, so it cannot close a gap this large.
Exercise
You tune a forest with RandomizedSearchCV and get a best CV accuracy of 0.912. Why is 0.912 not a fair estimate of future performance, and what should you do?
Show answer
The configuration was selected because it scored highest on those folds, so the score is biased upward. Hold out a test set before the search, run the search on the training portion only, and evaluate the final model once on the test set.