Simple Algorithm
Machine Learning · Convergence · 26 min

Hyperparameter Optimization

Grid, random search, Bayesian optimization and Hyperband.

Learning rates, penalties, depths, widths: most models have settings that training does not learn, and the right values can matter as much as the choice of model. Tuning them is optimization with an objective that is noisy, expensive and gradient-free. This lesson covers the main strategies, from random search to Bayesian optimization and Hyperband, and the trap they share: overfitting the validation set.

What you’ll learn

  • Formulate hyperparameter optimization as noisy, expensive black-box (and bilevel) optimization, and explain why random search beats grid search when only a few hyperparameters matter.
  • Derive the expected-improvement acquisition function, and compare Gaussian-process, tree-Parzen and random-forest surrogates.
  • Compute the budgets of successive halving and Hyperband, and state the assumption that makes early stopping of bad configurations safe.
  • Report tuned results honestly: equal tuning budgets for baselines, held-out assessment, and the optimism of the best validation score.

The problem

A configuration λ∈Λ\boldsymbol\lambda\in\Lambda fixes everything training does not learn: continuous values (learning rate, penalty), integers (depth, width), categorical choices (optimizer, kernel) and conditional ones (the momentum only matters if the optimizer uses it). Hyperparameter optimization seeks

λ⋆∈arg min⁡λ∈Λ Lval(w⋆(λ)),w⋆(λ)∈arg min⁡w Ltrain(w;λ),\boldsymbol\lambda^\star\in\argmin_{\boldsymbol\lambda\in\Lambda}\ \loss_{\text{val}}\big(\mathbf w^\star(\boldsymbol\lambda)\big),\qquad \mathbf w^\star(\boldsymbol\lambda)\in\argmin_{\mathbf w}\ \loss_{\text{train}}(\mathbf w;\boldsymbol\lambda),

a bilevel problem: the inner problem is training, the outer one is validation.

Property of f(λ)=Lvalf(\boldsymbol\lambda)=\loss_{\text{val}}Consequence
each evaluation is a full training runbudgets of tens to thousands of evaluations; every query must count
noisy: seeds, data order and the validation sample all move itthe best observed value is optimistic; differences smaller than the noise mean nothing
no gradient in general (and none at all for discrete choices)black-box methods; gradient-based tuning exists for continuous hyperparameters by differentiating through training, at a cost in memory or approximation
cheap approximations exist: fewer epochs, a data subset, a smaller modelmulti-fidelity methods spend most of the budget on promising configurations

Search spaces matter as much as search algorithms. Scale parameters such as learning rates and penalties should be searched on a log scale (sample log⁡λ\log\lambda uniformly), since 10−410^{-4} and 10−310^{-3} differ as much as 10−110^{-1} and 11. And the evaluation protocol of Validation & Cross-Validation applies unchanged: the objective is a validation estimate, so the final assessment needs data the search never touched.

Grid versus random search

Grid search evaluates the Cartesian product of a few values per hyperparameter; random search samples configurations independently from a distribution over Λ\Lambda. Bergstra & Bengio (2012) argued that random search is more efficient because of low effective dimensionality: for a given dataset, "only a few of the hyper-parameters really matter," and which ones matter changes from dataset to dataset.

With a budget of BB trials in dd dimensions, a grid tries only B1/dB^{1/d} distinct values of each hyperparameter, while random search tries BB distinct values of every one. If only one hyperparameter matters, the grid wastes most of its budget re-testing the same few values of it.

DerivationHow many random trials suffice?
  1. P(at least one of B trials lands in the top q)=1−(1−q)BP\big(\text{at least one of }B\text{ trials lands in the top }q\big)=1-(1-q)^B

    Suppose the configurations within the best fraction qq of the search space (measured by the sampling distribution) are all good enough. Each random trial lands there with probability qq, independently of the others, so

  2. B ≥ ln⁡(1/δ)−ln⁡(1−q) ≈ ln⁡(1/δ)qB\ \ge\ \frac{\ln(1/\delta)}{-\ln(1-q)}\ \approx\ \frac{\ln(1/\delta)}{q}

    This does not depend on the dimension of Λ\Lambda, only on the volume fraction qq. Requiring probability at least 1−δ1-\delta:

Predict before you look

How many independent random trials do you need so that, with probability at least 95%, at least one lands in the best 5% of the search space?

Show the answer

59 trials

Need 1−0.95B≥0.951-0.95^B\ge0.95, so B≥ln⁡0.05/ln⁡0.95≈58.4B\ge\ln0.05/\ln0.95\approx58.4: 59 trials (1−0.9559≈0.95151-0.95^{59}\approx0.9515, while 58 gives 0.9490.949). The "top 5%" is measured by the sampling distribution, so a poorly chosen range (or a linear scale for a learning rate) can make the good region tiny.

Bayesian optimization

Bayesian optimization uses the evaluations so far. It fits a probabilistic surrogate of f(λ)f(\boldsymbol\lambda) to the observed pairs, and chooses the next configuration by maximizing an acquisition function that trades exploitation (low predicted loss) against exploration (high uncertainty). The most common acquisition is expected improvement over the best value y⋆y^\star observed so far, popularized for expensive black boxes by Jones, Schonlau & Welch (1998).

DerivationExpected improvement in closed form (minimization)
  1. EI(λ)=E[(y⋆−f)+]=∫−∞u(y⋆−μ−sz) ϕ(z) dz\mathrm{EI}(\boldsymbol\lambda)=\E\big[(y^\star-f)_+\big]=\int_{-\infty}^{u}\big(y^\star-\mu-sz\big)\,\phi(z)\,dz

    Let the surrogate's posterior at λ\boldsymbol\lambda be f(λ)∼N(μ,s2)f(\boldsymbol\lambda)\sim\mathcal N(\mu,s^2). The improvement is (y⋆−f)+(y^\star-f)_+. Write f=μ+sZf=\mu+sZ with Z∼N(0,1)Z\sim\mathcal N(0,1), and u=(y⋆−μ)/su=(y^\star-\mu)/s; improvement is positive exactly when Z<uZ<u:

  2. EI(λ)=(y⋆−μ) Φ(u)+s ϕ(u),u=y⋆−μs\mathrm{EI}(\boldsymbol\lambda)=(y^\star-\mu)\,\Phi(u)+s\,\phi(u),\qquad u=\frac{y^\star-\mu}{s}

    Use ∫−∞uϕ=Φ(u)\int_{-\infty}^u\phi=\Phi(u) and ∫−∞uzϕ(z) dz=−ϕ(u)\int_{-\infty}^uz\phi(z)\,dz=-\phi(u):

  3. ∂ EI∂μ=−Φ(u),∂ EI∂s=ϕ(u)\frac{\partial\,\mathrm{EI}}{\partial\mu}=-\Phi(u),\qquad\frac{\partial\,\mathrm{EI}}{\partial s}=\phi(u)

    EI rises as the predicted mean falls (∂EI/∂μ=−Φ(u)<0\partial\mathrm{EI}/\partial\mu=-\Phi(u)<0) and as the uncertainty grows (∂EI/∂s=ϕ(u)>0\partial\mathrm{EI}/\partial s=\phi(u)>0): both exploitation and exploration pay.

Check your understanding

The best validation error so far is y⋆=0.20y^\star=0.20. The surrogate predicts three candidates: A with μ=0.22\mu=0.22, s=0.03s=0.03; B with μ=0.19\mu=0.19, s=0.005s=0.005; C with μ=0.25\mu=0.25, s=0.10s=0.10. Which one has the highest expected improvement?

  1. A
  2. B, the only one predicted to beat 0.200.20
  3. C
  4. They are equal
Show the answer

C. C

EI is about 0.00450.0045 for A, 0.01000.0100 for B and 0.01980.0198 for C. C's mean is worst, but its uncertainty leaves a real chance of a large improvement; B is predicted to improve, but only by about 0.010.01 and with almost no chance of more. That is exploration, quantified.

SurrogateModelsGood at
Gaussian process (Snoek, Larochelle & Adams, 2012)p(y∣λ)p(y\mid\boldsymbol\lambda), with a Matérn 5/2 kernel, GP hyperparameters integrated out, cost-aware and parallel variantsfew continuous hyperparameters and small budgets
Tree-structured Parzen estimator (Bergstra, Bardenet, Bengio & Kégl, 2011)two densities, ℓ(λ)\ell(\boldsymbol\lambda) for good trials (y<y⋆y<y^\star) and g(λ)g(\boldsymbol\lambda) for the rest; EI is maximized by maximizing ℓ/g\ell/gconditional and mixed spaces, cheap updates
Random forest, SMAC (Hutter, Hoos & Leyton-Brown, 2011)p(y∣λ)p(y\mid\boldsymbol\lambda) from the spread of a forest's predictionscategorical and conditional hyperparameters, many observations
Here y⋆y^\star for TPE is a quantile of the observed losses, not the best value. GP acquisition functions, their regret guarantees (GP-UCB) and their limits in high dimension are developed in Bayesian Optimization (Neighbors, Kernels & SVMs topic).

Multi-fidelity: successive halving, Hyperband, population-based training

Most bad configurations reveal themselves early. Successive halving (Jamieson & Talwalkar, 2016, building on the sequential halving of Karnin, Koren & Somekh, 2013, for best-arm identification) starts nn configurations with a small budget rr each (epochs, say), keeps the best 1/η1/\eta of them, multiplies their budget by η\eta, and repeats until one is left. Each round costs about nrnr, so the total is about nr (1+log⁡ηn)nr\,(1+\log_\eta n) instead of nn full runs.

RungConfigurationsEpochs eachEpochs in rung
181181
227381
39981
432781
518181
Successive halving with n=81n=81, η=3\eta=3, r=1r=1 and a full budget of 81 epochs: 405 epochs in total, the cost of 5 full runs, to screen 81 configurations. Training all 81 to completion would take 6,561 epochs.

The catch is the choice of nn versus rr: many configurations with tiny budgets risk killing slow starters, few with large budgets waste effort on bad ones. Hyperband (Li, Jamieson, DeSalvo, Rostamizadeh & Talwalkar, 2018) hedges by running several brackets of successive halving that trade nn against rr; with a maximum of 81 epochs and η=3\eta=3 the brackets start (n,r)=(81,1),(34,3),(15,9),(8,27),(5,81)(n,r)=(81,1),(34,3),(15,9),(8,27),(5,81), the last being plain random search. BOHB (Falkner, Klein & Hutter, 2018) replaces Hyperband's random sampling with a TPE-style model, aiming at Hyperband's fast start and Bayesian optimization's strong final performance.

Population-based training (Jaderberg et al., 2017) trains a population in parallel; periodically, poor members copy the weights and hyperparameters of better ones (exploit) and perturb them (explore). The result is a schedule of hyperparameters rather than fixed values.

Check your understanding

Successive halving can discard the configuration that would have been best after full training. When is this most likely?

  1. When the validation set is large
  2. When early validation performance ranks configurations poorly, for example a low learning rate that starts slowly but finishes best
  3. When η\eta is small, such as 2
  4. When the number of configurations is a power of η\eta
Show the answer

B. When early validation performance ranks configurations poorly, for example a low learning rate that starts slowly but finishes best

Early stopping is safe only if low-fidelity results are correlated with final results. Configurations whose curves cross (slow starters, schedules with a late learning-rate drop) are exactly the ones a multi-fidelity method misjudges, which is why Hyperband also runs brackets with larger starting budgets.

Overfitting the validation set

The best validation score after a search is the minimum of many noisy estimates, so it is optimistic: by up to s2ln⁡Ms\sqrt{2\ln M} for MM configurations whose scores have noise ss, and by ss times the expected maximum of MM standard normals when the noise is independent and Gaussian (Cross-Validation: Theory & Pitfalls). With 1,000 configurations of equal quality and noise of half a point, the winner looks about 1.6 points better than it is. Searches that compare configurations on cheap, noisy, low-fidelity evaluations add further noise to that selection.

Tuning also confounds comparisons between methods. Melis, Dyer & Blunsom (2018) re-tuned several language-model architectures with large-scale black-box hyperparameter search and found that "standard LSTM architectures, when properly regularised, outperform more recent models." A new method tuned for weeks against a baseline tuned for an afternoon measures the tuning budget, not the method.

PracticeWhy
assess the final configuration on untouched data, or with nested cross-validationthe search's own best score is selection-biased
re-evaluate the top few configurations with more seeds or folds before choosingseparates real gains from lucky draws
give every compared method the same search space size and budget, and report themotherwise the comparison measures tuning effort
use random search as a baseline for any tunerit is simple, parallel and often hard to beat by much
Turner et al. (2021) analyzed the black-box optimization challenge held at NeurIPS 2020 and concluded, as their title says, that Bayesian optimization is superior to random search for machine-learning hyperparameter tuning; the size of the gain depends on the problem and the budget.

Key takeaways

  • Hyperparameter optimization is noisy, expensive, mostly gradient-free bilevel optimization; search scale parameters on a log scale and keep final assessment separate.
  • Random search beats grids under low effective dimensionality: B≥ln⁡(1/δ)/qB\ge\ln(1/\delta)/q trials hit the top fraction qq with probability 1−δ1-\delta, whatever the dimension.
  • Bayesian optimization fits a surrogate (GP, TPE or random forest) and maximizes an acquisition such as EI=(y⋆−μ)Φ(u)+sϕ(u)\mathrm{EI}=(y^\star-\mu)\Phi(u)+s\phi(u), which rewards both low predicted loss and uncertainty.
  • Successive halving starting at 1/n1/n of a full budget screens nn configurations for the cost of about 1+log⁡ηn1+\log_\eta n full runs, assuming early results rank configurations well; Hyperband hedges across brackets, BOHB adds a model, and population-based training learns schedules.
  • The best validation score after a search is optimistic, and unequal tuning budgets confound method comparisons; assess on untouched data.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

You have 16 trials and two hyperparameters, of which only one actually affects the validation loss. How many distinct values of the important one do a 4×44\times4 grid and 16 random trials test?

  1. Grid 16, random 16
  2. Grid 4, random 16
  3. Grid 4, random 4
  4. Grid 16, random 4
Show the answer

B. Grid 4, random 16

The grid repeats each of its 4 values of the important hyperparameter 4 times, varying only the irrelevant one. Random trials almost surely give 16 different values of each. That is Bergstra and Bengio's argument for random search under low effective dimensionality.

Question 2

In the expected-improvement formula (y⋆−μ)Φ(u)+sϕ(u)(y^\star-\mu)\Phi(u)+s\phi(u) (minimization), what happens to EI if a candidate's predicted mean stays the same but its predictive uncertainty ss grows?

  1. EI falls, because uncertain candidates are risky
  2. EI is unchanged, because it depends only on the mean
  3. EI grows, because ∂ EI/∂s=ϕ(u)>0\partial\,\mathrm{EI}/\partial s=\phi(u)>0
  4. EI becomes negative when the mean is worse than y⋆y^\star
Show the answer

C. EI grows, because ∂ EI/∂s=ϕ(u)>0\partial\,\mathrm{EI}/\partial s=\phi(u)>0

Improvement is (y⋆−f)+(y^\star-f)_+, a convex function of ff, so spreading the distribution of ff raises its expectation. That built-in reward for uncertainty is what makes EI explore.

Question 3

Why does Hyperband run several brackets of successive halving instead of one?

  1. To hedge between many configurations with small budgets and few with large budgets, since the right trade-off is unknown
  2. To average out the noise of a single bracket
  3. Because successive halving needs the number of configurations to be a power of η\eta
  4. To fit a Bayesian surrogate model across brackets
Show the answer

A. To hedge between many configurations with small budgets and few with large budgets, since the right trade-off is unknown

Aggressive brackets screen many configurations cheaply but may kill slow starters; conservative ones give fewer configurations more budget, down to plain random search. Running all of them costs only a logarithmic factor and protects against either failure mode.

Question 4

After 500 trials of Bayesian optimization, your best configuration scores 91.8% on the validation set. What should you report as its expected accuracy on new data?

  1. 91.8%, the measured value
  2. 91.8% plus a correction, since validation sets are pessimistic
  3. The average validation score of all 500 trials
  4. Its score on a test set (or outer cross-validation folds) that the search never used
Show the answer

D. Its score on a test set (or outer cross-validation folds) that the search never used

91.8% is the maximum of 500 noisy estimates and therefore biased upward. An independent assessment, used once, is the honest number.

Further reading

  • J. Bergstra & Y. Bengio, "Random search for hyper-parameter optimization," Journal of Machine Learning Research 13, 281–305 (2012).
  • J. Snoek, H. Larochelle & R. P. Adams, "Practical Bayesian optimization of machine learning algorithms," Advances in Neural Information Processing Systems 25 (2012).
  • L. Li, K. Jamieson, G. DeSalvo, A. Rostamizadeh & A. Talwalkar, "Hyperband: a novel bandit-based approach to hyperparameter optimization," Journal of Machine Learning Research 18(185), 1–52 (2018).
  • S. Falkner, A. Klein & F. Hutter, "BOHB: robust and efficient hyperparameter optimization at scale," Proceedings of the 35th International Conference on Machine Learning, PMLR 80, 1437–1446 (2018).
  • M. Feurer & F. Hutter, "Hyperparameter optimization," in F. Hutter, L. Kotthoff & J. Vanschoren (eds.), Automated Machine Learning: Methods, Systems, Challenges (Springer, 2019), 3–33.