Bayesian optimization
To optimize an expensive gradient-free function, use a GP surrogate and an acquisition function to select evaluations. We derive PI, EI and GP-UCB, examine information-based acquisitions, batches and high dimensions, and apply them to neural-network hyperparameters on a local GPU.
After this lesson you can
- Implement a Bayesian optimization loop over a custom GP.
- Derive closed-form expected improvement and explain its exploration-exploitation tradeoff.
- Compare PI, EI, GP-UCB, GP Thompson sampling and max-value entropy search on test functions.
- Extend the loop to batches (q-EI) and high dimensions with trust regions (TuRBO).
- Tune a real model's hyperparameters with BoTorch and compare with random search.
Before you start
Choosing the next expensive evaluation
Imagine each evaluation trains a network or runs a simulator for hours. A dense grid spends most of the budget in mediocre regions. Exploiting the best observed point may instead miss a promising region not yet known. The decision is sequential: what an evaluation reveals changes where it is useful to evaluate next.
Bayesian optimization uses a probabilistic surrogate model of the function and an acquisition to decide the next experiment. Here we minimize over a bounded domain. After observing , fit a Gaussian process, maximize an acquisition summarizing the value of evaluating at , observe and repeat. The model is not the real function and the acquisition is a decision rule, not another expensive-function evaluation.
The figure’s function is on , without noise. The GP uses RBF length 0.6 and variance 1, numerical noise , and selects among 101 equally spaced candidates. It starts at , and . Changing acquisition midway through a run retains observations; resetting lets you compare from the same start. Hidden truth is included only for inspection.
Try several PI steps with zero margin: in this example its first choices cluster near the best initial value before exploring farther. With UCB and uncertainty weighs more and points appear early in less-observed regions. Neither behavior is inevitable in every problem; it depends on prior, initial data and grid.
Probability and magnitude of improvement
With latent prediction and best observed value , improvement for minimization is , where is an optional margin. Probability of improvement is and expected improvement (EI) is
PI only counts whether improvement occurs; EI weights how much. If , EI is and PI depends on whether the strict inequality holds. EI balances exploitation and exploration without an explicit selector: even with a worse mean than the best, a tail of large improvements can remain.
To derive EI write , , and . Integrate only over :
because . The figure’s colored region shows probability, not the value of the weighted integral. Controls use a normal function and the formula above; for the negative tail they calculate log EI with a continued fraction for Mills ratio. Exponentiating a very negative value can yield floating-point zero even while log EI remains finite.
In exact arithmetic maximizing EI or its logarithm is equivalent where EI is positive. In floating point, subtraction between small EI terms can lose precision and sometimes yield zero along with its gradient. Ament and colleagues develop LogEI reformulations also for noisy and batch variants. Code must calculate the logarithm stably, not merely do log(ei) after EI has underflowed.
To see cancellation, write . If and is large, approaches : two nearly equal numbers are subtracted. The Mills expansion gives
The logarithm is calculated by adding , , and the logarithm of the parenthesized factor. This is an asymptotic expansion: truncation is appropriate only sufficiently far into the tail. Near the center use the normal formula, and between regions an expression with log_ndtr and log1p. At do not evaluate : EI is .
Confidence, Thompson and information
For minimization, GP-UCB chooses the minimum of , or the maximum of its negative. A large favors uncertain locations, but an arbitrary constant does not automatically provide a guarantee. Thompson sampling draws an entire function from the joint posterior and evaluates its minimum; independent normals at each point are insufficient because they lose GP correlations.
Define simple regret and cumulative regret . The result of Srinivas and colleagues bounds cumulative regret in terms of maximum information for a GP and noise under their assumptions, with an appropriate schedule of : a bound of order implies decreasing average regret when . For a finite domain and the theorem’s Gaussian model, a growing schedule based on , and failure level can be used. It does not guarantee that the button with fixed finds the optimum in few evaluations, nor protect against a misspecified kernel.
With independent Gaussian noise of variance , is the maximum over sets of evaluations of , mutual information between latent values and observations. The proof relates band widths to instantaneous regret and sums predictive variances via that information gain. This is a high-probability bound under the model and theorem assumptions, not an empirical interval for any GPU experiment.
The figure uses standard Branin with , , and minimum value . The GP has RBF length 0.2 in normalized coordinates, outputs standardized at each step and diagonal noise . The random strategy uses a fixed seed and shares the three initial points. This is one teaching trajectory, not evidence of general superiority.
Information acquisitions seek to reduce uncertainty about the optimum. Entropy search targets location ; max-value entropy search (MES) targets optimal value . In minimization notation, MES maximizes mutual information , expected entropy reduction of the minimum value. Wang and Jegelka formulate MES for the maximum; convert minimum to maximum by changing the sign of . The optimum distribution is unknown and approximated using samples and, in practical implementations, a finite candidate set. This is not exact MES on the continuous domain.
The figure contains results run for seeds 0 through 19. Each strategy uses the same six initial points per seed. EI, UCB and Thompson share a pool of 64 uniform candidates per step; the RBF GP has length 0.3, signal 1, jitter and standardized outputs. UCB uses ; Thompson samples jointly over the pool. The grid selects without replacement from points with coordinates , and in permuted order; random search uses one uniform candidate per step. Bands are percentiles between runs, not confidence intervals for the mean. This specific setup does not authorize a universal method ranking. Reference minimum belongs to standard Hartmann 6D, defined in the lab and test-function documentation.
Batches, noise and dimensions
Batch optimization selects points before observing any. For noiseless minimization,
The expectation uses the joint normal of values and is approximated with correlated samples. Choosing the largest individual EI values often repeats nearby points because it ignores redundancy. Kriging believer is a sequential heuristic: propose one, temporarily include it with a fictitious value such as the mean, then select again. It can help, but is not generally equivalent to optimizing q-EI.
If two candidates are identical, their latent values coincide and evaluating both does not double batch improvement. If weakly correlated, there is an extra opportunity for at least one to improve. Joint acquisition quantifies this through covariance, while adding two marginal EIs double-counts shared improvement. The cell below calculates q-EI for a fixed pair; it does not present that pair as the optimal batch solution.
With noisy observations, the observed minimum may be lucky noise. Treating it as truth artificially reduces EI. A noisy acquisition integrates uncertainty about latent values and reference; qNEI or qLogNEI are suitable options when the noise model describes the situation. Unknown constraints can also be modeled and combined with feasibility probability, without confusing an arbitrary penalty with a guarantee of compliance.
In high dimensions, a global domain has much unobserved space, length fitting becomes difficult with few points and optimizing acquisition also costs. There is no universal threshold of 20 dimensions: degradation depends on structure, budget and method. TuRBO fits local models in trust regions expanding after success and contracting after failure, and allocates budget among regions. It can exploit local structure without guaranteeing all dimensional difficulty disappears. Random projections are another option when the function depends on a low-dimensional submanifold, but their utility depends on that assumption.
Lab: acquisitions from scratch
The following GP uses the same Cholesky operations as the previous lesson, now in arbitrary dimensions. Inputs are in the unit hypercube and outputs standardized on each fit. Predictive covariance includes small jitter for sampling joint functions. To focus on acquisitions, length is fixed at 0.2: hyperparameters are not automatically refitted.
import numpy as np
from scipy.linalg import solve_triangular
from scipy.special import ndtr, log_ndtr
from scipy.optimize import minimize
def kernel(A, B, length=0.2):
d2 = np.sum((A[:,None,:]-B[None,:,:])**2, axis=2)
return np.exp(-d2/(2*length**2))
def gp(X, y, Xs, length=0.2, joint=False):
center, scale = y.mean(), max(y.std(), 1e-6)
ys = (y-center)/scale
L = np.linalg.cholesky(kernel(X,X,length)+1e-6*np.eye(len(X)))
Ks = kernel(X,Xs,length)
alpha = solve_triangular(L.T, solve_triangular(L,ys,lower=True))
v = solve_triangular(L,Ks,lower=True)
mean = Ks.T@alpha
var = np.maximum(1e-12,1-np.sum(v*v,axis=0))
cov = kernel(Xs,Xs,length)-v.T@v if joint else None
return mean, np.sqrt(var), cov, ys.min()
def ei(mu, sd, best):
z = (best-mu)/sd
return (best-mu)*ndtr(z)+sd*np.exp(-z*z/2)/np.sqrt(2*np.pi)
def log_ei(mu, sd, best):
"""Escalar, sd > 0. Cola negativa por expansión asintótica."""
z = (best-mu)/sd
logphi = -0.5*z*z-0.5*np.log(2*np.pi)
if z < -12:
q = 1/(z*z)
series = 1-3*q+15*q**2-105*q**3+945*q**4-10395*q**5
return np.log(sd)+logphi+np.log(q)+np.log(series)
if z < 0:
return np.log(sd)+logphi+np.log1p(-np.exp(np.log(-z)+log_ndtr(z)-logphi))
return np.log(sd)+np.log(np.exp(logphi)+z*ndtr(z))
def branin(U):
u, v = np.atleast_2d(U).T
x, yb = 15*u-5, 15*v
return (yb-5.1*x*x/(4*np.pi**2)+5*x/np.pi-6)**2 + 10*(1-1/(8*np.pi))*np.cos(x)+10
print('log EI en z=-40:', log_ei(40.0,1.0,0.0), 'EI directa:', ei(40.0,1.0,0.0))The tail expansion is asymptotic and used only for ; the exercise requires checking it against extended precision. This cell’s direct EI serves ordinary comparison, not optimization of an extreme tail. For MES we use the minimum of joint samples over a finite pool and the noiseless Gaussian observation expression. With 16 Monte Carlo samples the result is a noisy approximation, not exact continuous MES.
def choose(X, y, pool, method, rg):
if method == 'random':
return pool[0]
joint = method in ('thompson','mes')
m, sd, cov, best = gp(X,y,pool,joint=joint)
if method == 'pi':
score = ndtr((best-m)/sd)
elif method == 'ei':
score = ei(m,sd,best)
elif method == 'ucb':
score = -m+2*sd
else:
L = np.linalg.cholesky(cov+1e-8*np.eye(len(pool)))
if method == 'thompson':
score = -(m+L@rg.normal(size=len(pool)))
else:
draws = m[:,None]+L@rg.normal(size=(len(pool),16))
minima = draws.min(axis=0)
gamma = (m[:,None]-minima[None,:])/sd[:,None]
logcdf = log_ndtr(gamma)
logpdf = -0.5*gamma**2-0.5*np.log(2*np.pi)
score = np.mean(0.5*gamma*np.exp(logpdf-logcdf)-logcdf,axis=1)
return pool[np.argmax(score)]
def run_branin(method, seed, steps=8):
rg = np.random.default_rng(seed)
X = rg.random((4,2)); y = branin(X)
pools = rg.random((steps,64,2))
sample_rng = np.random.default_rng(seed+1000)
for pool in pools:
x = choose(X,y,pool,method,sample_rng)
X = np.vstack((X,x)); y = np.append(y,branin(x))
return y.min()-5/(4*np.pi)
for method in ('random','pi','ei','ucb','thompson','mes'):
regrets = np.array([run_branin(method,seed) for seed in range(10)])
print(method, 'media', round(regrets.mean(),4), 'percentiles', np.round(np.quantile(regrets,[0.1,0.9]),4))Each method gets the same initial points and pools per seed; Thompson and MES use a separate generator for their random functions. The comparison presents mean and percentiles over ten seeds with equal evaluation count. The finite pool, fixed model and 16 MES samples are part of the experiment, so changing any can change the ordering.
To optimize EI continuously instead of choosing only from a pool, solve the cheap acquisition problem from multiple starts. The next example uses L-BFGS-B with numerical gradient differences and bounds each coordinate to . When acquisition vanishes, use a log EI implementation and check optimizer convergence. The minimum of a numerically calculated acquisition remains approximate.
rg = np.random.default_rng(8)
X = rg.random((6,2)); y = branin(X)
def neg_acq(x):
m, sd, _, best = gp(X,y,np.asarray(x)[None,:])
return -log_ei(float(m[0]),float(sd[0]),best)
starts = rg.random((5,2))
sols = [minimize(neg_acq, x, method='L-BFGS-B', bounds=[(0,1)]*2) for x in starts]
solution = min(sols,key=lambda s:s.fun)
print('mejor candidato',np.round(solution.x,4),'log EI',round(-solution.fun,4))
pair = np.array([[0.2,0.4],[0.8,0.7]])
m, sd, cov, best = gp(X,y,pair,joint=True)
L = np.linalg.cholesky(cov+1e-8*np.eye(2))
draws = m[:,None]+L@rg.normal(size=(2,2000))
qei = np.maximum(best-draws.min(axis=0),0).mean()
print('qEI Monte Carlo de un par fijo, escala estandarizada',round(qei,4))Reproducing the Hartmann 6D race
These cells generate the figure’s data without external files. The first defines the standard function and a run; the next four split the 20 seeds to keep browser cells short. Methods share initialization and candidate pools, but consume independent randomness for Thompson samples. Grid uses a permutation of its points. The 14 steps added to six initial points make 20 total evaluations.
A = np.array([[10,3,17,3.5,1.7,8],[0.05,10,17,0.1,8,14],[3,3.5,1.7,10,17,8],[17,8,0.05,10,0.1,14]])
P = 1e-4*np.array([[1312,1696,5569,124,8283,5886],[2329,4135,8307,3736,1004,9991],[2348,1451,3522,2883,3047,6650],[4047,8828,8732,5743,1091,381]])
coeff = np.array([1,1.2,3,3.2])
reference = -3.32236801141551
def hartmann(x):
x = np.atleast_2d(x)
return -np.sum(coeff*np.exp(-np.sum(A*(x[:,None,:]-P)**2,axis=2)),axis=1)
def race_one(seed, method, steps=14, n_candidates=64):
rg = np.random.default_rng(seed)
X = rg.random((6,6)); y = hartmann(X)
pools = rg.random((steps,n_candidates,6))
ts = np.random.default_rng(seed+10000)
perm = np.random.default_rng(seed+20000).permutation(3**6)
levels = np.array(np.meshgrid(*([np.linspace(0,1,3)]*6),indexing='ij')).reshape(6,-1).T
trace = [y.min()-reference]
for t in range(steps):
if method == 'random':
candidate = pools[t,0]
elif method == 'grid':
candidate = levels[perm[t]]
else:
mean, scale = y.mean(), max(y.std(),1e-6)
ys = (y-mean)/scale
L = np.linalg.cholesky(kernel(X,X,0.3)+1e-6*np.eye(len(X)))
K = kernel(X,pools[t],0.3)
alpha = solve_triangular(L.T,solve_triangular(L,ys,lower=True))
m = K.T@alpha
v = solve_triangular(L,K,lower=True)
sd = np.sqrt(np.maximum(1e-12,1-np.sum(v*v,axis=0)))
if method == 'ei':
score = ei(m,sd,ys.min())
elif method == 'ucb':
score = -m+2*sd
else:
cov = kernel(pools[t],pools[t],0.3)-v.T@v+1e-8*np.eye(n_candidates)
score = -(m+np.linalg.cholesky(cov)@ts.normal(size=n_candidates))
candidate = pools[t,np.argmax(score)]
X = np.vstack((X,candidate)); y = np.append(y,hartmann(candidate))
trace.append(y.min()-reference)
return trace
methods = ('random','grid','ei','ucb','thompson')
traces = {method: [] for method in methods}
def batch(lo,hi):
for method in methods:
traces[method].extend(race_one(seed,method) for seed in range(lo,hi))
print('semillas procesadas:',hi)batch(0,5)batch(5,10)batch(10,15)batch(15,20)
for method in methods:
arr = np.asarray(traces[method])
print(method, 'media final', round(arr[:,-1].mean(),4), 'percentiles', np.round(np.quantile(arr[:,-1],[0.1,0.9]),4))Calculations have the same definition as the figure, which stores means and percentiles generated by a local run of this recipe. Results are simulated on test functions, not measurements of a real system. Repeating with another budget, kernel or more candidates can change the comparison.
In that run final means were 2.1014 for random, 2.1151 for grid, 1.1372 for EI, 1.0525 for UCB and 1.8578 for Thompson. The axis measures distance to the known minimum, so lower is better. Bands and sample size show dispersion across seeds; do not extrapolate that ordering to other budgets or functions.
Local lab: Fashion-MNIST with BoTorch
Here the objective trains a real MLP on GPU. To keep execution accessible, use 3000 training images, 1000 validation images and two epochs per configuration. Learning rate, weight_decay and width are optimized. Each repetition shares three initial evaluations between BO and random search; then each method gets three more, so both use six evaluations to make their decision. Repeat with three seeds. This is a short validation comparison, not an exhaustive search or test performance estimate. The first run downloads Fashion-MNIST if absent from cache; local runtime requires PyTorch, torchvision, GPyTorch, BoTorch and CUDA.
from pathlib import Path
import numpy as np
import torch
from torch import nn
from torchvision.datasets import FashionMNIST
from gpytorch.mlls import ExactMarginalLogLikelihood
from botorch.models import SingleTaskGP
from botorch.models.transforms.outcome import Standardize
from botorch.fit import fit_gpytorch_mll
from botorch.acquisition.logei import qLogExpectedImprovement
from botorch.optim import optimize_acqf
assert torch.cuda.is_available(), 'Se necesita CUDA para este laboratorio'
device = torch.device('cuda')
dataset = FashionMNIST(str(Path.home()/'.cache'/'atlas-data'),train=True,download=True)
images = dataset.data.to(device=device,dtype=torch.float32).reshape(-1,784)/255
labels = dataset.targets.to(device=device)
def evaluation(u, split_seed):
"""Pérdida media de validación, siempre con el mismo reparto para una repetición."""
rg = np.random.default_rng(split_seed)
ids = rg.permutation(len(images))
train_ids, valid_ids = ids[:3000], ids[3000:4000]
torch.manual_seed(split_seed)
width = int(round(64+192*u[2]))
lr = 10**(-4+2*u[0]); decay = 10**(-6+4*u[1])
model = nn.Sequential(nn.Linear(784,width),nn.ReLU(),nn.Linear(width,10)).to(device)
optimizer = torch.optim.AdamW(model.parameters(),lr=lr,weight_decay=decay)
model.train()
for _ in range(2):
for batch in np.array_split(rg.permutation(train_ids),12):
ids_t = torch.as_tensor(batch,device=device)
optimizer.zero_grad()
loss = nn.functional.cross_entropy(model(images[ids_t]),labels[ids_t])
loss.backward(); optimizer.step()
model.eval()
with torch.no_grad():
ids_v = torch.as_tensor(valid_ids,device=device)
result = nn.functional.cross_entropy(model(images[ids_v]),labels[ids_v]).item()
return result
def experiment(seed):
rg = np.random.default_rng(seed)
initial = rg.random((3,3))
initial_loss = np.array([evaluation(u,seed) for u in initial])
bo_X, bo_loss = initial.copy(), initial_loss.copy()
random_X, random_loss = initial.copy(), initial_loss.copy()
for _ in range(3):
# BoTorch maximiza; el objetivo es la pérdida negativa.
tx = torch.tensor(bo_X,device=device,dtype=torch.double)
ty = torch.tensor(-bo_loss[:,None],device=device,dtype=torch.double)
gp = SingleTaskGP(tx,ty,outcome_transform=Standardize(m=1)).to(device)
fit_gpytorch_mll(ExactMarginalLogLikelihood(gp.likelihood,gp))
acq = qLogExpectedImprovement(gp,best_f=ty.max())
bounds = torch.stack((torch.zeros(3,device=device,dtype=torch.double),torch.ones(3,device=device,dtype=torch.double)))
torch.manual_seed(seed+len(bo_loss))
candidate, _ = optimize_acqf(acq,bounds=bounds,q=1,num_restarts=3,raw_samples=32,options={'maxiter':40})
u = candidate.detach().cpu().numpy()[0]
bo_X = np.vstack((bo_X,u)); bo_loss = np.append(bo_loss,evaluation(u,seed))
u_random = rg.random(3)
random_X = np.vstack((random_X,u_random)); random_loss = np.append(random_loss,evaluation(u_random,seed))
return bo_loss.min(), random_loss.min()
results = np.array([experiment(seed) for seed in (11,22,33)])
for seed, row in zip((11,22,33),results):
print('semilla',seed,'mejor pérdida BO y aleatoria',np.round(row,4))
print('media de mejores pérdidas',np.round(results.mean(axis=0),4))npm run lab and open the connection link.Width is rounded to an integer, so the objective has a discrete component and the continuous GP is an approximation. All comparisons within a seed use the same split and training rule; initial observations are shared and not retrained. GPU precision and operation order can change details across environments. To choose a final model, reserve an independent test set and evaluate it only after selecting the configuration with validation.
In a short local run, best validation losses for BO and random were respectively , and for seeds 11, 22 and 33. The mean of those three best losses was versus . The first seed dominates the difference and three repetitions cannot establish which strategy is generally better. Figures come from the configurations, subsets and two epochs of this cell, not the official test set or full Fashion-MNIST training.
Exercises
Step 1 of 3. When is improvement positive?
log_expected_improvement(mu, sigma, best) for minimization with scalars and nonnegative sigma. Return log EI; with zero sigma return the logarithm of positive deterministic improvement or negative infinity. Avoid computing EI first in the negative tail. Tests use extended precision.def log_expected_improvement(mu, sigma, best):
passSummary
- EI weights improvement magnitude, PI its probability, and GP-UCB uses a confidence bound. Thompson requires jointly sampled functions.
- MES seeks information about the optimum value; q-EI treats batch points jointly. With noise, the latent reference must be modeled.
- Scaling, multistart, paired comparisons and seeds make results interpretable. TuRBO uses local regions without eliminating all dimensional difficulty.