AI Logic

Hyperparameter Optimization

Random Search

Updated:

A comparison of grid search and random search with 9 trials each. On the left, a 3×3 grid; on the right, 9 randomly chosen points. Above each plot is the performance g(x) for the important parameter x, and to the left is h(y) for the unimportant parameter y. The grid tries only 3 values of x and misses the peak, while random search tries 9 values of x and gets near the peak.

What Is Random Search?

Random search is a search method that tries hyperparameter values drawn independently at random from fixed ranges and picks the setting with the best validation performance. Bergstra and Bengio (2012) showed, both experimentally and theoretically, that for tuning neural network hyperparameters it is more efficient than the widely used grid search (trying every value on a grid).

It is more efficient because often only a few of the hyperparameters strongly affect the result. With a grid, many nearly identical trials line up that differ only in the values of hyperparameters that do not matter. With random choices, the values of the important hyperparameters also change on every trial, so the same number of trials covers that axis more densely (the figure at the top).

Random search is also used as a baseline when comparing more advanced search methods such as Bayesian optimization and Hyperband. The paper also positions random search as "a natural baseline against which to judge progress in the development of new search methods."

Procedure

The procedure of random search is as follows.

  1. Decide which hyperparameters to search, and the range and distribution of each. Values that span orders of magnitude, like the learning rate, are drawn uniformly in log space (the paper draws the learning rate log-uniformly from 0.001 to 10). Choices such as the type of layer are picked with equal probability.
  2. Decide the number of trials SS, based on the compute budget.
  3. Draw SS settings λ(1),…,λ(S)\lambda^{(1)}, \dots, \lambda^{(S)}, each independently at random.
  4. Train a model with each setting and measure its performance Ψ(λ)\Psi(\lambda) (such as validation error) on validation data.
  5. Return the best setting.

The paper formulates hyperparameter search as the problem of picking, among the tried settings, the one with the lowest validation error (Eq. (4)).

λ^=argmin⁡λ∈{λ(1),…,λ(S)}Ψ(λ)\hat{\lambda} = \operatorname*{argmin}_{\lambda \in \{\lambda^{(1)}, \dots, \lambda^{(S)}\}} \Psi(\lambda)

Grid search and random search differ only in how the set of settings {λ(1),…,λ(S)}\{\lambda^{(1)}, \dots, \lambda^{(S)}\} is chosen. Grid search fixes candidate values L(k)L^{(k)} for each of the KK hyperparameters and tries every combination, so the number of trials is:

S=∏k=1K∣L(k)∣S = \prod_{k=1}^{K} \left|L^{(k)}\right|

Each additional hyperparameter multiplies the number of trials (the curse of dimensionality). Random search lets you choose the number of trials SS freely, regardless of the number of hyperparameters.

In the paper's deep belief network (DBN) experiments, there were 32 hyperparameters to search. Even with only 2 values each, a grid would need 2322^{32} (about 4.3 billion) trials, which is impractical.

Why It Is More Efficient Than a Grid

The core of the paper's explanation is that the function mapping hyperparameters to performance has low effective dimensionality. For example, consider performance over two hyperparameters xx and yy given by f(x,y)=g(x)+h(y)≈g(x)f(x, y) = g(x) + h(y) \approx g(x), determined almost entirely by xx (the figure at the top).

  • 9 trials on a grid: a 3×3 grid has only 3 values of xx. The remaining 6 trials only change yy, which does not matter, and keep testing the same places on g(x)g(x).
  • 9 random trials: all 9 trials have different values of xx, so g(x)g(x) is examined at 9 places.

If you knew in advance which hyperparameters matter, you could build a grid that is fine only along those axes. But the paper analyzed the performance function with a Gaussian process and confirmed the following two points (Figure 7).

  • Only some hyperparameters matter: even for a neural network with 7 hyperparameters, the effective dimensionality was 1–4 depending on the dataset.
  • Which hyperparameters matter differs by dataset: the learning rate mattered on every dataset, but beyond that, on some datasets the time at which the learning rate starts to decay mattered, on others the strength of weight decay (L2 penalty), and on others the number of hidden units.

So it is hard to build in advance a grid that suits every problem, while random search achieves "the same efficiency as searching only the important dimensions" on every problem.

The number of trials needed can be estimated with probability. If the good region occupies a fraction v/Vv/V of the volume of the search range, the probability that at least one of TT random trials lands in it is (Section 4):

1−(1−vV)T1 - \left(1 - \frac{v}{V}\right)^{T}

If the good region is 1% of the whole, 100 trials land in it with about 63% probability and 300 trials with about 95%. If it is 5% of the whole, 60 trials give about 95%. This probability does not depend on the number of hyperparameters being searched.

As an analogy, when searching for a long, thin treasure buried somewhere in a field, digging on a grid means that rows parallel to the treasure keep missing no matter how much you dig. Digging at scattered spots gives more chances to cross the treasure's row with the same number of holes.

Experimental Results

The paper re-solved, with random search, the same problems that Larochelle et al. (2007) had tackled with grid search and manual tuning. It used 8 datasets, including variants of MNIST.

Compared againstHyperparameters searchedResult
Grid search (100 trials on average)7 of a neural network (no preprocessing)Random search found models as good as or better than grid search in 8 trials
Grid search (100 trials on average, no preprocessing)9 over a wide range including preprocessingRandom search consistently beat grid search with 32 trials, and also beat the narrow-range results with 64 or more
Manual tuning combined with a grid (41 trials on average)32 of a deep belief networkWith 128 random trials: worse on 3, equal on 4, better on 1 dataset (Figure 9)

In the wide range of the second row, many combinations of preprocessing types lead to poor performance, so more trials are needed to find a good model. Even so, the paper estimates that trying just 4 levels of the fraction of variance kept by PCA preprocessing on a grid would require 5× as many trials on average (about 500).

For the deep belief network in the third row, random search matched results tuned by humans drawing on experience on many datasets, but did not beat them on all of them.

The paper also compares against using "low-discrepancy sequences" such as the Sobol sequence instead of random numbers. In simulations, the Sobol sequence was only a few points better than random, Latin hypercube sampling was about the same as random, and the grid was the worst in most cases.

Caveats

Draw hyperparameters that span orders of magnitude in log space. If you draw the learning rate uniformly from 0.0001–0.1 as is, about 90% of draws fall in 0.01–0.1, and small values are barely tried. Draw the learning rate, the strength of weight decay, the number of units, and so on log-uniformly.

Random search does not use earlier results to choose the next trial. If the good region is very small, it may not be found even with more trials. When each training run is expensive and only a few trials are possible, also consider methods like Bayesian optimization that choose the next point from past results.

Also keep the following in mind.

  • Do not make the search range too wide: as in the paper's second-row experiment, a wide range with many bad settings takes more trials to reach a good model. The wider the range, the more trials you need.
  • Do not report the single best trial's score as the performance: with many trials, you may pick a setting that happened to do well on the validation data. The paper accounts for the uncertainty about which trial is truly best by reporting a weighted average of test performance (Section 2.1). Measure final performance on test data that was not used to choose the setting.
  • You can stop early or add trials later: since trials are independent, stopping at any time leaves a complete experiment, and trials can be added when more machines become available. Trials that fail partway can be discarded or rerun. With grid search, this is not possible without rebuilding the grid.
  • It is also useful for studying the effect of a single hyperparameter: the paper recommends setting all other hyperparameters by random search and using that same set for every value of the hyperparameter under study.

Comparison with Other Search Methods

The table compares random search with other commonly compared hyperparameter search methods from the same viewpoints.

MethodUses past results?Easy to parallelize?Best suited for
Grid searchNoEasy (the number of grid points is fixed)1–2 hyperparameters
Random searchNoVery easy (trials can be added anytime)Many machines; an initial rough search; a baseline for other methods
Bayesian optimizationYes (a surrogate model picks the next point)Needs extra workEach training run is expensive and only a few trials are possible
HyperbandStops runs early based on intermediate results (points chosen at random)EasyA few epochs give a rough idea of good and bad
BOHBYes (a model picks Hyperband's points)EasyWanting the strengths of both Hyperband and Bayesian optimization

Rough guidelines for choosing:

  • With 3 or more hyperparameters, use random search rather than grid search: the paper says grid search is reliable only in low dimensions (1–2).
  • If many machines can run many trials at once, start with random search: it is easy to implement, its independent trials parallelize easily, and its results are easy to reproduce.
  • If only a few trials are possible, or you want to stop runs early, move on to Bayesian optimization or Hyperband: even then, use the random search results as the baseline for comparison.

PyTorch example

Show code
python
import math
import random
import torch
import torch.nn as nn

torch.manual_seed(0)
X_train, y_train = torch.randn(1024, 20), torch.randint(0, 2, (1024,))
X_val, y_val = torch.randn(512, 20), torch.randint(0, 2, (512,))


def log_uniform(rng, low, high):
    """Sample uniformly in log space (for values spanning orders of magnitude)"""
    return math.exp(rng.uniform(math.log(low), math.log(high)))


def sample_config(rng):
    """Draw each setting of one trial independently at random"""
    return {
        "lr": log_uniform(rng, 1e-4, 1e-1),
        "weight_decay": log_uniform(rng, 1e-6, 1e-3),
        "hidden": round(log_uniform(rng, 16, 512)),            # Units are also drawn on a log scale, then rounded
        "activation": rng.choice(["relu", "tanh"]),            # Choices are picked with equal probability
    }


def train_and_validate(cfg):
    act = nn.ReLU() if cfg["activation"] == "relu" else nn.Tanh()
    model = nn.Sequential(nn.Linear(20, cfg["hidden"]), act, nn.Linear(cfg["hidden"], 2))
    opt = torch.optim.SGD(model.parameters(), lr=cfg["lr"], momentum=0.9, weight_decay=cfg["weight_decay"])
    loss_fn = nn.CrossEntropyLoss()
    model.train()
    for _ in range(100):
        opt.zero_grad()
        loss_fn(model(X_train), y_train).backward()
        opt.step()
    model.eval()                                               # Switch to eval mode for validation
    with torch.no_grad():
        return loss_fn(model(X_val), y_val).item()             # Ψ(λ): validation loss


rng = random.Random(42)
S = 30                                                         # Number of trials (set by the compute budget)
results = []
for s in range(S):
    cfg = sample_config(rng)                                   # Trials are independent → can run in parallel
    results.append((train_and_validate(cfg), cfg))
best_loss, best_cfg = min(results, key=lambda r: r[0])         # Eq. (4): the setting with the lowest validation loss
print(best_loss, best_cfg)

FAQ

Q. How many trials should I run?
A.

It depends on what fraction of the search range the good region occupies. If the good region is 5% of the whole, 60 trials land in it at least once with about 95% probability (1−0.9560≈0.951 - 0.95^{60} \approx 0.95). In the paper's experiments, random search beat grid search with 8 trials in a narrow range and with 32–64 trials in a wide range.

Q. Are there cases where grid search is better?
A.

With only 1–2 hyperparameters to search, a grid can examine them finely enough and covers every combination without gaps. The paper also says grid search is reliable in low dimensions (1–2). With 3 or more, random search searches more efficiently.

Q. Can it be used with tools such as Optuna?
A.

Yes. Optuna has RandomSampler; specifying it instead of the default TPE gives random search. Bayesian optimization–style methods such as TPE also pick points at random for the first several trials before they start using past results.

References

  1. J. Bergstra and Y. Bengio, "Random Search for Hyper-Parameter Optimization," Journal of Machine Learning Research, vol. 13, pp. 281–305, 2012.
  2. H. Larochelle, D. Erhan, A. Courville, J. Bergstra, and Y. Bengio, "An Empirical Evaluation of Deep Architectures on Problems with Many Factors of Variation," ICML, 2007.