Hyperparameter Tuning

A researcher trains a convolutional network overnight. It gets stuck at 40% accuracy. Swapping the learning rate from 0.1 to 0.001 fixes everything in the morning. Nothing about the architecture changed. Only a single scalar chosen before training began. This is the central fact that makes hyperparameter tuning unavoidable in deep learning. The difference between a broken model and a state-of-the-art one is often small. It often comes down to a handful of numbers set outside the learning process. Hyperparameters — learning rate, batch size, weight decay, dropout probability, number of layers, momentum — are not learned by gradient descent. They are chosen by the practitioner (or by an outer search algorithm). This happens before or alongside training. They shape the entire loss landscape that the optimizer will explore. Get them wrong and even a perfect architecture underperforms. Get them right and a mediocre architecture can rival a fancier one. Deep networks are expensive to train. The hyperparameter space is high-dimensional and non-convex. So blind trial-and-error does not scale. Production teams need principled search strategies. These strategies must find good configurations under a fixed compute budget. This article treats hyperparameter tuning as a search problem. The problem is over a black-box, expensive-to-evaluate function. Given a configuration, train the network and return a validation score. We cover three families of search strategies. These are grid search, random search, and Bayesian optimization. We build from the simplest exhaustive method to a model-based approach. This approach reasons about the function it is optimizing. We connect this to the mechanics you already know. Adam and Its Variants supplies the inner optimizer. Early Stopping and Debugging the Training Process supply the tools. These tools make each evaluation cheaper and catch failures early. This way, the outer search wastes less compute. By the end, you will understand several key ideas. You will see why random search beats grid search in high dimensions. You will see how a Gaussian process turns scattered trials into a posterior belief about the loss surface. You will also see how an acquisition function decides where to sample next. This sets up later material on Transfer Learning and Fine-Tuning. There, tuning often means adapting a small number of hyperparameters. This is done around an already-pretrained backbone, rather than searching from scratch.

Key takeaways
  • Hyperparameters (learning rate, batch size, regularization strength, architecture width) are set outside gradient descent and must be tuned by an outer search loop.
  • Grid search is exhaustive and simple but scales exponentially with the number of hyperparameters and wastes trials on unimportant dimensions.
  • Random search matches or beats grid search at the same budget because it samples every dimension densely, not just a coarse product grid.
  • Bayesian optimization builds a probabilistic surrogate model (typically a Gaussian process) of the validation score and uses an acquisition function to pick the next configuration intelligently.
  • Early stopping and cheap proxy evaluations (small budgets, sub-epoch checkpoints) make each search trial affordable, which is essential since deep network training is expensive.
  • No search method is free: grid search needs no assumptions but wastes compute; random search is simple but ignores learned structure; Bayesian optimization is sample-efficient but adds overhead and struggles with very high dimensions.
The core insight

Hyperparameter tuning is black-box optimization over an expensive function — training a network — so the right search strategy trades exploration cost against the value of the information each trial provides.

The idea

A hyperparameter is any configuration value fixed before the learning algorithm runs, as opposed to a parameter (weights, biases) updated by gradient descent inside training. Common hyperparameters include the learning rate η\eta, batch size BB, weight decay coefficient λ\lambda, dropout rate pp, number of layers, and momentum coefficients in optimizers like Adam. Hyperparameter tuning is the process of choosing values for these variables to optimize a held-out validation metric — typically validation loss or accuracy, never the test set, since tuning against the test set silently leaks information and inflates reported performance. Formally, tuning is optimization of a function f(θ)f(\theta) where θ∈Θ\theta \in \Theta is a hyperparameter configuration drawn from a configuration space Θ\Theta (a product of intervals, discrete sets, and categorical choices), and f(θ)f(\theta) is the validation score obtained by training a model with configuration θ\theta until convergence (or a fixed budget) and evaluating it. This function is a black box: it has no closed form, no accessible gradient with respect to θ\theta, and each evaluation costs minutes to days of compute. This is fundamentally different from the inner optimization problem (minimizing training loss over network weights), which does have gradients and is solved with methods like Adam and Its Variants. The outer problem — search over Θ\Theta — is what this article addresses. Three strategies dominate practice. Grid search discretizes each hyperparameter into a fixed set of values and evaluates every combination in the Cartesian product. Random search samples configurations independently from a specified distribution over Θ\Theta (e.g., log-uniform for learning rate) and evaluates a fixed number of them. Bayesian optimization maintains a probabilistic surrogate model of ff, fits it to all trials observed so far, and uses an acquisition function to choose the next point that best balances exploring uncertain regions against exploiting regions known to be good. Understanding why the third approach dominates in sample efficiency — and why the second dominates the first — requires understanding how information behaves across dimensions of unequal importance, developed next.

How it works

Grid search proceeds by discretizing each hyperparameter axis and enumerating the full product. If hyperparameter ii has kik_i candidate values, the total number of trials is ∏iki\prod_i k_i — exponential in the number of hyperparameters. ``` GRID-SEARCH(grids[1..d], train_and_eval):

# grids[i] is a list of k_i candidate values for hyperparameter i best_score := -infinity best_config := null for config in CARTESIAN-PRODUCT(grids[1], ..., grids[d]): score := train_and_eval(config) # trains model, returns validation score if score > best_score: best_score := score best_config := config return best_config, best_score ```

Random search instead samples each configuration independently from a chosen distribution per axis (uniform, log-uniform, categorical) and evaluates a budget of TT trials, where TT is chosen in advance based on available compute — no exponential blow-up with dimension. ``` RANDOM-SEARCH(distributions[1..d], train_and_eval, T): best_score := -infinity best_config := null for t := 1 to T: config := [SAMPLE(distributions[i]) for i in 1..d] score := train_and_eval(config) if score > best_score: best_score := score best_config := config return best_config, best_score ``` The key reason random search is preferred to grid search at equal budget: in high dimensions, most objective functions are dominated by a small number of important hyperparameters (the effective dimensionality is low). Grid search wastes evaluations by repeating the same values along unimportant axes; random search, by contrast, produces a distinct value on every axis for every trial, so it explores the important axes far more densely for the same total budget. This is a geometric fact about projections of a grid versus a random sample onto a low-dimensional subspace, illustrated below.

Bayesian optimization replaces blind sampling with a model-guided search. It maintains a surrogate model — most commonly a Gaussian process (GP) — over the unknown function f(θ)f(\theta), using all (θt,f(θt))(\theta_t, f(\theta_t)) pairs observed so far. After fitting the GP, every untried point θ\theta has a predicted mean μ(θ)\mu(\theta) and standard deviation σ(θ)\sigma(\theta) (a posterior belief, not a point estimate). An acquisition function, such as Expected Improvement (EI), converts this belief into a score that favors points that are either likely to beat the current best (exploitation, low σ\sigma, high μ\mu) or highly uncertain (exploration, high σ\sigma). The next trial is chosen by maximizing the acquisition function — a cheap optimization over the surrogate, not over the real expensive objective. ``` BAYES-OPT(objective_space, train_and_eval, T, n_init): D := {} # observed (config, score) pairs for t := 1 to n_init: config := RANDOM-SAMPLE(objective_space) # warm-start with random trials score := train_and_eval(config) D := D union {(config, score)} for t := n_init+1 to T: GP := FIT-GAUSSIAN-PROCESS(D) # posterior mean mu(.), std sigma(.) f_best := max(score for (_, score) in D) config := argmax over config in objective_space of EXPECTED-IMPROVEMENT(GP, config, f_best) score := train_and_eval(config) D := D union {(config*, score)} return argmax (config, score) in D of score ``` where the Expected Improvement acquisition function, in closed form for a GP posterior N(μ(θ),σ(θ)2)\mathcal{N}(\mu(\theta), \sigma(\theta)^2), is

EI(θ)=σ(θ)[z Φ(z)+ϕ(z)],z=μ(θ)−fbest−ξσ(θ)\mathrm{EI}(\theta) = \sigma(\theta)\left[z \,\Phi(z) + \phi(z)\right], \qquad z = \frac{\mu(\theta) - f_{\text{best}} - \xi}{\sigma(\theta)}

with Φ,ϕ\Phi, \phi the standard normal CDF and PDF, and ξ≥0\xi \ge 0 a small exploration margin. Intuitively: EI is large where the predicted mean is high (good exploitation candidate) or the uncertainty is large (good exploration candidate), and exactly zero where the GP is certain the point is worse than the current best.

Figure
Grid vs. random search: projection onto the important axis
Grid search (3×3) Random search (9 pts) unimportant axis (batch size) important axis (learning rate) only 3 distinct learning rates tried unimportant axis (batch size) 9 distinct learning rates tried

Complexity & correctness

Grid search complexity. With dd hyperparameters and kik_i candidate values for the ii-th, the number of trials is N=∏i=1dkiN = \prod_{i=1}^{d} k_i, and total cost is N⋅CtrainN \cdot C_{\text{train}}, where CtrainC_{\text{train}} is the cost of one training-and-evaluation run. This is exponential in dd for fixed ki=kk_i = k: N=kdN = k^d. Memory cost is O(N)O(N) to store all scores, or O(1)O(1) streaming if only the best is kept. Grid search is exhaustive over the specified grid, so within the discretization it is guaranteed to find the best grid point — but the discretization itself may miss the true optimum, and refining the grid to reduce that error multiplies NN further.

Random search complexity. With a fixed trial budget TT chosen independent of dd, total cost is T⋅CtrainT \cdot C_{\text{train}} — no exponential dependence on dimension. The correctness argument for why random search is competitive rests on effective dimensionality: suppose only deff≪dd_{\text{eff}} \ll d of the hyperparameters materially affect ff. A grid with kk levels per axis places only kk distinct values along any single important axis, no matter how large dd is, because the grid is a rigid product structure. A random sample of TT points, by contrast, has TT distinct values (with probability 1, for continuous distributions) projected onto every axis independently. So for the same total budget N=kdN = k^d trials, grid search tries only kk values of the important axis, while random search with T=kdT = k^d trials tries kdk^d values of that axis — a search that is a factor of kd−1k^{d-1} denser along the direction that matters. This is why Bergstra and Bengio's foundational empirical and theoretical analysis showed random search reliably outperforms grid search at equal budget whenever the effective dimensionality is low, which is typical for deep network hyperparameters (learning rate and one or two regularization terms usually dominate; exact batch size or momentum decay often barely matter within a wide range).

Bayesian optimization complexity. Each iteration fits a GP to tt observed points, which costs O(t3)O(t^3) for the Cholesky factorization used in exact GP inference (inverting the t×tt \times t kernel covariance matrix), plus O(t2)O(t^2) per prediction query. Over TT total iterations this GP-fitting overhead is O(T4)O(T^4) in the worst case (summing t3t^3 over t=1,…,Tt=1,\ldots,T), which becomes the bottleneck only when TT is large (hundreds to low thousands) or when CtrainC_{\text{train}} is small enough that the surrogate overhead is comparable to actual training cost — in deep learning, CtrainC_{\text{train}} (hours of GPU time) almost always dominates this polynomial surrogate cost, which is exactly the regime where Bayesian optimization pays off. The correctness/efficiency argument: EI provably never assigns positive value to a point that is worse than the current best with the GP's own certainty, and it is bounded below by exploitation (it never fully ignores promising regions) while remaining unbounded above wherever uncertainty is large (it never fully stops exploring). Formally, EI is the posterior expectation of the improvement random variable I(θ)=max⁡(0,f(θ)−fbest)I(\theta) = \max(0, f(\theta) - f_{\text{best}}) under the GP, so maximizing it is the Bayes-optimal single-step (myopic) choice given the model — it is not globally optimal over the whole search horizon (that would require solving a much harder sequential decision problem), which is the honest caveat: BO greedily optimizes expected one-step gain, not long-run regret.

Tradeoffs, honestly stated.

MethodSample efficiencyParallelizabilityAssumptionsWeakness
GridLow (wastes budget on unimportant axes)Perfect (trials independent)NoneExponential blow-up in dd
RandomMediumPerfect (trials independent)None (distribution choice matters)No learning across trials
Bayesian (GP)High (fewest trials to good result)Poor (each choice depends on all previous)Smoothness of ff, kernel choiceO(t3)O(t^3) overhead, weak in d≳20d \gtrsim 20, hard to parallelize

Worked example

Consider tuning two hyperparameters for an image classifier: learning rate η∈[10−4,10−1]\eta \in [10^{-4}, 10^{-1}] (searched on a log scale) and weight decay λ∈[10−5,10−1]\lambda \in [10^{-5}, 10^{-1}] (also log scale). Suppose the true validation accuracy surface has a narrow ridge of good performance around η≈3×10−3\eta \approx 3\times10^{-3}, largely insensitive to λ\lambda across two orders of magnitude — a realistic effective-dimensionality-1 situation.

Grid search, budget N=9N = 9 (3 × 3 grid): η∈{10−4,10−2.5,10−1}\eta \in \{10^{-4}, 10^{-2.5}, 10^{-1}\}, λ∈{10−5,10−3,10−1}\lambda \in \{10^{-5}, 10^{-3}, 10^{-1}\}. Only three distinct η\eta values are ever tried; none lands near 3×10−33\times10^{-3}, so the best grid point may sit at η=10−2.5≈3.2×10−3\eta = 10^{-2.5} \approx 3.2\times10^{-3} by luck, achieving 91.2% validation accuracy — the near-hit is coincidence, not guarantee.

Random search, budget T=9T = 9, sampled log-uniformly on both axes:

Trialη\etaλ\lambdaVal. accuracy
14.1×10−44.1\times10^{-4}2.0×10−32.0\times10^{-3}78.4%
22.8×10−32.8\times10^{-3}6.0×10−56.0\times10^{-5}93.6%
36.7×10−26.7\times10^{-2}1.1×10−21.1\times10^{-2}61.0%
41.5×10−31.5\times10^{-3}4.4×10−44.4\times10^{-4}90.7%
59.3×10−39.3\times10^{-3}7.7×10−37.7\times10^{-3}84.1%
63.3×10−33.3\times10^{-3}1.2×10−41.2\times10^{-4}93.9%
71.2×10−41.2\times10^{-4}3.9×10−23.9\times10^{-2}65.2%
85.5×10−35.5\times10^{-3}8.8×10−58.8\times10^{-5}89.5%
98.0×10−48.0\times10^{-4}2.5×10−32.5\times10^{-3}82.3%

Nine distinct η\eta values were sampled, two of them (trials 2 and 6) land close to the true ridge, and the best result (93.9%) beats grid search's coincidental near-hit — because the density of η\eta-values tried near the optimum was higher, exactly as the complexity argument predicts.

Bayesian optimization, budget T=9T = 9 with ninit=3n_{\text{init}} = 3 random warm-start trials, then GP-guided: after the first 3 random trials establish rough structure (say accuracies of 78%, 84%, 65% at scattered points), the GP posterior mean rises steeply near η≈3×10−3\eta \approx 3\times10^{-3} and EI concentrates subsequent trials there. By trial 9, Bayesian optimization typically converges to η≈3.1×10−3\eta \approx 3.1\times10^{-3}, λ≈1.5×10−4\lambda \approx 1.5\times10^{-4}, achieving 94.3% — extracting slightly more signal from the same nine-trial budget by using earlier results to inform later choices, at the cost of having to fit and query a GP after every trial and losing the ability to launch all 9 trials in parallel.

Common pitfalls & traps

PitfallWhy it happensConsequence
Tuning against the test setUsing test accuracy to pick the best configInflated, non-reproducible reported performance
Uniform (not log-uniform) sampling for learning rateTreating η∈[10−4,10−1]\eta \in [10^{-4}, 10^{-1}] as linearSearch wastes almost all trials at large, unstable learning rates
Ignoring interaction between batch size and learning rateTuning each axis independently, one at a timeMisses configurations where both must move together (linear scaling rule)
No fixed compute budget per trialLetting some trials train far longer than othersComparisons are unfair; expensive configs look artificially better
Reusing the same validation split across many trialsSmall validation set, hundreds of trialsOverfitting the validation set itself ("meta-overfitting")
Restarting the GP surrogate from scratch, discarding prior runsTreating each tuning session as independentWastes information; slower convergence in Bayesian optimization

Pioneers & history

Hyperparameter search connects two distinct lineages: classical statistical experiment design (grid and factorial designs date to Fisher's agricultural field trials) and Bayesian decision theory applied to machine learning model selection, popularized as computational budgets made naive grid search infeasible for deep networks.

Origins · 1 minJames Bergstra and how this was discovered
JB
James Bergstra
b. 1981 · Machine learning researcher who, with Yoshua Bengio, published the influential 2012 analysis proving random search dominates grid search at equal budget when effective dimensionality is low, reshaping standard practice for tuning deep networks

History
1951
Box and Wilson formalize response-surface methodology for experimental optimization.
1978
Mockus develops the Bayesian approach to global optimization with expected improvement.
1998
Jones, Schonlau, and Welch popularize Efficient Global Optimization (EGO) using Gaussian processes.
2012
Bergstra and Bengio show random search outperforms grid search for hyperparameter optimization.
2015
Snoek, Larochelle, and Adams (Spearmint) and later Hyperband/BOHB bring practical, scalable Bayesian and bandit-based tuning to deep learning pipelines.

Where this matters

Hyperparameter tuning underlies nearly every production deep learning pipeline. Cloud ML platforms (Google Vertex AI, Amazon SageMaker Automatic Model Tuning, Azure ML) expose Bayesian optimization as a managed service specifically for learning rate, regularization, and architecture search. Open-source libraries — Optuna, Ray Tune, Hyperopt, and scikit-optimize — implement random search, tree-structured Parzen estimators, and GP-based Bayesian optimization as interchangeable backends behind a common search API. Large-scale neural architecture search systems combine Bayesian optimization with bandit-based early stopping (Hyperband, BOHB) to prune bad configurations early, saving enormous compute at data-center scale. Recommendation systems, speech models, and vision transformers trained by major labs all report the specific learning-rate schedule, warmup length, and weight decay found via exactly this kind of outer search — the tuning step is often the difference between a paper's headline result and an unremarkable baseline. It also directly foreshadows Transfer Learning and Fine-Tuning, where the search space shrinks (often to just a learning rate and number of unfrozen layers) but the same search machinery — random or Bayesian — is reused around a pretrained backbone.

Ask the tutor: How would you design a hyperparameter search strategy under a strict fixed compute budget when some configurations are far more expensive to train than others?

Why can't we just use gradient descent to tune hyperparameters directly, the same way we tune weights?

Some hyperparameters (like weight decay strength) do have well-defined gradients with respect to validation loss in principle, and gradient-based hyperparameter optimization exists as a research area. But most practical hyperparameters are non-differentiable with respect to the validation metric as usually computed: batch size and number of layers are discrete, and computing an exact gradient of validation loss with respect to the learning rate would require differentiating through the entire multi-step training trajectory, which is expensive, numerically unstable, and only gives a local gradient rather than global information about the loss surface. Black-box search methods avoid this by treating each full training run as a single, opaque function evaluation, at the cost of needing many such evaluations.

How many trials does Bayesian optimization typically need to beat random search in practice?

It depends heavily on the dimensionality and smoothness of the search space, but empirically Bayesian optimization tends to show its advantage after the first 5–15 trials, once the surrogate model has enough data to form a meaningful posterior — before that, it is essentially doing warm-start random search anyway. In low dimensions (2–5 hyperparameters), Bayesian optimization can reach a given validation accuracy with roughly half to a third of the trials random search needs. In high dimensions (dozens of hyperparameters), the GP surrogate's own fitting difficulty grows, and the gap narrows or can even reverse, which is why practitioners often restrict Bayesian optimization to the handful of hyperparameters known to matter most.

What is Hyperband, and how does it relate to grid, random, and Bayesian search?

Hyperband is a bandit-based method that allocates compute adaptively rather than searching configurations alone: it launches many configurations (often sampled randomly) with a small budget, evaluates them, discards the worst performers early, and reallocates the saved compute to the survivors for a longer run. It is orthogonal to how configurations are chosen — it can wrap random search or feed candidate selection into a Bayesian model, as in BOHB (Bayesian Optimization with Hyperband). The key insight it exploits is that most bad configurations reveal themselves as bad within a fraction of full training time, so early stopping of unpromising trials (much like Early Stopping within a single run) saves enormous compute across an entire search.

Does the choice of validation set size affect which tuning method I should use?

Yes, indirectly. A small validation set produces a noisy estimate of f(θ)f(\theta), and Bayesian optimization's Gaussian process assumes (or must explicitly model) observation noise; ignoring it causes the surrogate to overfit to noise and chase spurious peaks. With a small or noisy validation set, either use a GP with an explicit noise term, average over several validation folds per trial, or fall back to random search, which is more robust to noisy evaluations because it does not build cumulative trust in any single point's exact value. Larger, more reliable validation sets make the smoothness assumptions behind Bayesian optimization more trustworthy.

Can hyperparameter tuning be combined with early stopping to reduce cost per trial?

Yes, and in practice this is one of the most important cost-saving techniques. Rather than training every candidate configuration to full convergence, each trial can be run with the same early-stopping criterion used in normal training (monitoring validation loss plateau), so bad configurations are killed off after a few epochs instead of running to completion. This shrinks CtrainC_{\text{train}} per trial substantially and lets the search allocate its budget toward more configurations rather than fewer, fully-trained ones — the tradeoff being that partial training curves can sometimes mis-rank configurations whose validation loss improves slowly but eventually surpasses early leaders.

How does hyperparameter search change when fine-tuning a pretrained model instead of training from scratch?

The search space typically shrinks dramatically: instead of tuning architecture depth, initialization scheme, and a wide learning-rate range, fine-tuning usually only needs a small learning rate (often 10–100× smaller than from-scratch training), a choice of how many layers to unfreeze, and light regularization to prevent catastrophic forgetting. Because each fine-tuning run is often cheaper than training from scratch, more trials become affordable within the same budget, and simple random search over this narrow space is frequently sufficient — Bayesian optimization's extra sample efficiency matters less when trials are already cheap. This narrowed, cheaper search is a central practical theme in Transfer Learning and Fine-Tuning.

Before this

Where this leads