Grid search for random forest hyperparameters

MediumHyperparameter tuningClassification

Goal: Choosing model hyperparameters with cross-validation, then evaluating on a separate test set.

Python — example.py
from sklearn.datasets import load_wine
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report
from sklearn.model_selection import GridSearchCV, train_test_split

X, y = load_wine(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, stratify=y, random_state=1)
grid = GridSearchCV(RandomForestClassifier(random_state=0),
                    {"n_estimators": [50, 150], "max_depth": [None, 4]}, cv=4, n_jobs=1)
grid.fit(X_tr, y_tr)
print("Best parameters:", grid.best_params_)
print(f"Cross-validation accuracy: {grid.best_score_:.3f}")
print(classification_report(y_te, grid.predict(X_te), digits=3))

Code explanation

We first split the data into training and test sets, run GridSearchCV on the training set only, then evaluate the best model once on the test set. Evaluating on the data used to choose the hyperparameters gives an optimistic estimate.

Requirements

Shell
pip install scikit-learn

How to run

Save the code in a file example.py then run it:

Shell
python example.py

Output recorded during testing

Best parameters: {'max_depth': None, 'n_estimators': 50}
Cross-validation accuracy: 0.970
              precision    recall  f1-score   support

           0      0.938     1.000     0.968        15
           1      1.000     0.944     0.971        18
           2      1.000     1.000     1.000        12

    accuracy                          0.978        45
   macro avg      0.979     0.981     0.980        45
weighted avg      0.979     0.978     0.978        45

This example was actually run and tested on 21 November 2026 on a CPU — scikit-learn 1.9.1, python 3.13.18

Libraries used

Related examples

MediumOptunaRun and tested

Hyperparameter tuning with Optuna

Searching for the best hyperparameters with the TPE algorithm instead of grid search.

Hyperparameter tuning · Model tuning