Module 4 · Beginner · How models learn and why they fail

Hyperparameter tuning with grid search

Hyperparameter tuning in Python for beginners, with GridSearchCV and RandomizedSearchCV, how to read the results, and why tuning on the test set fails.

By theprogrammers team · · 15 min read

A new oven bakes your usual cake badly. You don't rewrite the recipe; you try a few temperatures and baking times, taste each cake, and keep the best pair. The recipe stays the same, only the settings change.

Machine learning models have settings like that too, such as a decision tree's maximum depth. They aren't learnt from the data; you choose them before training. Choosing them well is called hyperparameter tuning, and it can turn a mediocre model into a good one. Done carelessly, it also produces scores that look great and fall apart on new data.

What you need first: how a decision tree makes predictions, cross-validation explained and overfitting and underfitting.

Key terms

  • Parameter: a value the model learns from the data during training, such as the questions and cut-offs in a decision tree.
  • Hyperparameter: a setting you choose before training, such as max_depth.
  • Search space: the hyperparameter values you decide to try.
  • Grid search: trying every combination of the values you list.
  • Random search: trying a fixed number of random combinations from ranges you give.

Parameters vs hyperparameters

The difference is who chooses the value:

Chosen byExample in a decision treeExample in linear regression
ParameterThe model, during fitThe questions and cut-offs, such as "petal width at most 0.8"The slope and intercept
HyperparameterYou, before fitmax_depth, min_samples_leafThe penalty strength in Ridge regression

A hyperparameter changes how the model learns, so you can't pick it with the training score: a deeper tree always fits the training data better. You need data the model hasn't trained on, and cross-validation gives you that without touching the test set.

Tuning one setting by hand

The data is the Pima diabetes set from the cross-validation lesson: 768 women, 8 medical measurements, and whether each developed diabetes.

Download the data: pima-diabetes.csv (35 KB), or from the original source, OpenML. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with pd.read_csv("pima-diabetes.csv").

import numpy as np
import pandas as pd
from sklearn.datasets import fetch_openml
from sklearn.model_selection import train_test_split, cross_val_score, StratifiedKFold
from sklearn.tree import DecisionTreeClassifier

X, y = fetch_openml("diabetes", version=1, as_frame=True, return_X_y=True)
y = (y == "tested_positive").astype(int)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, stratify=y, random_state=0)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
print(X_train.shape, X_test.shape)
(576, 8) (192, 8)

y == "tested_positive" turns the text label into True or False, and .astype(int) into 1 or 0. StratifiedKFold makes 5 folds that each keep the same share of diabetic women; shuffle=True mixes the rows first, and random_state=0 fixes the shuffle so every model below is scored on exactly the same folds. That's what makes the comparisons fair.

Predict first: a depth-1 tree asks one question; an unlimited tree keeps asking until its leaves are pure. Which depth will score best in cross-validation: shallow, middle or unlimited?

for depth in [1, 2, 3, 4, 5, 6, 8, 10, None]:
    tree = DecisionTreeClassifier(max_depth=depth, random_state=0)
    score = cross_val_score(tree, X_train, y_train, cv=cv).mean()
    print(f"max_depth={str(depth):4}: CV accuracy {score:.3f}")
max_depth=1   : CV accuracy 0.668
max_depth=2   : CV accuracy 0.701
max_depth=3   : CV accuracy 0.681
max_depth=4   : CV accuracy 0.710
max_depth=5   : CV accuracy 0.717
max_depth=6   : CV accuracy 0.719
max_depth=8   : CV accuracy 0.680
max_depth=10  : CV accuracy 0.694
max_depth=None: CV accuracy 0.674

Too shallow underfits, unlimited overfits, and the best scores sit in the middle, around depths 5 and 6. This loop is hyperparameter tuning: try each value, score it on data the tree didn't train on, keep the best. The rest of the lesson is about doing it for several settings at once, faster and without fooling yourself.

Grid search: every combination

Depth isn't the only setting that controls overfitting. min_samples_leaf says how many training rows each leaf must hold: with 40, a tree can't make a leaf for one or two unusual women. The best depth may depend on the leaf size, so the two have to be tuned together.

GridSearchCV takes a dictionary of values to try, fits every combination with cross-validation, and remembers the best:

from sklearn.model_selection import GridSearchCV

param_grid = {
    "max_depth": [2, 3, 4, 5, 6, 8, None],
    "min_samples_leaf": [1, 5, 10, 20, 40],
}
grid = GridSearchCV(DecisionTreeClassifier(random_state=0), param_grid, cv=cv)
grid.fit(X_train, y_train)
print("best settings:", grid.best_params_)
print(f"best CV accuracy: {grid.best_score_:.3f}")
best settings: {'max_depth': 4, 'min_samples_leaf': 40}
best CV accuracy: 0.753

7 depths × 5 leaf sizes is 35 combinations, and each is trained 5 times, once per fold: 175 trees in a few seconds. The dictionary keys must be the hyperparameters' exact names in scikit-learn.

Tuning both settings beat the best single depth (0.719) by more than three points. After the search, grid holds a tree retrained on all the training data with the best settings (refit=True is the default), so you can use grid.predict straight away.

Read the results as a map

cv_results_ stores the score of every combination. Arranged as a table of depth against leaf size, it becomes a map of the search space, and this is the one picture to keep for tuning: a map of settings with a best spot on it.

import matplotlib.pyplot as plt

results = pd.DataFrame(grid.cv_results_)
results["depth"] = [str(p["max_depth"]) for p in results["params"]]
table = results.pivot(index="depth", columns="param_min_samples_leaf", values="mean_test_score")
table = table.loc[["2", "3", "4", "5", "6", "8", "None"]]

fig, ax = plt.subplots(figsize=(7, 5))
image = ax.imshow(table.values, cmap="viridis")
ax.set_xticks(range(len(table.columns)), table.columns)
ax.set_yticks(range(len(table.index)), table.index)
for i in range(table.shape[0]):
    for j in range(table.shape[1]):
        ax.text(j, i, f"{table.values[i, j]:.3f}", ha="center", va="center",
                color="white" if table.values[i, j] < 0.73 else "black", fontsize=9)
ax.set_xlabel("min_samples_leaf")
ax.set_ylabel("max_depth")
ax.set_title("Cross-validated accuracy for every combination")
fig.colorbar(image, ax=ax)
plt.show()
Heatmap of cross-validated accuracy, with max_depth 2, 3, 4, 5, 6, 8 and None as rows and min_samples_leaf 1, 5, 10, 20 and 40 as columns. Depth 2 scores 0.701 in every column and depth 3 about 0.68. For depths 4 and deeper, scores rise from left to right, and the whole min_samples_leaf 40 column is bright yellow at 0.753. The darkest cell is the unlimited tree with leaves of 1, at 0.674.

cv_results_["params"] holds each combination's settings; the depth column turns each depth into text, so None becomes the label "None". pivot turns the long list of results into a grid with one row per depth and one column per leaf size, and .loc[[...]] puts the rows in order. imshow colours each cell by its value, and the loop writes the score into every cell.

Two things stand out. Large leaves rescue deep trees: with leaves of 1, the unlimited tree scores only 0.674, but once every leaf must hold 40 women it reaches 0.753, because it can no longer chase single rows. In fact every depth from 4 upwards ties at 0.753 with leaves of 40: the leaf size, not the depth, is doing the work. And the best cell is at the edge of the grid, at the largest leaf size tried. When the best value sits at an edge, the real best may lie beyond it, so widen the grid in that direction and search again.

Random search: fewer tries, wider ranges

Grid search gets slow fast. Five values for each of four settings is 5⁴ = 625 combinations, or 3,125 fits with 5 folds. Random search tries a fixed number of random combinations instead, drawn from ranges you give. Because each try uses a fresh value of every setting, 20 random tries test 20 different depths and 20 different leaf sizes, while a 4 × 5 grid of the same cost tests only 4 and 5.

from sklearn.model_selection import RandomizedSearchCV
from scipy.stats import randint

param_ranges = {
    "max_depth": randint(2, 15),
    "min_samples_leaf": randint(1, 60),
}
search = RandomizedSearchCV(DecisionTreeClassifier(random_state=0), param_ranges,
                            n_iter=20, cv=cv, random_state=0)
search.fit(X_train, y_train)
print("best settings:", search.best_params_)
print(f"best CV accuracy: {search.best_score_:.3f}")
best settings: {'max_depth': 7, 'min_samples_leaf': 26}
best CV accuracy: 0.754

randint(2, 15) means "any whole number from 2 to 14" (the upper end is left out), and n_iter=20 sets the number of tries. random_state=0 makes the random choices repeatable.

With 20 tries instead of 35, random search matches the grid (0.754 against 0.753). It found a different combination, depth 7 with leaves of 26: values between the grid's points that the grid could never try.

Experiment: how few tries are enough? Change n_iter and predict how the best score changes with 5, 20 and 50 tries.

for n in [5, 20, 50]:
    s = RandomizedSearchCV(DecisionTreeClassifier(random_state=0), param_ranges,
                           n_iter=n, cv=cv, random_state=0).fit(X_train, y_train)
    print(f"n_iter={n:2}: best {s.best_params_}, CV accuracy {s.best_score_:.3f}")
n_iter= 5: best {'max_depth': 5, 'min_samples_leaf': 22}, CV accuracy 0.752
n_iter=20: best {'max_depth': 7, 'min_samples_leaf': 26}, CV accuracy 0.754
n_iter=50: best {'max_depth': 7, 'min_samples_leaf': 26}, CV accuracy 0.754

Five random tries already reach 0.752, within a whisker of the full grid's 175 fits. More tries found nothing better than the 20th. That's typical: many combinations score almost the same, so a modest random search lands near the top quickly. The gains from tuning come from leaving the bad region (tiny leaves), not from finding the single perfect cell.

The final test, once

Tuning used only the training data, through cross-validation. Now the test set gets its single use: one honest estimate of how the chosen model does on new women.

print(f"grid search:   CV {grid.best_score_:.3f}, test {grid.score(X_test, y_test):.3f}")
print(f"random search: CV {search.best_score_:.3f}, test {search.score(X_test, y_test):.3f}")
grid search:   CV 0.753, test 0.750
random search: CV 0.754, test 0.776

The test scores land within about two points of the cross-validated ones, which is what an honest process looks like. Differences that size are normal with 192 test women: each woman is about half a percentage point. Random search's 0.776 isn't proof that it's better; it's well within the noise.

See it fail: tuning on the test set

The tempting shortcut is to skip cross-validation and pick the settings that score best on the test set. Here's what that does. Split off a third set, called "fresh" here, to play the part of next year's patients, then tune 90 combinations on the test set:

X_rest, X_fresh, y_rest, y_fresh = train_test_split(X, y, test_size=0.3, stratify=y, random_state=1)
X_tr, X_te, y_tr, y_te = train_test_split(X_rest, y_rest, test_size=0.3, stratify=y_rest, random_state=1)

best_score, best_tree = 0, None
for depth in range(1, 16):
    for leaf in [1, 2, 5, 10, 20, 40]:
        t = DecisionTreeClassifier(max_depth=depth, min_samples_leaf=leaf, random_state=0).fit(X_tr, y_tr)
        if t.score(X_te, y_te) > best_score:
            best_score, best_tree = t.score(X_te, y_te), t

print(f"chosen on the test set: depth {best_tree.max_depth}, leaf {best_tree.min_samples_leaf}")
print(f"test accuracy (used to choose): {best_score:.3f}")
print(f"fresh data (never used):        {best_tree.score(X_fresh, y_fresh):.3f}")
chosen on the test set: depth 5, leaf 1
test accuracy (used to choose): 0.772
fresh data (never used):        0.710

The test set promised 0.772; on fresh patients the tree scores 0.710. Nothing is wrong with the code. With 90 tries, one combination was bound to get lucky on those particular 162 women, and choosing by the test score picks exactly that lucky one. Once you've chosen anything with the test set, its score is no longer an estimate of the future; it's a measure of how well you fitted the test set. This is a form of data leakage.

Tuning a whole pipeline

In real projects the model sits at the end of a pipeline, and preprocessing can be tuned too. Name a pipeline step's setting as step name, two underscores, setting name. make_pipeline names each step after its class in lowercase:

from sklearn.pipeline import make_pipeline
from sklearn.impute import SimpleImputer

X_nan = X_train.replace({"plas": {0: np.nan}, "pres": {0: np.nan}, "mass": {0: np.nan}})
pipe = make_pipeline(SimpleImputer(), DecisionTreeClassifier(random_state=0))
print(list(pipe.named_steps))

pipe_grid = GridSearchCV(pipe, {
    "simpleimputer__strategy": ["mean", "median"],
    "decisiontreeclassifier__max_depth": [3, 4, 5, 6],
    "decisiontreeclassifier__min_samples_leaf": [20, 40, 60],
}, cv=cv).fit(X_nan, y_train)
print(pipe_grid.best_params_, round(pipe_grid.best_score_, 3))
['simpleimputer', 'decisiontreeclassifier']
{'decisiontreeclassifier__max_depth': 5, 'decisiontreeclassifier__min_samples_leaf': 40, 'simpleimputer__strategy': 'mean'} 0.738

In this data, a glucose (plas), blood pressure (pres) or BMI (mass) of 0 means "not measured", as the public datasets lesson showed, so replace marks those zeros as missing. The imputer then fills them, and the grid search chooses how it fills them along with the tree's settings. Because the imputer is inside the pipeline, each fold learns its fill values from its own training rows only.

The best pipeline scores 0.738, a little below the 0.753 of the tree on the raw data. Fixing the zeros was the right thing for the data, yet the score fell. A likely reason: for a tree, "this value wasn't measured" can be a clue in itself, and filling it with the average hides that clue. You'd only know by trying both, which is exactly what tuning a pipeline lets you do. (SimpleImputer(add_indicator=True) keeps the clue by adding a "was missing" column.)

SituationUse
One or two settings, a few values eachGrid search: it's small and checks everything
Three or more settingsRandom search with 20 to 60 tries
You don't know the right range at allRandom search over a wide range, then a small grid around the best area
Settings that vary over orders of magnitude, such as a penalty from 0.001 to 100Random search with scipy.stats.loguniform, or a grid like [0.001, 0.01, 0.1, 1, 10, 100]
Each fit takes minutes or hoursRandom search with few tries, or smarter tools such as Optuna, covered later in the course

Whatever the method, start coarse and wide, look at the results, then narrow down.

Practice

  1. Is each of these a parameter or a hyperparameter: (a) the slope of a linear regression line, (b) the test_size of a split, (c) the cut-off 1.75 in a tree's question, (d) min_samples_leaf?
Show the answer

(a) Parameter: learnt during fit. (b) Neither, strictly: it's a choice about how you evaluate, not about the model. (c) Parameter: the tree learns it. (d) Hyperparameter: you set it before training.

  1. A grid has 4 values of max_depth, 3 of min_samples_leaf and 2 of criterion, with 5-fold cross-validation. How many trees are trained, including the final refit?
Show the answer

4 × 3 × 2 = 24 combinations, × 5 folds = 120 trees, plus 1 refit on all the training data with the best settings: 121.

  1. Your grid search's best min_samples_leaf is 40, the largest value in the grid. What should you do, and why?
Show the answer

Extend the grid past 40 (for example 40, 60, 80, 120) and search again. A best value at the edge means the score might still be rising beyond it: the true best may be outside the range you tried.

  1. Widen the leaf-size grid to [20, 40, 60, 80, 120] with depths [3, 4, 5, 6, None]. Does the best score improve?
Show the answer
wide = GridSearchCV(DecisionTreeClassifier(random_state=0),
                    {"max_depth": [3, 4, 5, 6, None], "min_samples_leaf": [20, 40, 60, 80, 120]},
                    cv=cv).fit(X_train, y_train)
print(wide.best_params_, round(wide.best_score_, 3))
{'max_depth': 4, 'min_samples_leaf': 40} 0.753

No: the best is still a leaf size of 40, now in the middle of the range instead of at the edge, with the same 0.753. Leaves of 60 to 120 score lower, so the first search had found the real best. Widening the grid was still the right check: it turned "maybe there's something better" into "there isn't".

  1. A colleague reports "after tuning 500 combinations, our test accuracy is 0.91". What question do you ask first?
Show the answer

"Was the test set used to choose between the combinations?" If it was, 0.91 is the score of the luckiest of 500 tries on that test set, and it will be too optimistic. The honest number comes from data that played no part in any choice: tune with cross-validation on the training set, then score the test set once.

Interview questions

What's the difference between a parameter and a hyperparameter?

Parameters are learnt from the training data during fitting, such as regression coefficients or tree splits. Hyperparameters are set before training and control how learning happens, such as tree depth, the number of neighbours in KNN or a regularisation strength. Hyperparameters are chosen with validation data or cross-validation.

Grid search or random search: which would you use and why?

Grid search for a few hyperparameters with a handful of values each. Random search when there are several hyperparameters or wide ranges, because for the same budget it tests many more distinct values of each, which matters when only one or two hyperparameters really affect the score. For expensive models, Bayesian optimisation tools such as Optuna are more efficient still.

Why shouldn't you tune hyperparameters on the test set?

Choosing the best of many settings by test score selects the setting that happened to fit that particular test set, so the test score becomes optimistic and no longer estimates performance on new data. Tune with cross-validation or a separate validation set, and keep the test set for one final check.

Key takeaways

  • Parameters are learnt by the model; hyperparameters are settings you choose before training.
  • Tune by scoring each setting on data the model didn't train on: cross-validation on the training set.
  • GridSearchCV tries every combination; RandomizedSearchCV tries a fixed number of random ones and scales better.
  • If the best value is at the edge of your search, widen the search.
  • Choosing settings with the test set makes its score optimistic; use it once, at the end.

Frequently asked questions

How many hyperparameters should I tune?

Start with the one or two that matter most for the model, such as depth and leaf size for a tree, or the penalty strength for Ridge. Tuning many settings at once costs time and raises the risk of fitting the validation folds by luck.

Does tuning always improve a model?

Not always by much. Defaults are often reasonable, and better features usually help more than tuning. But for models that overfit easily, such as deep trees, tuning the settings that control complexity can make a big difference.

What is Optuna?

A Python library that searches hyperparameters with Bayesian optimisation: it uses the results of earlier tries to choose promising settings next, so it needs fewer tries than random search on slow models.

What to learn next

  1. Use every idea in this module in the project: diagnose and fix an overfitting model, the next lesson.
  2. Revisit cross-validation explained, which every search here relies on.
  3. Tune a penalty strength in Ridge and Lasso regression.