Imagine two students who train the same network on the same data with the same code. One uses a learning rate of and the other uses . 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 (P4.13), the batch size (P4.15), the strength 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.
- 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).
- For each candidate setting, train on the training set and score it on the validation set.
- Pick the setting with the best validation score.
- 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 -fold cross-validation instead, which costs 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 and one of behave very differently, while and behave almost the same. What counts is the ratio, not the difference. So a search should treat each factor of (each decade) equally.
Suppose the learning rate may be anywhere from to . If you draw it uniformly from , then the probability of a value above is . 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:
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 and for any positive setting whose useful values span several orders of magnitude.
Not every setting is a scale. A dropout probability between and , or a number of layers from to , is searched on its plain range. For a momentum close to it is common to search on a log scale, because and differ as much as and do.
Grid search
Grid search lists a few values for each hyperparameter and tries every combination. With values for each of hyperparameters it costs
Three values each: runs for one setting, for two, for three, for five and for ten. Bengio’s chapter gives the example of five hyperparameters with six values each, which is 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 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
Random search draws each setting independently from its own distribution (uniform, or log-uniform for scales) and runs each draw. With trials, every setting takes different values. If only one setting matters, all trials count toward exploring it.
That has a number attached. If the best of the range of one important setting is the target, each trial lands in it with probability . The chance that at least one of independent trials lands in it is
For this is . Sixty random trials reach the best of an important setting about times in , however many other settings there are. A grid with sixty runs would have only or values per setting for two settings, and fewer for more settings. The chance reaches at . 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 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.
Things to try:
- Count the ticks and read the best values. With runs the grid tests learning rates and random search tests . The grid’s best is , random search averages over 200 seeds and beats this grid in of them, though a single run can lose.
- Raise the budget to 25, then 36. At the grid still has its closest line from the peak and stays at , while random search averages . At the grid reaches because a line happens to fall near the peak (random search averages ). 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 runs against . 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, . For a setting whose surrogate score is Gaussian with mean and standard deviation (when higher is better),
where and are the cumulative distribution function and the density of the standard Gaussian.
Go deeper Three settings, worked out
Take . Setting A: , , so EI is (probably a little better than the best). Setting B: , , so EI is (a worse mean, but so uncertain that it may be much better). Setting C: , , so EI is (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 configurations and a keep-a-third rule, the rounds are
- configurations for epoch: epochs,
- for epochs: epochs,
- for epochs: epochs,
- for epochs: epochs.
The whole search costs epochs. Training all configurations for the full epochs would cost . 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 models at a true accuracy of on examples gave a best of that fell back to on fresh data. The cell below repeats it for , , and 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 is above the truth, which is about standard deviations of one score.
- Smaller validation sets inflate more. With examples the best of shows . The configurations are all equal, so the winner was lucky and scores on fresh data.
Real configurations differ, and a real search finds real differences along with the luck. The practical rules:
- 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).
- 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.
- Keep the validation set large enough for the differences you care about, and count how many settings you tried (P1.D13 shows error bars).
- 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 to , 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 : round trains configurations for units each, so every round costs units.
- Winner’s curse: for equal configurations with true score and a measurement spread of , the best seen is about , with for and for (the expected maximum of standard Gaussian draws). The spread of one accuracy on examples is .
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.969The penalty strength differs by a factor of among the three best candidates, and their scores hardly differ. The worst candidate used a learning rate of 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 is close to the cross-validation accuracy of , as it should be when the test rows stayed out of the search.
Check your understanding
Only the learning rate matters in a problem with two hyperparameters. Why does random search with trials usually explore it better than a grid?
The grid repeats each of its three learning rates for three values of the other setting, so six of its runs add nothing about the setting that matters. The training length is the same for both. A random draw can miss the best value, which is why the comparison is about averages. A grid can also use a log scale, so that is not the difference.
A search of many settings ends with a best validation accuracy of . Which number should you report as the expected accuracy on new data?
The best validation score is optimistic, because the setting was chosen for having the best score, and that includes some luck. The mean over all trials is pessimistic because it includes bad settings. The training accuracy says nothing about new data. The test set, looked at once, gives an estimate that the choice did not touch.
Fifty configurations all have a true accuracy of . Each is measured on validation examples, and the best score seen is . What accuracy do you expect from that winner on fresh data?
All fifty configurations are equal, so the winner has the same true accuracy as the others. Its extra score was luck, and on fresh data it falls back to the truth, as in the simulation. There is no reason for it to land halfway, and a larger score on one measurement does not make a model stronger when the gap is within the noise.
Successive halving gives every configuration a small budget and keeps the best third for a larger budget. What does it assume?
The method saves compute by stopping configurations that look weak early, which works when early ranks predict late ranks. That fails for a setting that starts slowly and finishes well, such as a small learning rate. The size of the validation set and the number of important settings are not part of the assumption, and the configurations are not equal, or there would be nothing to choose.
In Bayesian optimization with expected improvement, what is the job of the acquisition function?
The surrogate model estimates the score and the uncertainty at untried settings, and the acquisition function turns those estimates into a ranking of where to try next. It does not train the network, does not replace the data splits, and it is not an average of the past scores.
Exercises
- A model has four hyperparameters, and you want 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 answer
runs, and only different learning rates, each repeated times. random trials test different learning rates. - You run random trials, and the top of one important setting is the target. What is the chance that at least one trial lands in it?
Show answer
. - The learning rate is searched between and . What fraction of draws falls below if you draw uniformly on the raw range, and if you draw log-uniformly?
Show answer
Raw uniform: , about one draw in a hundred. Log-uniform: the exponent is uniform on and the draws below have exponent in , which is half of the range, so . - Successive halving starts with configurations for 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 for epochs use?
Show answer
The rounds are , , , and epochs, which is for each of rounds, so epochs. Full training of all is epochs. - Twenty configurations are all truly at accuracy and are measured on examples, so one score has a standard deviation of . About how far above is the best score, if the expected maximum of standard Gaussian draws is ?
Show answer
, so the best score is about . The simulation of the exact binomial gives . - You tune candidate settings with -fold cross-validation and then evaluate the choice by nested cross-validation with outer folds and inner folds. About how many model fits does the nested version need, ignoring the final refits?
Show answer
Plain -fold cross-validation needs fits. The nested version needs fits, because each of the outer folds runs a -fold search over all 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.