Sub topic 10
Tuning the main hyperparameters
This chapter assumes you can train a scikit-learn classifier and read cross-validation scores. It also assumes you know how a forest is built from bootstrap samples and random feature subsets. Here you learn which settings matter, what each one does, and how to tune them without wasting time.
Start with the defaults
A random forest works well with few changes. Tune a few settings, in this order of impact:
| Hyperparameter | scikit-learn name | Main effect |
|---|---|---|
| Number of trees | `n_estimators` | Lowers variance, then levels off |
| Features per split | `max_features` | Controls how different the trees are |
| Tree depth | `max_depth` | Limits how complex each tree gets |
| Leaf size | `min_samples_leaf` | Smooths predictions and resists noise |
Number of trees
Adding trees never makes a forest overfit more. Each new tree adds a vote, and the averaged prediction becomes more stable. The gain shrinks quickly, so past a few hundred trees you mostly pay in training time and memory.
Treat n_estimators as a budget, not a setting to search. Choose a value that is large enough for the score to stop moving, such as 300 to 500, and fix it while you tune the others.
Features per split
max_features is the number of features each split may consider. It sets a trade-off:
- A small value makes the trees differ more from each other. Averaging then removes more variance, but each tree is weaker.
- A large value makes each tree stronger, but the trees look alike and averaging helps less.
The scikit-learn default for classification is "sqrt", the square root of the feature count. For regression the default is all features (1.0), so it is worth trying smaller values there. This is often the most useful setting to tune.
Depth and leaf size
By default the trees grow until every leaf is pure. That keeps bias low and relies on averaging to control variance. Two settings let you stop growth earlier:
max_depthcaps the number of levels.min_samples_leafrequires each leaf to hold at least that many training samples.
Prefer min_samples_leaf over max_depth. It adapts to dense and sparse regions of the data, while a depth cap treats them the same. Try values such as 1, 3, 5 and 10. Larger leaves help most on noisy data and in regression.
A search that fits the budget
Because the forest has an out-of-bag score, you can compare settings without cross-validation. Cross-validation is still the safer choice when the dataset is small. The example below uses it with a random search.
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_distributions = {
"max_features": ["sqrt", "log2", 0.5],
"min_samples_leaf": randint(1, 11),
"max_depth": [None, 6, 10, 20],
}
search = RandomizedSearchCV(
RandomForestClassifier(n_estimators=300, random_state=0, n_jobs=-1),
param_distributions,
n_iter=15,
cv=5,
random_state=0,
)
search.fit(X_train, y_train)
print("Best parameters:", search.best_params_)
print("CV accuracy: ", round(search.best_score_, 3))
print("Test accuracy: ", round(search.score(X_test, y_test), 3))The search keeps n_estimators fixed and tunes the other three. The test set is used once, after the search, so the final score is not inflated by the tuning.
Common mistakes
- Searching
n_estimatorsalong with everything else. Larger values almost always score at least as well, so the search only adds cost. - Tuning on the test set. Use cross-validation or the OOB score for choices, and keep the test set for the final check.
- Expecting large gains. Forests are forgiving, so tuning often adds a small amount. If scores stay low, the features or the data usually matter more.
Exercise
A forest's OOB accuracy is the same at 300 trees and at 1000 trees. A teammate says the model is underfitting and asks for more trees. What do you advise?
Show answer
More trees will not help. The score has already leveled off, because extra trees only reduce variance, and that has stopped changing. If the model underfits, lower the bias instead. Allow deeper trees with a smaller min_samples_leaf or a larger max_depth, or raise max_features so each tree is stronger.
Exercise
Why is min_samples_leaf often preferred over max_depth for limiting tree growth?
Show answer
It adapts to the data. Dense regions can still be split into many leaves, while sparse or noisy regions stop early. A depth cap cuts every branch at the same level, whatever the amount of data under it.