Pulse Data Hub

Hyperparameter Tuning in Python: Does It Help?

Hyperparameter tuning in Python is often presented as a free accuracy boost. This guide runs a grid search and a randomized search on a real dataset and measures what they gain. On this data the answer is: almost nothing, and the cost is large.

What hyperparameter tuning is

A hyperparameter is a setting you choose before training, such as the number of trees or the maximum depth. Tuning means trying many combinations and keeping the one with the best cross-validated score. Scikit-learn offers GridSearchCV (every combination) and RandomizedSearchCV (a random sample of combinations).

Set up: data, split and baseline

We use the breast cancer dataset bundled with scikit-learn (569 rows, 30 features), a stratified split of 426 training and 143 test rows, and a random forest with default settings. Never tune on the test rows; they stay untouched until the end. For why, see cross-validation in Python and train-test split.

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score
from sklearn.ensemble import RandomForestClassifier
X, y = load_breast_cancer(return_X_y=True)
Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=.25, stratify=y, random_state=0)
cv = StratifiedKFold(5, shuffle=True, random_state=0)
base = RandomForestClassifier(random_state=0)
print(cross_val_score(base, Xtr, ytr, cv=cv).mean())
print(base.fit(Xtr, ytr).score(Xte, yte))

The untuned forest scores 0.9671 in cross-validation and 0.9441 on the test set (135 of 143 correct).

Grid search

from sklearn.model_selection import GridSearchCV
grid = {"n_estimators": [50, 100, 200, 400], "max_depth": [2, 4, 8, None],
        "min_samples_leaf": [1, 2, 5, 10], "max_features": ["sqrt", "log2", 0.5]}
g = GridSearchCV(RandomForestClassifier(random_state=0), grid, cv=cv, n_jobs=2).fit(Xtr, ytr)
print(g.best_params_, g.best_score_, g.score(Xte, yte))

The grid has 192 combinations, so 960 model fits with 5 folds. On two CPU cores it took 137.1 seconds. The best settings were max_depth=4, max_features=0.5, min_samples_leaf=2 and n_estimators=100, with a cross-validated score of 0.9671 and a test score of 0.9441. Both are identical to the untuned forest.

The scores across the grid show why. They range from 0.9366 to 0.9671, 14 combinations tie for the top score, and 29.2% of all combinations are within half a point of the best. The standard deviation across folds for the winning setting is 0.0089, larger than most of the gaps you are trying to resolve.

Randomized search

from sklearn.model_selection import RandomizedSearchCV
from scipy.stats import randint
dist = {"n_estimators": randint(50, 401), "max_depth": [2, 4, 8, None],
        "min_samples_leaf": randint(1, 11), "max_features": ["sqrt", "log2", 0.5]}
r = RandomizedSearchCV(RandomForestClassifier(random_state=0), dist, n_iter=20,
                       cv=cv, n_jobs=2, random_state=0).fit(Xtr, ytr)

Twenty random draws mean 100 fits and 15.4 seconds, about nine times faster. It picked 149 trees, depth 8, min_samples_leaf=3 and max_features="sqrt", with a cross-validated score of 0.9694 and the same test accuracy, 0.9441. The extra 0.0023 in cross-validation is the noise you get from choosing the best of many tries.

Bar chart: grid search took 137.1 seconds and randomized search 15.4 seconds, both reaching 94.4% test accuracy
Same test accuracy, nine times less time. Measured on 2 CPU cores.

The score you report must come from outside the search

The best cross-validation score is biased upward because you picked the maximum. To estimate how a tuned model will really perform, wrap the search inside an outer cross-validation (nested CV). With a smaller grid of 12 combinations on all 569 rows, the five outer folds scored 0.947, 0.982, 0.939, 0.974 and 0.956, a mean of 0.9596, lower than the 0.9671 to 0.9694 the inner searches reported.

small = {"max_depth": [2, 4, None], "min_samples_leaf": [1, 5], "n_estimators": [100, 200]}
outer = StratifiedKFold(5, shuffle=True, random_state=1)
nested = cross_val_score(GridSearchCV(RandomForestClassifier(random_state=0), small, cv=cv), X, y, cv=outer)
print(nested.mean())

One caution: the test set has only 143 rows, so one extra correct prediction moves accuracy by 0.7 points. A difference smaller than that cannot be called real.

When tuning pays off

  • Models that are sensitive to settings, such as gradient boosting learning rates, SVM C and gamma, or regularisation strength.
  • Large datasets where small gains are worth the compute.
  • After features and data quality are fixed. See feature engineering that helps, tested. Better inputs often matter more than better settings, though we did not test that on this dataset.

Start with randomized search or a small grid, check that the best score clears the fold noise, and report a nested or held-out estimate. Docs: scikit-learn hyperparameter tuning guide. Related: random forests explained.

FAQ

Is grid search or random search better?

Random search covered the same ground here in a ninth of the time. Grid search is fine for two or three parameters; it grows multiplicatively with each one you add.

Why did tuning not improve the random forest?

Random forests are already robust to their settings, and this dataset is easy (about 96% to 97% accuracy at default). The sample is also small, so differences are mostly noise. Your data may behave differently.

Which versions were used?

scikit-learn 1.9.1, SciPy 1.18.1, Python 3.13, run on 2 CPU cores. Timings will differ on your machine.

Newsletter Signup Form

Latest tutorials

Latest articles

On this page
Verified by MonsterInsights