Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 4: Neural Network Foundations

Hyperparameter tuning

P4.2340 min●●○ IntermediateReviewed Dec 3, 2026

Why this matters for machine learning

Training finds the weights, but the learning rate, the penalty strength and the size of the network are chosen by you, and a poor choice can ruin a good model. A search turns that choice into a small budgeted experiment that you can run and report honestly.

Before this: Train, validation and test sets, Optimizers, Learning-rate schedules

After this lesson you can

  • Separate parameters from hyperparameters, and run a search with the validation-set protocol so that the test set is used once
  • Say which hyperparameters usually matter most for a network, and search the learning rate and the penalty strength on a log scale
  • Count the cost of a grid (kdk^d runs), compute the chance that random search reaches the best few percent of one setting, and say when a grid is competitive
  • Describe coarse-to-fine search, Bayesian optimization and successive halving in a few sentences each
  • Explain the winner's curse of a search with numbers, and name what protects against it

Imagine two students who train the same network on the same data with the same code. One uses a learning rate of 0.10.1 and the other uses 0.0010.001. One of them may get a model that works, and the other may conclude that the method does not work, although nothing about the data or the model was wrong. A single number that nobody learned from the data made the difference.

Such numbers are everywhere in deep learning: how fast to learn, how strong a penalty to apply, how wide to make the layers. This lesson is about choosing them well when every try costs a whole training run.

Parameters and hyperparameters

A parameter is a number that training finds by itself, such as a weight (P4.8). A hyperparameter is a number that you choose around the training: the learning rate η\eta (P4.13), the batch size BB (P4.15), the strength λ\lambda of weight decay (P4.17), the dropout probability, the number of layers and units (P4.3), the length of training. P3.A4 drew the same line and said where the choice is made: on a validation set.

Choosing hyperparameters is an optimization problem of its own (P1.F1). Its objective is the validation score. Its inputs are the hyperparameters. And each evaluation of the objective is a complete training run, which may take minutes or days. There is no cheap gradient of the validation score with respect to the learning rate that you can follow. That is why the methods in this lesson only try settings and look at the results. They are called black-box methods, because they treat the training run as a box that takes settings in and returns one number.

The protocol: tune on validation, report once on test

The rules of P3.A4 apply unchanged, and a search makes them more important, because a search looks at the validation score many times.

  1. Split the data into training, validation and test sets before anything else. Scaling and every other step that learns from data is fitted on the training rows only (P3.A11).
  2. For each candidate setting, train on the training set and score it on the validation set.
  3. Pick the setting with the best validation score.
  4. Look at the test set once, for the final model, and report that number whatever it is. If it disappoints you, do not go back and search again against the same test set.

When the data set is small, a single validation split is noisy. Then each candidate is scored by kk-fold cross-validation instead, which costs kk runs per candidate and uses every example for validation once (P3.A4). When you also need an honest estimate and have no spare test set, P3.A4 describes nested cross-validation: an inner loop that chooses the setting inside each outer training part. Bengio (2012) calls the same idea double cross-validation. For networks on large data one validation split is usual, because cross-validation multiplies the cost.

What matters most

A network has many hyperparameters, and they are not equally important. Bengio (2012) writes that the initial learning rate is often the single most important hyperparameter and that, if there is time to tune only one, it is the one to tune. He also advises tuning it to within roughly a factor of two. So the first search is almost always over the learning rate.

A common order after that, as a rule of thumb and not a law:

  • The learning rate and its schedule (P4.13, P4.14). The range test of P4.14 gives an order of magnitude cheaply.
  • The batch size (P4.15). Changing it moves the best learning rate, so re-check the rate after changing it.
  • The regularization strength: weight decay and dropout (P4.17). Too weak and the model overfits, too strong and it cannot fit even the real pattern.
  • The size of the network: width and depth (P4.3, P4.11). A bigger network can fit more, and it costs more to train and can overfit more.

Bergstra and Bengio (2012) studied this with a statistical analysis of several neural-network problems. They found that for most data sets only a few hyperparameters really matter, and that which ones matter is different from one data set to another. You cannot know in advance which two or three settings will carry the result for your problem. That fact decides how a search should be built, as the next sections show.

Wide or deep? Theory shows that some functions need far fewer units with depth than without (P4.11), but it does not say whether your task looks like those functions. So width and depth are two more hyperparameters: try a few sizes at a fixed training budget and compare them on the validation set.

Scales: search the learning rate on a log scale

A learning rate of 0.0010.001 and one of 0.00010.0001 behave very differently, while 0.09010.0901 and 0.09020.0902 behave almost the same. What counts is the ratio, not the difference. So a search should treat each factor of 1010 (each decade) equally.

Suppose the learning rate may be anywhere from 10−410^{-4} to 10−110^{-1}. If you draw it uniformly from [0.0001,0.1][0.0001, 0.1], then the probability of a value above 0.010.01 is 0.09/0.0999=0.9010.09/0.0999 = 0.901. About nine draws in ten land in the top decade, and the bottom decade gets about one in a hundred. The fix is to draw the exponent uniformly:

x∼Uniform(−4,−1),η=10x.x \sim \mathrm{Uniform}(-4, -1), \qquad \eta = 10^{x}.

This is a log-uniform draw. Each decade gets one third of the draws. It uses the uniform distribution of P1.D3 on the exponent. Bengio (2012) also recommends sampling hyperparameters of this kind uniformly in the log domain. The same advice holds for the weight decay λ\lambda and for any positive setting whose useful values span several orders of magnitude.

Not every setting is a scale. A dropout probability between 00 and 0.50.5, or a number of layers from 11 to 66, is searched on its plain range. For a momentum close to 11 it is common to search 1−μ1-\mu on a log scale, because 0.90.9 and 0.990.99 differ as much as 0.990.99 and 0.9990.999 do.

Grid search lists a few values for each hyperparameter and tries every combination. With kk values for each of dd hyperparameters it costs

kd runs.k^{d}\ \text{runs}.

Three values each: 33 runs for one setting, 99 for two, 2727 for three, 243243 for five and 5904959049 for ten. Bengio’s chapter gives the example of five hyperparameters with six values each, which is 65=77766^5 = 7776 configurations. The cost grows exponentially with the number of settings. This is the same cost explosion as the grid of P1.F1.

There is a second, quieter weakness. In a grid, every value of the learning rate is repeated in the grid for every combination of the other settings. If the learning rate is the only setting that matters, a 3×33\times 3 grid has run only three different learning rates, and the other six runs repeated them.

Grid search has strengths too. It is simple and easy to explain, it parallelizes trivially, and it is a good choice for one or two settings.

Random search draws each setting independently from its own distribution (uniform, or log-uniform for scales) and runs each draw. With nn trials, every setting takes nn different values. If only one setting matters, all nn trials count toward exploring it.

That has a number attached. If the best 5%5\% of the range of one important setting is the target, each trial lands in it with probability 0.050.05. The chance that at least one of nn independent trials lands in it is

1−0.95n.1 - 0.95^{n}.

For n=60n = 60 this is 1−0.9560=0.9541 - 0.95^{60} = 0.954. Sixty random trials reach the best 5%5\% of an important setting about 9595 times in 100100, however many other settings there are. A grid with sixty runs would have only 77 or 88 values per setting for two settings, and fewer for more settings. The chance reaches 0.950.95 at n=59n = 59. This is the argument of Bergstra and Bengio (2012): when only a few settings matter, random search covers each important setting with many more distinct values than a grid of the same cost, and it is simple to run, to stop early and to extend with more trials.

Random search has its own noise. A few random draws can miss a good region by bad luck, and the result changes with the seed. That is why the widget below has a reseed button.

The signature picture: coverage

The widget shows a made-up map of validation accuracy over two hyperparameters: the learning rate on the horizontal axis (log scale) and the weight decay on the vertical axis (log scale). Brighter is better. In the first map, the learning rate matters a lot, and the weight decay matters little. The first panel runs a k×kk\times k grid. The second panel runs the same number of random trials, or a simple coarse-to-fine search. The tick marks outside each frame show which values of each setting were tried.

seed 1

9 runs each. Grid: best accuracy 0.808, from 3 values of each setting. Random (seed 1): best 0.905, from 9 different learning rates. Over 200 reseeds, random search averages 0.838 and beats this grid in 75% of them.

Grid, 9 runs
learning rate (log scale) →3 values triedweight decay →3 values

Best: 0.808 (3 learning rates)

Random, 9 runs
learning rate (log scale) →9 values triedweight decay →9 values

Best: 0.905 (9 learning rates)

0.50 0.92 validation accuracy of the made-up model

grid or random run coarse-to-fine second round best run. Ticks outside the frame show the values each method tried.

Grid best
0.808
Random, mean of 200
0.838
Coarse to fine, mean of 200
0.856
Random beats grid
75%

The accuracy map is made up and fixed: its peak is at 0.43 on the learning-rate axis and 0.65 on the weight-decay axis (each axis scaled to 0 to 1). The grid always puts its points at the centres of equal cells, so the result depends on where the peak falls between grid lines. The random points come from a seeded generator, so a seed always gives the same points. Coarse to fine spends half the runs at random, then the other half at random inside a box of half-width 0.15 around the best point so far.

A made-up accuracy map over the learning rate and the weight decay, both on a log scale. Left (top on a phone): a grid. Right (bottom): random search or coarse-to-fine search with the same number of runs. Black diamonds mark the best run. Ticks outside the frame show the distinct values tried for each setting. The button “Reseed” draws new random points. The numbers under the panels repeat the search with 200 seeds. The map is made up, and the search is seeded, so the same settings always give the same picture.

Things to try:

  • Count the ticks and read the best values. With 99 runs the grid tests 33 learning rates and random search tests 99. The grid’s best is 0.8080.808, random search averages 0.8380.838 over 200 seeds and beats this grid in 75%75\% of them, though a single run can lose.
  • Raise the budget to 25, then 36. At 2525 the grid still has its closest line 0.070.07 from the peak and stays at 0.8100.810, while random search averages 0.8890.889. At 3636 the grid reaches 0.9150.915 because a line happens to fall near the peak (random search averages 0.9010.901). A grid depends on where its lines fall.
  • Switch to “Both matter”. With a round peak the grid is as good as random search or better: at 1616 runs 0.9010.901 against 0.8370.837. Random search wins when a few settings carry the result.

Coarse to fine. In practice, random search is often run in rounds: a wide search with short runs, then a narrower box around the best region (the right panel’s second mode), then longer runs (Bengio, 2012, calls this multi-resolution search). If the best value sits on the edge of your range, move the range. Do not narrow too early, because the first round is noisy.

Bayesian optimization

Random search ignores what the earlier trials found. Bayesian optimization uses it. After a few trials it fits a cheap surrogate model to the pairs (settings, score). Snoek, Larochelle and Adams (2012) used a Gaussian process, which gives for every untried setting both an estimate of the score and an uncertainty. An acquisition function then scores each untried setting by how useful a trial there would be, and the next training run goes where the acquisition function is highest. After each run, the surrogate is refitted.

One common acquisition function is expected improvement: the expected amount by which a trial would beat the best score so far, f∗f^*. For a setting whose surrogate score is Gaussian with mean μ\mu and standard deviation ss (when higher is better),

EI=(μ−f∗) Φ(z)+s φ(z),z=μ−f∗s,\begin{aligned} \mathrm{EI} &= (\mu - f^*)\,\Phi(z) + s\,\varphi(z),\\ z &= \frac{\mu - f^*}{s}, \end{aligned}

where Φ\Phi and φ\varphi are the cumulative distribution function and the density of the standard Gaussian.

Go deeper Three settings, worked out

Take f∗=0.90f^* = 0.90. Setting A: μ=0.91\mu = 0.91, s=0.01s = 0.01, so EI is 0.01080.0108 (probably a little better than the best). Setting B: μ=0.88\mu = 0.88, s=0.05s = 0.05, so EI is 0.01150.0115 (a worse mean, but so uncertain that it may be much better). Setting C: μ=0.88\mu = 0.88, s=0.01s = 0.01, so EI is 0.000080.00008 (probably worse, and we are fairly sure of it).

Expected improvement prefers the uncertain setting B to A, and both far to C. The rule balances exploiting what looks good and exploring what is unknown. This is the shape of the idea only. Real implementations differ in the surrogate they use, in how they treat integer and categorical settings, and in how they run trials in parallel. Bayesian optimization pays most when each run is expensive and there are few settings. Bergstra and Bengio (2012) suggest that random search is a natural baseline to compare any adaptive method against.

Stopping weak trials early

Most trials in a search are bad, and a bad trial often shows it early. Successive halving uses that (Jamieson and Talwalkar studied it for hyperparameter search in a 2015 preprint). Start many configurations with a small budget (for example one epoch each), keep the best third, give the survivors three times the budget, and repeat. With 2727 configurations and a keep-a-third rule, the rounds are

  • 2727 configurations for 11 epoch: 2727 epochs,
  • 99 for 33 epochs: 2727 epochs,
  • 33 for 99 epochs: 2727 epochs,
  • 11 for 2727 epochs: 2727 epochs.

The whole search costs 4×27=1084\times 27 = 108 epochs. Training all 2727 configurations for the full 2727 epochs would cost 27×27=72927\times 27 = 729. Hyperband (Li and others, 2018) runs several such schedules that start with different numbers of configurations, to guard against the case where early scores mislead. It samples configurations at random and allocates the training budget adaptively.

The method assumes that a configuration that is behind early stays behind. That is often true and sometimes false: a small learning rate may look slow at epoch 1 and win at epoch 27, and a large one may look best early and then become unstable (P4.14). So the budget of the first round should be long enough for the ranking to mean something.

Seeds, noise and the winner’s curse

A training run has randomness in it: the initial weights (P4.12), the order of the mini-batches (P1.F4), dropout (P4.17) and augmentation (P4.18). The same settings with a different seed give a different score (P1.G3). A validation set of finite size adds more noise (P1.D13). So every score in a search is a noisy measurement of the setting’s true quality.

That noise creates a trap: the best of many noisy scores is, on average, too high, because the winner is partly the setting that was lucky (multiple comparisons, P1.D13). P1.D13’s example of 2020 models at a true accuracy of 0.800.80 on 10001000 examples gave a best of 0.8230.823 that fell back to 0.8000.800 on fresh data. The cell below repeats it for 11, 55, 2020 and 5050 configurations.

Try it: the best of many equal configurations

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Running the code gives this (on the machine used for this lesson):

one run: sd of the score = 0.0126
configs  best seen  fresh score
    1    0.800      0.800
    5    0.815      0.800
   20    0.823      0.800
   50    0.828      0.800
n = 200, 50 configs: best seen 0.861

What to notice:

  • The inflation grows with the number of tries. A single configuration shows no inflation, and the best of 5050 is 0.0280.028 above the truth, which is about 2.252.25 standard deviations of one score.
  • Smaller validation sets inflate more. With 200200 examples the best of 5050 shows 0.8610.861. The configurations are all equal, so the winner was lucky and scores 0.8000.800 on fresh data.

Real configurations differ, and a real search finds real differences along with the luck. The practical rules:

  1. Report the test score of the final model, not the best validation score. The test set did not take part in the choice (P3.A4).
  2. Do not read small gaps as differences. If two settings differ by less than the noise of one run, they are tied. For the best few candidates, run several seeds each, and compare the means with their spread.
  3. Keep the validation set large enough for the differences you care about, and count how many settings you tried (P1.D13 shows error bars).
  4. Record the seeds and the settings of every trial, so the search can be repeated (P1.G3, P12.3).

Budget thinking and tools

A search has a budget of runs or GPU-hours. Start from a published recipe for a similar model, use short runs and the range test of P4.14 for the first round, and stop when the best-so-far curve flattens.

  • Look at the curves, not only the final number (P4.22): a loss that explodes or stays flat often ends a trial early.
  • Record the seed and the settings of every trial (P12.3).

Optuna and Ray Tune are Python libraries that run random, Bayesian and early-stopping searches. scikit-learn’s GridSearchCV and RandomizedSearchCV do grid and random search with cross-validation. The Code tab shows RandomizedSearchCV with log-uniform draws on the digits data: twelve settings of one small network have a cross-validation accuracy from 0.6460.646 to 0.9700.970, so the choice matters a great deal.

The three depths

Intuition

Tuning is like tuning a radio. The knob for the station (the learning rate) matters a great deal, and you turn it by ratios, not by fixed amounts. The knob for the treble (the weight decay) matters less. A grid sets the dial at three fixed stations and tries the treble at each of them. A random search turns both knobs to many different positions, so it hears many more stations. Where the analogy breaks: with a radio you hear the quality at once, while here each reading takes a whole training run, and every reading is a little noisy. The loudest-sounding reading is partly luck.

Math

  • Successive halving with keep-fraction 1/ρ1/\rho: round ii trains N/ρiN/\rho^{i} configurations for ρi\rho^{i} units each, so every round costs NN units.
  • Winner’s curse: for kk equal configurations with true score μ\mu and a measurement spread of ss, the best seen is about μ+cks\mu + c_k s, with ck=1.87c_k = 1.87 for k=20k = 20 and 2.252.25 for k=50k = 50 (the expected maximum of kk standard Gaussian draws). The spread of one accuracy on NN examples is μ(1−μ)/N\sqrt{\mu(1-\mu)/N}.

Code

Run locally with scikit-learn 1.8.0: a log-uniform random search with 12 candidates and 3-fold cross-validation on the development rows (80% of the data), then the held-out test rows once. Libraries such as Optuna and Ray Tune keep the same structure: a function trains with the given settings and returns a validation score, and the library chooses the next settings.

from scipy.stats import loguniform
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split, RandomizedSearchCV
from sklearn.neural_network import MLPClassifier

X, y = load_digits(return_X_y=True)
X = X / 16.0
X_dev, X_test, y_dev, y_test = train_test_split(
    X, y, test_size=0.2, random_state=0, stratify=y)

model = MLPClassifier(hidden_layer_sizes=(32,), max_iter=60, random_state=0)
space = {
    "learning_rate_init": loguniform(1e-4, 1e-1),
    "alpha": loguniform(1e-6, 1e-1),       # L2 penalty strength
}
search = RandomizedSearchCV(model, space, n_iter=12, cv=3, random_state=0)
search.fit(X_dev, y_dev)                   # tuning sees only the dev rows

res = search.cv_results_
print("rank  lr      alpha  CV acc")
for i in res["rank_test_score"].argsort()[:3]:
    print("%4d  %.4f  %.0e  %.3f" % (res["rank_test_score"][i],
          res["param_learning_rate_init"][i], res["param_alpha"][i],
          res["mean_test_score"][i]))
print("worst CV accuracy: %.3f" % res["mean_test_score"].min())
print("test accuracy:     %.3f" % search.score(X_test, y_test))
rank  lr      alpha  CV acc
   1  0.0407  8e-03  0.970
   2  0.0087  1e-04  0.969
   3  0.0250  8e-02  0.969
worst CV accuracy: 0.646
test accuracy:     0.969

The penalty strength differs by a factor of 800800 among the three best candidates, and their scores hardly differ. The worst candidate used a learning rate of 0.00020.0002 and had not converged in 60 epochs, so the length of training and the learning rate interact (P4.14). That is one run on one small problem, not a rule. The test accuracy of 0.9690.969 is close to the cross-validation accuracy of 0.9700.970, as it should be when the test rows stayed out of the search.

Check your understanding

  1. Only the learning rate matters in a problem with two hyperparameters. Why does random search with 99 trials usually explore it better than a 3×33\times 3 grid?

  2. A search of many settings ends with a best validation accuracy of 0.910.91. Which number should you report as the expected accuracy on new data?

  3. Fifty configurations all have a true accuracy of 0.800.80. Each is measured on 10001000 validation examples, and the best score seen is 0.830.83. What accuracy do you expect from that winner on fresh data?

  4. Successive halving gives every configuration a small budget and keeps the best third for a larger budget. What does it assume?

  5. In Bayesian optimization with expected improvement, what is the job of the acquisition function?

Exercises

  1. A model has four hyperparameters, and you want 55 values of each in a grid. How many training runs is that, and how many different learning rates does it test if the learning rate is one of the four?
    Show answer54=6255^4 = 625 runs, and only 55 different learning rates, each repeated 125125 times. 6060 random trials test 6060 different learning rates.
  2. You run 2020 random trials, and the top 10%10\% of one important setting is the target. What is the chance that at least one trial lands in it?
    Show answer1−0.920=1−0.1216=0.8781 - 0.9^{20} = 1 - 0.1216 = 0.878.
  3. The learning rate is searched between 10−510^{-5} and 10−110^{-1}. What fraction of draws falls below 10−310^{-3} if you draw uniformly on the raw range, and if you draw log-uniformly?
    Show answerRaw uniform: (10−3−10−5)/(10−1−10−5)≈0.0099(10^{-3}-10^{-5})/(10^{-1}-10^{-5}) \approx 0.0099, about one draw in a hundred. Log-uniform: the exponent is uniform on [−5,−1][-5,-1] and the draws below 10−310^{-3} have exponent in [−5,−3][-5,-3], which is half of the range, so 0.50.5.
  4. Successive halving starts with 8181 configurations for 11 epoch and keeps a third at every round, tripling the epochs. How many epochs does the whole search use, and how many would full training of all 8181 for 8181 epochs use?
    Show answerThe rounds are 81×181\times 1, 27×327\times 3, 9×99\times 9, 3×273\times 27 and 1×811\times 81 epochs, which is 8181 for each of 55 rounds, so 405405 epochs. Full training of all is 81×81=656181\times 81 = 6561 epochs.
  5. Twenty configurations are all truly at 0.800.80 accuracy and are measured on 10001000 examples, so one score has a standard deviation of 0.01260.0126. About how far above 0.800.80 is the best score, if the expected maximum of 2020 standard Gaussian draws is 1.871.87?
    Show answer1.87×0.0126=0.02361.87\times 0.0126 = 0.0236, so the best score is about 0.8240.824. The simulation of the exact binomial gives 0.8230.823.
  6. You tune 2020 candidate settings with 55-fold cross-validation and then evaluate the choice by nested cross-validation with 55 outer folds and 44 inner folds. About how many model fits does the nested version need, ignoring the final refits?
    Show answerPlain 55-fold cross-validation needs 20×5=10020\times 5 = 100 fits. The nested version needs 5×4×20=4005\times 4\times 20 = 400 fits, because each of the 55 outer folds runs a 44-fold search over all 2020 candidates.

Next: P4.24 asks why large networks generalize at all, which is the question behind every number in this lesson, and P4.22 shows how to read the training curves that tell you which setting to change.

Key takeaways

  • A parameter is found by training (a weight). A hyperparameter is chosen by you around the training (learning rate, penalty strength, width, depth, batch size). Choose them on the validation set (or by cross-validation), and look at the test set once, at the end.
  • The learning rate is often the single most important hyperparameter of a network (Bengio, 2012). Next come the schedule and batch size, the regularization strength, and the size of the network. Which ones matter differs from one problem to the next.
  • Search scale settings such as the learning rate and the weight decay on a log scale: draw xx uniformly and use 10x10^x. Uniform draws on the raw range would spend most trials on the largest decade.
  • A grid with kk values for each of dd settings costs kdk^d runs and tests only kk distinct values of each setting. nn random trials test nn distinct values of each, so random search covers an important setting better when only a few settings matter (Bergstra and Bengio, 2012). It is no better when all settings matter about equally.
  • Coarse-to-fine search narrows the ranges in rounds. Bayesian optimization fits a surrogate to the trials so far and picks the next trial with an acquisition function such as expected improvement. Successive halving and Hyperband stop weak trials early.
  • The best validation score of many equal configurations is inflated by luck. With 50 configurations that all have a true accuracy of 0.800.80, the best score seen on 10001000 validation examples averages 0.8280.828. Re-measure the finalists on fresh data, with several seeds, and report the test score.
Found a mistake? Tell us