Search

Search papers and lessons

Hyperparameter Optimization

Level 3 · 10 min read

Hyperparameter optimization is the search for the settings a model is not trained to learn, such as its learning rate, chosen by trying candidates and scoring each on held-out data.

On this page

  • Colour = topic mix
  • Probability
  • Linear algebra
  • Discrete math
  • Learning basics
  • Calculus
  • Inference
  • ReadReady to readNot yet

TL;DR

A model has two kinds of numbers. Parameters, such as the weights of a network, are learned from data during training. Hyperparameters, such as the learning rate or the strength of a penalty, are set before training and control how that learning runs. Hyperparameter optimization is the procedure for choosing them: train a model for each candidate setting, score each one on held-out validation data, and keep the best.

Builds on: Train, Validation and Test Sets, Cross-Validation, Bayesian Optimization · Leads to: Successive Halving, Multi-Armed Bandit

Where it's used

Training a fraud detector. A bank's model for flagging card fraud has a depth limit, a learning rate and a penalty on complexity. Each choice changes how many fraud cases are caught and how many good payments are blocked. The team tries a set of combinations, scores each on a validation month of transactions, and keeps the one with the best trade-off.

Training an image classifier. A convolutional network trained on photos has a learning rate that can make training either converge in hours or diverge in the first minute. Engineers commonly try a few orders of magnitude, such as 0.1, 0.01 and 0.001, before fine-tuning around the best one. The chosen value is then fixed for the final training run. See Learning Rate.

Choosing how much to regularise. A recommender system needs a penalty strength that stops it Overfitting the ratings it has seen. Too little penalty and the model memorises the training ratings; too much and it cannot learn the taste patterns at all. The penalty is a hyperparameter, and its value is found by scoring several settings on users the model has not seen.

How it works

Take a model with one hyperparameter, the penalty strength λ, and three candidate values: 0.1, 1 and 10. Training is done on the training set, and the score is measured on the validation set.

  1. Write down the candidates. The search space here is 10.
  2. Train one model per candidate. Train with λ = 0.1, then with λ = 1, then with λ = 10. Each run starts from scratch, and the training data is the same each time. Check: three candidates means three full training runs.
  3. Score each model on validation data. Suppose the validation error is 0.30 for λ = 0.1, 0.22 for λ = 1 and 0.27 for λ = 10. The validation data was never used to fit the weights, so these numbers estimate how the model will do on new cases.
  4. Pick the best. The lowest error is 0.22, at λ = 1. Choose λ = 1.
  5. Measure once on the test set. The test set is used only now, to report how well the chosen model generalises. Its score is not used to make any of the choices above. Suppose it is 0.24. That is the number reported.
flowchart LR
  S["candidate settings"] --> T["train one model per setting on the training set"]
  T --> V["score each model on the validation set"]
  V --> B["keep the setting with the best validation score"]
  B --> F["report one test score for that setting"]

The loop in the middle is the whole idea. Everything that follows in this lesson is about how to choose the candidates (step 1) and how to spend the training budget (step 2).

The math

Let θ\theta be a hyperparameter setting, and let Dtrain\mathcal{D}_{\text{train}} and Dval\mathcal{D}_{\text{val}} be the training and validation data. Let A(θ,Dtrain)A(\theta, \mathcal{D}_{\text{train}}) be the function that trains a model with setting θ\theta, and let LvalL_{\text{val}} be the validation loss. The goal is

θ⋆=arg⁡min⁡θ∈Θ  Lval(A(θ,Dtrain))\theta^{\star} = \arg\min_{\theta \in \Theta} \; L_{\text{val}}\big(A(\theta, \mathcal{D}_{\text{train}})\big)

where Θ\Theta is the search space. Each evaluation of the function inside the brackets is one full training run, which is why the search is expensive.

Step 2 in symbols: the search space and the budget

A grid search fixes a finite list of values for each hyperparameter and tries every combination. With kk values for each of dd hyperparameters, it runs kdk^d trainings. The toy example has d=1d = 1 and k=3k = 3, so 3 trainings.

Random search instead draws nn settings from a distribution over Θ\Theta, for example a uniform distribution on log⁡10\log_{10} of the learning rate (the base-10 logarithm, so each decade gets equal weight). The budget is nn trainings, chosen in advance.

Step 3 in symbols: scoring

For each candidate, compute LvalL_{\text{val}} on the validation data only. In the toy example, the three losses are L(0.1)=0.30L(0.1) = 0.30, L(1)=0.22L(1) = 0.22 and L(10)=0.27L(10) = 0.27. The argmin is θ⋆=1\theta^{\star} = 1, because 0.220.22 is smaller than both 0.270.27 and 0.300.30.

Step 4 in symbols: the Bayesian shortcut

When each training is very costly, a model of the loss is built from the evaluations done so far (a surrogate, see Bayesian Optimization). An Acquisition Function then picks the next setting to try by weighing the predicted loss against the uncertainty about it. The loop repeats until the budget runs out, and the same argmin rule picks the answer at the end.

Worked examples

Example
1. One hyperparameter, three candidates
  1. Candidates for λ: 0.1, 1, 10.
  2. Validation errors: 0.30, 0.22, 0.27.
  3. The smallest error is 0.22, which belongs to λ = 1.
  4. Report λ = 1 as the chosen setting, with its test error measured once.
Example
2. A small grid over two hyperparameters

A model has learning rate in 0.1 and batch size in 64. A grid search runs 3 × 2 = 6 trainings.

  1. Validation accuracy for each pair, learning rate then batch size:
    • 0.001 with 32: 0.81; 0.001 with 64: 0.80
    • 0.01 with 32: 0.88; 0.01 with 64: 0.86
    • 0.1 with 32: 0.85; 0.1 with 64: 0.52 (training diverged)
  2. The highest accuracy is 0.88, at learning rate 0.01 and batch size 32.
  3. Check: no other pair reaches 0.88, so there is no tie to break.
  4. The diverged run is kept in the table. A setting that breaks training is information, and it shows the learning rate has to stay below a limit.
Example
3. A realistic case: one setting matters, one does not

An image model has two hyperparameters: learning rate, which strongly affects accuracy, and dropout rate, which barely does. The team has a budget of 9 trainings. Compare two designs.

  1. Grid design: 3 learning rates × 3 dropout rates = 9 runs. The learning rate takes only 3 distinct values across all runs.
  2. Random design: 9 draws, each with its own learning rate and dropout rate. The learning rate takes 9 distinct values.
  3. Suppose accuracy depends only on the learning rate. The grid has explored 3 values of the setting that matters; the random design has explored 9.
  4. The random design is the better use of the same budget here, because the grid spends 3 of its 9 runs repeating each learning rate with a dropout value that makes no difference.
  5. This is the argument of Bergstra and Bengio (2012): when only a few hyperparameters matter, random search covers the important ones more densely.

Try it: a model has learning rate and dropout, and only learning rate matters. You have a budget of 4 trainings. How many distinct learning rates does a 2 × 2 grid test, and how many does a random design of 4 draws test? Answer: the grid tests 2 distinct learning rates (2 values of dropout are repeated across them); the random design tests 4 distinct learning rates.

Common mistakes and tradeoffs

It is tempting to think the test set is the place to choose the best setting, since it is the most realistic data. In fact, if the test score drives the choice, the reported score is optimistic, because the choice was made to fit that test set. The test set is used once, after all choices are fixed.

It is tempting to think that a grid search is thorough and therefore safe. In fact a grid spends most of its runs on combinations that are redundant when only some hyperparameters matter, and it never tries values between the grid points. A random search or a Bayesian search usually reaches a good setting with fewer runs.

It is tempting to search a learning rate on a linear scale, with values 0.1, 0.2, 0.3 and so on. In fact the useful range often spans several orders of magnitude, so the candidates should be spaced on a log scale: 0.0001, 0.001, 0.01, 0.1.

It is tempting to think that a search over many settings is free because it only changes one number. In fact each candidate is a full training run, so the cost multiplies: 20 candidates trained for a week each is 20 weeks of compute.

When to use it: whenever a model has settings you choose by hand and a reliable validation set exists. When not to: when there is no held-out data, or when a single run is so cheap that the default settings from a known recipe are good enough. Alternatives include tuning by hand from a known recipe, Successive Halving for stopping weak runs early, and Multi-Armed Bandit methods that trade exploration against exploitation.

History

Early neural network work set hyperparameters by hand and by experience, and results depended heavily on the person doing the tuning. As models grew, systematic search became necessary. Grid search, which tries every combination on a fixed list, was the default for many years.

In 2012, Bergstra and Bengio showed on several tasks that random search often finds equally good settings with far fewer trainings than grid search, because only a few hyperparameters usually matter. In the same year, Snoek, Larochelle and Adams showed that a Bayesian model of the validation loss could pick settings more efficiently still, which led to the surrogate-based methods described above.

Recap

  • A hyperparameter is a setting chosen before training; a parameter is learned during it.
  • Each candidate setting costs one full training run, scored on validation data.
  • Grid search tries every combination; random search samples; Bayesian search models the loss and picks the next point.
  • The test set is used once, after every choice is made.
  • Next: Successive Halving stops weak runs early to spend the budget on promising ones.

Check yourself

QuestionName one hyperparameter and one parameter of a neural network, and say how each is set.Show answer

The learning rate is a hyperparameter: it is chosen before training and fixed during it. A weight is a parameter: it is learned from the training data during training. A typical answer also notes that hyperparameters are chosen by scoring candidates on validation data.

QuestionA search tries learning rates 0.001, 0.01 and 0.1, and validation errors are 0.40, 0.28 and 0.31. Which setting is chosen, and why not the one with the lowest training error?Show answer

The learning rate 0.01 is chosen, because its validation error 0.28 is the lowest. The training error is not used to choose, since a model can reduce its training error by overfitting and then do worse on new data.

QuestionWhy does a random search of 9 draws test more distinct values of an important hyperparameter than a 3 by 3 grid?Show answer

The grid repeats each value of the important hyperparameter three times, once for each value of the unimportant one, so it has only 3 distinct values. Each random draw has its own value, so 9 draws give 9 distinct values, which covers the important hyperparameter more densely for the same budget.

QuestionA team tunes its learning rate by scoring each candidate on the test set, then reports the best test score. What is wrong, and what should they do?Show answer

The reported score is optimistic, because the choice of learning rate was fitted to the test set, so the test set no longer measures generalisation to new data. They should tune on the validation set, fix the choice, and then report one score on the untouched test set.

Sources