Sub topic 3
Tuning Random Forests in Practice
Assume you know features, labels, train/test splits, cross-validation, and accuracy or mean squared error. A random forest has several hyperparameters, which are settings chosen before training.
Tuning the Main Hyperparameters
| Hyperparameter | Effect | Typical trade-off |
|---|---|---|
| `n_estimators` | Number of trees | More trees reduce variance but increase time |
| `max_features` | Features considered at each split | Smaller values decorrelate trees but may increase bias |
| `max_depth` | Maximum tree depth | Shallower trees reduce overfitting |
| `min_samples_leaf` | Minimum samples in each leaf | Larger leaves smooth predictions |
Start with enough trees, such as 200 or 500. More trees usually help less after the estimate becomes stable. Tune max_features, max_depth, and min_samples_leaf with cross-validation. Do not use the test set to select these values.
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import GridSearchCV, train_test_split
data = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(
data.data, data.target, test_size=0.2,
stratify=data.target, random_state=0
)
model = RandomForestClassifier(
n_estimators=300, random_state=0, n_jobs=-1
)
grid = GridSearchCV(
model,
{
"max_features": ["sqrt", 0.5],
"max_depth": [None, 10, 20],
"min_samples_leaf": [1, 3, 10],
},
cv=5, scoring="accuracy", n_jobs=-1
)
grid.fit(X_train, y_train)
print(grid.best_params_)
print("Test accuracy:", grid.score(X_test, y_test))A Worked Example with scikit-learn
GridSearchCV fits one model for every parameter combination and scores each with five-fold cross-validation. The test score is reported only after selection. For imbalanced classes, choose a metric such as balanced accuracy, precision, recall, or area under the ROC curve instead of ordinary accuracy.
Interpreting Feature Importance
Impurity-based importance measures how much splits using a feature reduce impurity across the forest. It is fast, but it can favor continuous features or categorical features with many possible values. Correlated features can also divide importance between themselves.
Permutation importance measures how much the validation score falls after a feature's values are shuffled. It is easier to relate to model performance, but correlated features can hide one another. Calculate it on held-out data and repeat the shuffling several times.
Limitations and Alternatives
Random forests often need more memory than a single tree and can be slower at prediction time. They may perform poorly on very high-dimensional sparse data, extrapolate poorly beyond the training range, and provide less transparent explanations than a small tree or linear model. Consider linear models, nearest-neighbor methods, or gradient-boosted trees when their assumptions fit the problem better.
Related Methods
Extremely randomized trees choose split thresholds more randomly than random forests, which can reduce correlation and speed training. Boosting builds trees sequentially, giving later trees more attention to earlier errors. It can achieve higher accuracy but is often more sensitive to tuning.
Exercise
Why should the test set not be used during hyperparameter tuning?
Show answer
Repeated choices based on test performance leak information into the model-selection process, making the final test score overly optimistic.