Bayesian optimization is a search method that builds a model (a surrogate model) from the results tried so far to predict which hyperparameters are likely to give a good validation error, and uses it to choose the next value to try. Each trial of a hyperparameter such as the learning rate or the number of layers costs one full training run of the model. Bayesian optimization is used for this kind of problem, where a single evaluation is expensive, to keep the number of trials as small as possible.
Grid search and random search fix the points to try in advance or pick them at random, so they do not use earlier results to choose the next one. Bayesian optimization uses all past results to choose the next point, much like a treasure hunter deciding where to dig next based on what the previous holes turned up.
The idea is old, but in 2012 Snoek et al. laid out a practical way to use it for tuning machine learning hyperparameters (NIPS 2012). In the paper, they searched 9 hyperparameters of a convolutional network on CIFAR-10 and reached a test error of 14.98%, more than 3 points better than an expert-tuned setting (18% test error).
Theory (The Iterative Procedure)
Bayesian optimization repeats the following steps. Here, the goal is to find the hyperparameter x that minimizes the validation error f(x).
First, choose a few points, for example at random, try them, and measure the validation error.
Fit the surrogate model: from the results at the tried points, predict the validation error at untried points x. The surrogate model is usually a Gaussian process, which gives both the predicted mean μ(x) and the prediction uncertainty (standard deviation) σ(x). σ(x) is small near tried points and large far from them.
Pick the point that maximizes the acquisition function: compute the acquisition function a(x), which expresses "how worthwhile it is to try that point next," and choose the maximizer xnext=argmaxxa(x). Computing the acquisition function is far cheaper than training, so it can be searched finely.
Train the model with the chosen xnext and measure the validation error.
Add the result and return to step 2. After a fixed number of iterations N, return the best point found.
The acquisition function Snoek et al. used is expected improvement (EI) (Eq. (2) in the paper).
Here, f(xbest) is the best validation error so far, and Φ and ϕ are the cumulative distribution function and probability density function of the standard normal distribution. EI is the expected amount by which a point improves on the current best, and it is large at two kinds of points:
Points where the predicted mean μ(x) is low: it refines the area near places already known to be good (exploitation).
Points where the uncertainty σ(x) is high: it examines places not yet tried (exploration).
In the lower right of the figure at the top, EI peaks around x≈0.47, between tried points, where the mean is low and the uncertainty is also large. On the tried points themselves, σ(x) is nearly 0, so EI is nearly 0 as well.
Other acquisition functions include PI (Probability of Improvement), which uses the probability of beating the current best, and GP-UCB, which uses μ(x)−κσ(x) (the lower confidence bound when minimizing). The paper chooses EI because it behaves more stably than PI and, unlike GP-UCB, has no parameter κ to tune.
Practical Improvements by Snoek et al.
Snoek et al. added the following improvements to make Bayesian optimization practical for tuning machine learning hyperparameters.
Use the ARD Matérn 5/2 kernel for the Gaussian process: the commonly used squared exponential kernel assumes the function is overly smooth. Matérn 5/2 assumes the function is twice differentiable and learns a separate influence (length scale) for each hyperparameter (ARD).
Average over the Gaussian process hyperparameters: instead of fixing kernel hyperparameters such as the length scales to single values, it draws several values from their posterior by slice sampling and averages the EI computed with each (the integrated acquisition function, Eq. (6)). This reduces failures caused by committing too early while only a few points have been tried.
Use expected improvement per second: training time varies widely with the hyperparameters. Predicting the training time with a Gaussian process as well, and choosing by EI divided by the predicted time, makes it easier to find good points in a short time.
Run trials in parallel: when several machines run trials at once, the results of points still pending are filled in by Monte Carlo sampling from the Gaussian process before computing EI. This avoids wasting effort on trying similar points at the same time.
Values that span orders of magnitude (such as 0.0001 to 0.1), like the learning rate and weight decay, are searched in log space. The horizontal axis of the figure at the top also assumes the log of the learning rate rescaled to 0–1. Searching on a linear scale spends almost all trials in the 0.01–0.1 range and barely explores small values.
Comparison with Other Search Methods
The table compares Bayesian optimization with other commonly compared hyperparameter search methods from the same viewpoints.
Method
Uses past results?
Easy to parallelize?
Best suited for
Random search
No
Very easy
Many machines; an initial rough search
Bayesian optimization
Yes (a surrogate model picks the next point)
Needs extra work
Each training run is expensive and only a few trials are possible
Many machines, and hyperparameters may change during training
Rough guidelines for choosing:
If one training run takes hours and only a few dozen trials are possible, use Bayesian optimization.
If intermediate results reveal good and bad settings, use Hyperband or BOHB to stop bad settings early.
Caveats
Bayesian optimization with a Gaussian process struggles with problems that have many hyperparameters to search or many categorical values. As the number of dimensions grows, the number of points needed to cover the space grows rapidly. The computational cost of a Gaussian process also grows with the cube of the number of tried points N. Such problems use methods with other surrogate models, such as the Tree-structured Parzen Estimator (TPE) (Optuna's default sampler is TPE).
Also keep the following in mind.
Watch for noise in the validation error: even with the same hyperparameters, results vary with the random seed. When the noise is large, the surrogate model gets pulled toward lucky results. Use a model that accounts for observation noise, or retry promising settings several times.
Do not make the search range too wide: Bayesian optimization finds good points inside the range and does not look outside it. On the other hand, an overly wide range wastes trials. Set a reasonable range from experience or published settings.
PyTorch example
▶Show code
python
import math
import torch
import torch.nn as nn
# Example of 1-D Bayesian optimization (over the log learning rate) with a Gaussian process and expected improvement (EI)
torch.manual_seed(0)
X_train, y_train = torch.randn(512, 20), torch.randint(0, 2, (512,))
X_val, y_val = torch.randn(256, 20), torch.randint(0, 2, (256,))
def objective(u: float) -> float:
"""u is in [0, 1]. Trains a small model with learning rate 10^(−4 + 3u) (0.0001 to 0.1) and returns the validation loss"""
lr = 10 ** (-4 + 3 * u)
model = nn.Sequential(nn.Linear(20, 64), nn.ReLU(), nn.Linear(64, 2))
opt = torch.optim.SGD(model.parameters(), lr=lr)
loss_fn = nn.CrossEntropyLoss()
for _ in range(200):
opt.zero_grad()
loss_fn(model(X_train), y_train).backward()
opt.step()
with torch.no_grad():
return loss_fn(model(X_val), y_val).item()
def matern52(a, b, length=0.2, amp=1.0):
r = (a[:, None] - b[None, :]).abs() / length
return amp * (1 + math.sqrt(5) * r + 5.0 / 3.0 * r ** 2) * torch.exp(-math.sqrt(5) * r)
def gp_posterior(x_obs, y_obs, x, noise=1e-4):
mean = y_obs.mean()
K = matern52(x_obs, x_obs) + noise * torch.eye(len(x_obs))
L = torch.linalg.cholesky(K)
k_s = matern52(x_obs, x)
alpha = torch.cholesky_solve((y_obs - mean)[:, None], L)
mu = mean + (k_s.T @ alpha).squeeze(1)
v = torch.linalg.solve_triangular(L, k_s, upper=False)
var = (matern52(x, x).diagonal() - (v ** 2).sum(0)).clamp_min(1e-12)
return mu, var.sqrt()
def expected_improvement(mu, sigma, best):
normal = torch.distributions.Normal(torch.zeros((), dtype=mu.dtype), torch.ones((), dtype=mu.dtype))
gamma = (best - mu) / sigma
return sigma * (gamma * normal.cdf(gamma) + normal.log_prob(gamma).exp())
grid = torch.linspace(0, 1, 501, dtype=torch.float64)
x_obs = torch.rand(3, dtype=torch.float64) # 1. Try 3 random initial points
y_obs = torch.tensor([objective(u.item()) for u in x_obs], dtype=torch.float64)
for step in range(10): # Repeat steps 2–5 ten times
y_std = (y_obs - y_obs.mean()) / (y_obs.std() + 1e-9) # Standardize the loss scale before fitting
mu, sigma = gp_posterior(x_obs, y_std, grid)
ei = expected_improvement(mu, sigma, y_std.min())
u_next = grid[ei.argmax()]
y_next = objective(u_next.item())
x_obs = torch.cat([x_obs, u_next[None]])
y_obs = torch.cat([y_obs, torch.tensor([y_next], dtype=torch.float64)])
print(f"Step {step + 1:2d}: learning rate {10 ** (-4 + 3 * u_next.item()):.5f}, validation loss {y_next:.4f}")
best = y_obs.argmin()
print("Best learning rate:", 10 ** (-4 + 3 * x_obs[best].item()))
FAQ
Q. How many trials are enough?
A.
There is no fixed answer. The more hyperparameters there are to search, the more trials are needed. A practical approach is to cap the number of trials based on the time per training run and the compute time available, and to stop once the best result stops improving.
Q. How does it relate to tools such as Optuna?
A.
Optuna's default sampler is TPE, which is also a form of Bayesian optimization that picks the next point from past results. Some tools also offer Gaussian process–based methods. Using such tools is more convenient than implementing it yourself, since they also handle parallelization and early stopping of trials.
Q. Does it always beat random search?
A.
No. Its advantage shows when only a few trials are possible and each evaluation is expensive. When many machines can run hundreds of trials at once, or when there are many hyperparameters to search, it may not differ much from random search or Hyperband.