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.
- 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.
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 , batch size , weight decay coefficient , dropout rate , 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 where is a hyperparameter configuration drawn from a configuration space (a product of intervals, discrete sets, and categorical choices), and is the validation score obtained by training a model with configuration 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 , 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 — 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 (e.g., log-uniform for learning rate) and evaluates a fixed number of them. Bayesian optimization maintains a probabilistic surrogate model of , 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 has candidate values, the total number of trials is — 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 trials, where 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 , using all pairs observed so far. After fitting the GP, every untried point has a predicted mean and standard deviation (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 , high ) or highly uncertain (exploration, high ). 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 , is
with the standard normal CDF and PDF, and 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.
Complexity & correctness
Grid search complexity. With hyperparameters and candidate values for the -th, the number of trials is , and total cost is , where is the cost of one training-and-evaluation run. This is exponential in for fixed : . Memory cost is to store all scores, or 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 further.
Random search complexity. With a fixed trial budget chosen independent of , total cost is — no exponential dependence on dimension. The correctness argument for why random search is competitive rests on effective dimensionality: suppose only of the hyperparameters materially affect . A grid with levels per axis places only distinct values along any single important axis, no matter how large is, because the grid is a rigid product structure. A random sample of points, by contrast, has distinct values (with probability 1, for continuous distributions) projected onto every axis independently. So for the same total budget trials, grid search tries only values of the important axis, while random search with trials tries values of that axis — a search that is a factor of 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 observed points, which costs for the Cholesky factorization used in exact GP inference (inverting the kernel covariance matrix), plus per prediction query. Over total iterations this GP-fitting overhead is in the worst case (summing over ), which becomes the bottleneck only when is large (hundreds to low thousands) or when is small enough that the surrogate overhead is comparable to actual training cost — in deep learning, (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 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.
| Method | Sample efficiency | Parallelizability | Assumptions | Weakness |
|---|---|---|---|---|
| Grid | Low (wastes budget on unimportant axes) | Perfect (trials independent) | None | Exponential blow-up in |
| Random | Medium | Perfect (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 , kernel choice | overhead, weak in , hard to parallelize |
Worked example
Consider tuning two hyperparameters for an image classifier: learning rate (searched on a log scale) and weight decay (also log scale). Suppose the true validation accuracy surface has a narrow ridge of good performance around , largely insensitive to across two orders of magnitude — a realistic effective-dimensionality-1 situation.
Grid search, budget (3 × 3 grid): , . Only three distinct values are ever tried; none lands near , so the best grid point may sit at by luck, achieving 91.2% validation accuracy — the near-hit is coincidence, not guarantee.
Random search, budget , sampled log-uniformly on both axes:
| Trial | Val. accuracy | ||
|---|---|---|---|
| 1 | 78.4% | ||
| 2 | 93.6% | ||
| 3 | 61.0% | ||
| 4 | 90.7% | ||
| 5 | 84.1% | ||
| 6 | 93.9% | ||
| 7 | 65.2% | ||
| 8 | 89.5% | ||
| 9 | 82.3% |
Nine distinct 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 -values tried near the optimum was higher, exactly as the complexity argument predicts.
Bayesian optimization, budget with 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 and EI concentrates subsequent trials there. By trial 9, Bayesian optimization typically converges to , , 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
| Pitfall | Why it happens | Consequence |
|---|---|---|
| Tuning against the test set | Using test accuracy to pick the best config | Inflated, non-reproducible reported performance |
| Uniform (not log-uniform) sampling for learning rate | Treating as linear | Search wastes almost all trials at large, unstable learning rates |
| Ignoring interaction between batch size and learning rate | Tuning each axis independently, one at a time | Misses configurations where both must move together (linear scaling rule) |
| No fixed compute budget per trial | Letting some trials train far longer than others | Comparisons are unfair; expensive configs look artificially better |
| Reusing the same validation split across many trials | Small validation set, hundreds of trials | Overfitting the validation set itself ("meta-overfitting") |
| Restarting the GP surrogate from scratch, discarding prior runs | Treating each tuning session as independent | Wastes 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
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 , 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 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.