Back to Tutorials
Machine Learning
Intermediate

Hyperparameter Tuning Without Fooling Yourself

Search a real model’s settings by grid and at random, then watch the winner of a hundred tries fall apart on new data.

10 minInteractive: drag, click and try things as you read


Every model comes with settings you choose before training: how deep a tree grows, how fast a network learns, how strongly wiggles are punished. They’re called hyperparameters, and good ones can matter as much as the choice of model. Tuning them means trying settings and keeping whichever scores best. How you search matters less than how you score: pick the best of enough tries, and the winning score flatters the winner. Here you’ll search a real model’s settings two ways, then watch a winner fall apart on new data.

Parameters and hyperparameters#

A model’s parameters are what training learns: the weights of a network, the splits of a tree. Its hyperparameters are the choices you make before training starts, which shape what training can learn. You can’t learn them from the training data itself, because the training data always prefers the most flexible setting: a model that memorises every point scores perfectly on the points it memorised (that’s overfitting). So you score each setting on data held back from training, the validation set, or with cross-validation.

The model here draws a smooth curve through 100 noisy points. It’s called kernel ridge regression, and it has two settings. Wiggliness is how quickly each point’s influence fades with distance: low, and the curve is stiff and broad; high, and it can bend to every point. The smoothing penalty is how heavily the fit is punished for bending. Both run over many powers of ten, so they’re searched on log scales. Each try trains the model on the 100 points and measures its error on 100 more.

The obvious way to search is a grid: pick a few values for each setting and try every combination. Nine tries means three values of each. The other common way is random search: nine tries, each with both settings drawn at random from the same ranges.

Predict first

With 9 tries each, which do you expect to find the lower validation error: a 3-by-3 grid, or 9 random settings?

Try it
Made-up noisy points along a hidden curve. Every validation error, including the whole map, is computed by training the model in your browser. Draw again to see how random search varies; tap anywhere on the map to try a setting yourself.

The dark valley is where good settings live: it runs diagonally, because a wigglier curve can be tamed by a heavier penalty. The 3-by-3 grid’s best error is 0.376. None of its nine combinations lands in the darkest part of the valley: its middle wiggliness would do as well as anything with a penalty near 1, but the grid’s three penalties skip right past it. The first random draw finds 0.356, as low as anywhere on the map. Across 100 random draws, 9 random tries beat this grid 92 times. With 25 tries the grid is finer and the contest closer: random wins 58 times in 100.

That’s the argument James Bergstra and Yoshua Bengio made in 2012, testing neural networks across several datasets. Usually only a few hyperparameters really matter, and which ones depends on the problem. A grid spends most of its tries repeating the same few values of the settings that matter. Random search tries a new value of every setting on every try. It’s also easier to run: stop whenever your time runs out, and add tries later without redesigning a grid.

The best of many is flattered#

Every validation score includes some luck: the particular points in the validation set happen to suit some settings a little more than others. Try one setting, and its luck averages out. Try a hundred and keep the best, and you are partly choosing the luckiest.

Predict first

You try 100 random settings and keep the one with the lowest error on a 30-point validation set. On new data, how does the winner do?

Try it
The same made-up curve and model, computed in your browser. Each dot is one random setting: its error on the validation set across, and its error on unlimited new data up (worked out exactly from the hidden curve, which in real life you never know).

With 100 settings and 30 validation points, the winner’s validation error is 0.253. That’s impossible on new data: the noise in the measurements alone gives any model an error of at least 0.300. On new data the winner scores 0.327, and 7 of the other settings were really better. Change the validation set and the story repeats: across the ten sets, the winner’s real rank ranges from 1st to 42nd.

Give it 1,000 validation points instead and the two scores nearly agree: the winner is the real best for 7 of the 10 validation sets and never worse than fifth. Fewer tries help too. The more you try and the less data you score on, the more the winning score flatters. Gavin Cawley and Nicola Talbot showed in 2010 that this selection effect can be as large as the differences between the models being compared. Kaggle competitors know it as the shake-up, when the final standings on hidden data reshuffle the public leaderboard.

Tuning without fooling yourself#

  • Lock away a test set first. Tune using the rest, then score the final, chosen model on the test set once. That number is the honest one; the tuning score is not.
  • Score with cross-validation rather than one small validation set, so each setting’s score averages over more data.
  • For a fully honest estimate without a separate test set, use nested cross-validation: an inner loop tunes the settings and an outer loop scores the whole tuning process on data it never saw.
  • Don’t chase the third decimal place. Once you’re in the good valley, differences between settings are often smaller than the luck in your scores. Prefer the simpler or more stable setting.
  • Search sensible ranges on log scales for anything that runs over powers of ten, such as learning rates and penalties.

In code#

Grid and random search with scikit-learn (pip install scikit-learn scipy), on data like the figures’, with a test set locked away before any tuning:

import numpy as np
from scipy.stats import loguniform
from sklearn.kernel_ridge import KernelRidge
from sklearn.model_selection import GridSearchCV, RandomizedSearchCV, train_test_split

rng = np.random.default_rng(0)
x = rng.uniform(0, 2, (400, 1))
y = np.sin(3 * x[:, 0]) + 0.5 * np.sin(9 * x[:, 0]) + rng.normal(0, 0.3, 400)
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25, random_state=0)  # test set locked away

grid = GridSearchCV(KernelRidge(kernel="rbf"),
                    {"gamma": np.logspace(-1, 4, 3), "alpha": np.logspace(-6, 1, 3)},
                    cv=5, scoring="neg_root_mean_squared_error").fit(x_train, y_train)
rand = RandomizedSearchCV(KernelRidge(kernel="rbf"),
                          {"gamma": loguniform(1e-1, 1e4), "alpha": loguniform(1e-6, 1e1)},
                          n_iter=9, cv=5, scoring="neg_root_mean_squared_error", random_state=0).fit(x_train, y_train)

for name, search in [("grid, 9 settings", grid), ("random, 9 settings", rand)]:
    test = np.sqrt(np.mean((search.predict(x_test) - y_test) ** 2))
    print(f"{name}: cross-validated error {-search.best_score_:.3f}, test error {test:.3f}")
# grid, 9 settings: cross-validated error 0.306, test error 0.329
# random, 9 settings: cross-validated error 0.302, test error 0.328

In scikit-learn, gamma is the wiggliness and alpha the penalty. With 300 training points both searches find the good valley this time. Notice that each search’s own score is better than its score on the locked-away test set: the same flattery as in the second figure, on a smaller scale.

What to remember

  • Hyperparameters are choices made before training; score them on held-out data, never on the training data.
  • Random search tries a new value of every setting each time, so it usually beats a grid with the same budget; smarter searches build on it.
  • The best of many tries is flattered by luck, more so with small validation sets; keep a test set aside and score the final choice on it once.

Keep going

Sign in to save your place and keep a learning streak. Free, with Google.