Module contents
Lesson 17 of 27Core 110 min

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 ff over a bounded domain. After observing Dt={(xi,yi)}i=1t\mathcal D_t=\{(x_i,y_i)\}_{i=1}^t, fit a Gaussian process, maximize an acquisition at(x)a_t(x) summarizing the value of evaluating at xx, observe yt+1y_{t+1} and repeat. The model is not the real function and the acquisition is a decision rule, not another expensive-function evaluation.

InteractiveOne optimization step
  • GP mean
  • ±2σ band
  • Evaluations
Acquisition rescaled between 0 and 1, maximum at the marked point.
Acquisition
2.0
Evaluations3
Best observed value0.010
Next x1.25
Choose PI, EI or UCB and evaluate the next point. Reveal the function to compare what the algorithm knows with what it has not measured. The lower curve is rescaled to show its maximum, not to compare units across acquisitions.

The figure’s function is f(x)=0.6sin⁡(3x)+0.2cos⁡(7x)+0.15(x−1)2f(x)=0.6\sin(3x)+0.2\cos(7x)+0.15(x-1)^2 on [−2.5,2.5][-2.5,2.5], without noise. The GP uses RBF length 0.6 and variance 1, numerical noise 10−510^{-5}, and selects among 101 equally spaced candidates. It starts at −2-2, 0.20.2 and 22. 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 β=9\beta=9 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 F(x)∣Dt∼N(μ(x),σ2(x))F(x)\mid\mathcal D_t\sim\Normal(\mu(x),\sigma^2(x)) and best observed value ft∗f_t^*, improvement for minimization is I(x)=max⁡(ft∗−F(x)−ξ,0)I(x)=\max(f_t^*-F(x)-\xi,0), where ξ≥0\xi\ge0 is an optional margin. Probability of improvement is PI⁡(x)=Φ(z)\operatorname{PI}(x)=\Phi(z) and expected improvement (EI) is

EI⁡(x)=(ft∗−ξ−μ)Φ(z)+σϕ(z),z=ft∗−ξ−μσ,σ>0.\operatorname{EI}(x)=(f_t^*-\xi-\mu)\Phi(z)+\sigma\phi(z),\qquad z=\frac{f_t^*-\xi-\mu}{\sigma},\quad\sigma>0.

PI only counts whether improvement occurs; EI weights how much. If σ=0\sigma=0, EI is max⁡(ft∗−ξ−μ,0)\max(f_t^*-\xi-\mu,0) 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.

InteractiveAnatomy of expected improvement
  • Predictive density
  • Improving values
  • Best value
0.5
1.00
0.0
EI0.1978
log EI−1.62
Vary mean, standard deviation and best value. The colored area contains outcomes that improve, but EI also weights distance to the threshold. The plot only shows values from −6 to 6. Force a very small tail to compare EI with log EI.

To derive EI write F=μ+σZF=\mu+\sigma Z, Z∼N(0,1)Z\sim\Normal(0,1), and d=ft∗−ξ−μd=f_t^*-\xi-\mu. Integrate only over Z<z=d/σZ<z=d/\sigma:

E[I]=∫−∞z(d−σu)ϕ(u) ⁣du=dΦ(z)+σϕ(z),\E[I]=\int_{-\infty}^{z}(d-\sigma u)\phi(u)\dd u=d\Phi(z)+\sigma\phi(z),

because ∫−∞zuϕ(u) ⁣du=−ϕ(z)\int_{-\infty}^{z}u\phi(u)\dd u=-\phi(z). 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 EI⁡/σ=ϕ(z)+zΦ(z)\operatorname{EI}/\sigma=\phi(z)+z\Phi(z). If z=−xz=-x and xx is large, xΦ(−x)x\Phi(-x) approaches ϕ(x)\phi(x): two nearly equal numbers are subtracted. The Mills expansion gives

EI⁡/σ∼ϕ(z)z2(1−3z2+15z4−105z6+⋯ ),z→−∞.\operatorname{EI}/\sigma\sim\frac{\phi(z)}{z^2}\left(1-\frac3{z^2}+\frac{15}{z^4}-\frac{105}{z^6}+\cdots\right),\qquad z\to-\infty.

The logarithm is calculated by adding log⁡σ\log\sigma, log⁡ϕ(z)\log\phi(z), −2log⁡∣z∣-2\log|z| 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 z=0z=0 do not evaluate log⁡(−z)\log(-z): EI is σ/2π\sigma/\sqrt{2\pi}.

Confidence, Thompson and information

For minimization, GP-UCB chooses the minimum of μt(x)−βtσt(x)\mu_t(x)-\sqrt{\beta_t}\sigma_t(x), or the maximum of its negative. A large βt\beta_t 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 rt=min⁡i≤tf(xi)−f(x∗)r_t=\min_{i\le t} f(x_i)-f(x^*) and cumulative regret RT=∑t=1T[f(xt)−f(x∗)]R_T=\sum_{t=1}^T[f(x_t)-f(x^*)]. The result of Srinivas and colleagues bounds cumulative regret in terms of maximum information γT\gamma_T for a GP and noise under their assumptions, with an appropriate schedule of βt\beta_t: a bound of order TβTγT\sqrt{T\beta_T\gamma_T} implies decreasing average regret when βTγT=o(T)\beta_T\gamma_T=o(T). For a finite domain and the theorem’s Gaussian model, a growing schedule based on ∣X∣|\mathcal X|, tt and failure level can be used. It does not guarantee that the button with fixed β\beta finds the optimum in few evaluations, nor protect against a misspecified kernel.

With independent Gaussian noise of variance σn2>0\sigma_n^2>0, γT\gamma_T is the maximum over sets of TT evaluations of 12log⁡det⁡(I+σn−2KA)\tfrac12\log\det(\mat I+\sigma_n^{-2}\mat K_A), 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.

InteractiveAcquisitions on Branin
Normalized acquisition: 0 1. Points: evaluations; ring: next candidate. The u and v axes run from 0 to 1, left to right and bottom to top respectively.
  • Acquisition
  • Random
Acquisition
2.0
Evaluations3
Best Branin20.518
Next point0.90, 0.35
The surface colors normalized acquisition on a 21 × 21 grid in the unit domain. Each step adds a point; the regret curve is compared with a fixed random sequence of equal size.

The figure uses standard Branin with x1=15u−5x_1=15u-5, x2=15vx_2=15v, and minimum value 5/(4π)5/(4\pi). The GP has RBF length 0.2 in normalized coordinates, outputs standardized at each step and diagonal noise 10−610^{-6}. 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 x∗x^*; max-value entropy search (MES) targets optimal value f∗f^*. In minimization notation, MES maximizes mutual information I(Yx;f∗∣Dt)I(Y_x;f^*\mid\mathcal D_t), expected entropy reduction of the minimum value. Wang and Jegelka formulate MES for the maximum; convert minimum to maximum by changing the sign of ff. 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.

InteractiveA race of 20 seeds
  • Random
  • Grid
  • EI
  • UCB
  • Thompson
Seeds20
Final evaluations20
Best reference value−3.3224
Enable 10th to 90th percentile bands and isolate methods. Each curve summarizes the same budget of 20 evaluations, six shared initial and 14 additional, on Hartmann 6D.

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 10−610^{-6} and standardized outputs. UCB uses β=2\sqrt\beta=2; Thompson samples jointly over the pool. The grid selects without replacement from 363^6 points with coordinates 00, 0.50.5 and 11 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 −3.3223680114-3.3223680114 belongs to standard Hartmann 6D, defined in the lab and test-function documentation.

Batches, noise and dimensions

Batch optimization selects qq points before observing any. For noiseless minimization,

qEI⁡(x1,…,xq)=E ⁣[max⁡ ⁣(ft∗−min⁡jF(xj),0)|Dt].q\operatorname{EI}(x_1,\dots,x_q)=\E\!\left[\max\!\left(f_t^*-\min_jF(x_j),0\right)\middle|\mathcal D_t\right].

The expectation uses the joint normal of qq values and is approximated with correlated samples. Choosing the qq 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.

[ ]Surrogate and acquisitionsBrowser
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 z<−12z<-12; 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.

[ ]PI, EI, UCB, Thompson and MES on BraninBrowser
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 = -([email protected](size=len(pool)))
        else:
            draws = m[:,None][email protected](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 [0,1][0,1]. When acquisition vanishes, use a log EI implementation and check optimizer convergence. The minimum of a numerically calculated acquisition remains approximate.

[ ]Multistart and a batch of twoBrowser
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][email protected](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 363^6 points. The 14 steps added to six initial points make 20 total evaluations.

[ ]Hartmann 6D and one runBrowser
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)
[ ]Seeds 0 to 4Browser
batch(0,5)
[ ]Seeds 5 to 9Browser
batch(5,10)
[ ]Seeds 10 to 14Browser
batch(10,15)
[ ]Seeds 15 to 19 and summaryBrowser
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.

[ ]qLogEI versus random searchLocal GPU
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))
This cell needs the local lab (PyTorch with your GPU). Start it with 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 (1.2387,0.6413)(1.2387,0.6413), (0.6248,0.6399)(0.6248,0.6399) and (0.6571,0.6763)(0.6571,0.6763) for seeds 11, 22 and 33. The mean of those three best losses was 0.84020.8402 versus 0.65250.6525. 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

NumericImprovement with a worse mean
In minimization, with predictive mean μ=1\mu=1, standard deviation σ=0.5\sigma=0.5, best value f∗=0.8f^*=0.8 and zero margin, calculate EI.
ProofIntegrating improvement
Prove: Derive the closed EI formula for a Gaussian prediction in minimization.
0
Let F=μ+σZF=\mu+\sigma Z with Z∼N(0,1)Z\sim\Normal(0,1) and σ>0\sigma>0. Define d=f∗−μd=f^*-\mu and z=d/σz=d/\sigma.

Step 1 of 3. When is improvement positive?

QuizThe best datum may be luck
If evaluations are very noisy, which choice directly addresses using the best observed value as the EI reference?
QuizDimension and regions
What does TuRBO do compared with one global model in a high-dimensional problem?
CodeLog EI without underflow
Implement 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):
  pass
Shift+Enter to run

Summary

Key idea
Bayesian optimization uses a surrogate to decide which expensive evaluation merits the next budget. The result depends on the model and acquisition as well as how they are optimized and evaluated.
  • 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.