AI Wiki中文/EN

Bayesian optimization: choose the next expensive experiment

贝叶斯优化

Fit a Gaussian-process surrogate, derive expected improvement, and spend six objective calls on a finite grid.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Start with the problem

Suppose a model takes hours to train. Trying every learning rate is expensive, while calculating where to try next may take seconds. Bayesian optimization uses the completed trials to build a probabilistic surrogate, then chooses a new configuration with an acquisition function. The surrogate predicts the objective; the acquisition function values an experiment.

A low predicted loss is attractive. An uncertain point can also be useful because it might improve on the best observed result. Snoek, Larochelle and Adams, Section 2, describe this separation. Their full system models more than the small fixed-kernel example below. Start with Gaussian processes if conditioning a joint Gaussian is unfamiliar.

Definitions and derivation

Assume a deterministic scalar objective to minimize. We use a zero-mean Gaussian process with unit-variance, unit-length-scale RBF kernel k(a,b)=exp(−(a−b)²/2). Let K be the covariance matrix of queried points, kₓ their covariance with x, and δ a positive numerical jitter. Gaussian conditioning gives the latent prediction:

μ(x)=kx⊤(K+δI)−1y,σ2(x)=k(x,x)−kx⊤(K+δI)−1kx.\mu(x)=k_x^\top(K+\delta I)^{-1}y,\qquad \sigma^2(x)=k(x,x)-k_x^\top(K+\delta I)^{-1}k_x.

These are the standard regression equations from GPML, Chapter 2. Cholesky factorization solves the systems without explicitly forming an inverse. The tiny jitter makes numerical solves safer; it is not a fitted estimate of real measurement noise. A different mean, kernel or noise model produces different predictions.

For the current best observed loss, define improvement as a positive decrease. Integrating that decrease over a Gaussian predictive distribution gives:

I(x)=max⁡(fbest−F(x),0),EI⁡(x)=(fbest−μ)Φ(z)+σϕ(z),z=fbest−μσ.I(x)=\max(f_{\rm best}-F(x),0),\quad \operatorname{EI}(x)=(f_{\rm best}-\mu)\Phi(z)+\sigma\phi(z),\quad z=\frac{f_{\rm best}-\mu}{\sigma}.

Here Φ and φ are the standard normal CDF and density, and σ is positive. To derive the expression, integrate (fbest−u) times the predictive density from negative infinity to fbest, substitute v=(u−μ)/σ, and use the integral of vφ(v), which is −φ(v). The first term rewards a promising mean; the second reflects uncertainty. They are not independently adjustable weights.

The zero-variance limit and equal-mean case are useful checks:

σ=0: EI⁡=max⁡(fbest−μ,0),μ=fbest: EI⁡=σ2π.\sigma=0:\ \operatorname{EI}=\max(f_{\rm best}-\mu,0),\qquad \mu=f_{\rm best}:\ \operatorname{EI}=\frac{\sigma}{\sqrt{2\pi}}.

An acquisition value is an expectation under the surrogate. It is neither a promised improvement nor a probability that the configuration is optimal. We maximize EI over unqueried grid points, not over the expensive objective itself. The initial two objective calls are included in the six-call budget.

Run the calculation

This complete Python 3.12 / NumPy 1.26.4 program minimizes a deliberately cheap toy function, f(x)=(x−0.35)²+0.1 sin(5x), as if each selected evaluation were expensive. The search grid has nine points from −2 to 2. Endpoint queries initialize the surrogate; ties favor smaller x. No objective value at an unselected point is used to choose the next query.

import numpy as np
from math import erf,exp,sqrt,pi


def kernel(a,b):return np.exp(-.5*(np.asarray(a)[:,None]-np.asarray(b)[None,:])**2)


def posterior(observed,values,candidates,jitter=1e-8):
    x,y,q=[np.asarray(v,dtype=float) for v in (observed,values,candidates)]
    if x.ndim!=1 or y.shape!=x.shape or q.ndim!=1 or not 1<=x.size<=32 or not q.size:raise ValueError('matched observations and candidate vector required')
    if not all(np.isfinite(v).all() for v in (x,y,q)) or len(set(x))!=len(x) or not np.isfinite(jitter) or jitter<=0:raise ValueError('finite unique observations and positive jitter required')
    L=np.linalg.cholesky(kernel(x,x)+jitter*np.eye(len(x)))
    alpha=np.linalg.solve(L.T,np.linalg.solve(L,y));cross=kernel(x,q)
    mu=cross.T@alpha;v=np.linalg.solve(L,cross);variance=1-np.sum(v*v,axis=0)
    if np.min(variance)<-1e-8:raise ValueError('invalid posterior variance')
    return mu,np.sqrt(np.maximum(variance,0))


def expected_improvement(mu,sigma,best):
    if not all(np.isfinite(v) for v in (mu,sigma,best)) or sigma<0:raise ValueError('finite mean/best and nonnegative deviation required')
    delta=best-mu
    if sigma==0:return max(delta,0.)
    z=delta/sigma
    return max(0.,delta*(1+erf(z/sqrt(2)))/2+sigma*exp(-z*z/2)/sqrt(2*pi))


def optimize(objective,candidates,budget=6):
    grid=sorted(set(float(x) for x in candidates))
    if len(grid)<2 or not all(np.isfinite(x) for x in grid) or type(budget) is not int or not 2<=budget<=min(32,len(grid)):raise ValueError('finite grid and valid evaluation budget required')
    seen=[grid[0],grid[-1]];values=[float(objective(x)) for x in seen];trace=[]
    while len(seen)<budget:
        remaining=[x for x in grid if x not in seen];mu,sd=posterior(seen,values,remaining)
        ei=[expected_improvement(m,s,min(values)) for m,s in zip(mu,sd)]
        i=max(range(len(remaining)),key=lambda j:(ei[j],-remaining[j]))
        x=remaining[i];y=float(objective(x));trace.append((x,mu[i],sd[i],ei[i],y));seen.append(x);values.append(y)
    return seen,values,trace


def objective(x):return (x-.35)**2+.1*np.sin(5*x)


if __name__=='__main__':
    grid=np.linspace(-2,2,9);seen,values,trace=optimize(objective,grid)
    print('queried points:',seen)
    print('next x / predicted mean / sigma / EI / observed objective:')
    for row in trace:print([round(float(v),9) for v in row])
    i=int(np.argmin(values));print('best observed point / value:',seen[i],round(values[i],9))
    print('equal mean, more uncertainty:',round(expected_improvement(1,0,1),9),round(expected_improvement(1,1,1),9))

Actual output:

queried points: [-2.0, 2.0, 0.5, 0.0, 1.0, -0.5]
next x / predicted mean / sigma / EI / observed objective:
[0.5, 1.110589955, 0.944817379, 1.57707752, 0.082347214]
[0.0, 0.156391007, 0.432157947, 0.137908558, 0.1225]
[1.0, 0.91100391, 0.184629674, 1.36e-07, 0.326607573]
[-0.5, 0.639212451, 0.157743375, 8.177e-06, 0.662652786]
best observed point / value: 0.5 0.082347214
equal mean, more uncertainty: 0 0.39894228

The trace distinguishes predicted mean, uncertainty, EI and the subsequently measured value. The best observed point is 0.5 after six calls. This does not identify a continuous global minimum. For n observations and m candidates, the dense factorization costs O(n³), prediction through triangular solves costs O(n²m), and covariance storage costs O(n²). Expensive training may dominate these costs; for a cheap objective, the surrogate can cost more than the experiment.

When the method fails

A misspecified smooth kernel can be confidently wrong near discontinuities. In many dimensions, sparse observations say little about most of the search space. Categorical choices and conditional hyperparameters need an appropriate representation; assigning arbitrary numeric distances is not neutral.

With noisy evaluations, the smallest measured loss may be an unusually lucky observation. Noisy-improvement criteria, repeated measurements and explicit noise models address a different problem from this deterministic example. Pending parallel trials and variable evaluation costs also change candidate selection; they cannot be handled by merely relabeling EI as “best per second.” The finite-grid implementation supplies no regret guarantee. Use hyperparameter search as a transparent baseline and retain the same outer test discipline.

Exercises with answers

  1. If the predicted mean equals the best loss and σ=1, what is EI?

Answer 1: 1/√(2π)≈0.39894228, even though the predicted mean offers no decrease.

  1. If σ=0 and the predicted loss is two units worse, what is EI?

Answer 2: Zero. The degenerate predictive distribution offers no positive improvement.

  1. Does evaluating EI on all nine candidates spend nine training runs?

Answer 3: No. It spends surrogate computation. Only calls to the objective count as training evaluations in this budget.

  1. Why is the reported best point not a proof of global optimality?

Answer 4: Three grid points remain unqueried, points between grid locations are excluded, and the surrogate assumptions can be wrong.

Sources and next steps

The original 2012 paper’s Section 2.2 motivates expected improvement; GPML Section 2.2 and Algorithm 2.1 supply the conditioning and Cholesky calculations. The grid, six-call sequence and analytic toy objective are original exercises, not a reproduction of the paper’s model-training benchmarks. Compare Gaussian processes for prediction and hyperparameter search for experimental bookkeeping.

Make a prediction, then check

What is maximized to choose the next point in this example?

Choose one answer

Learning objectives

  • Derive expected improvement and handle zero predictive variance.
  • Track objective-call budgets separately from surrogate calculations.

Prerequisites & connections

Explore related knowledge →

References

  1. Practical Bayesian Optimization of Machine Learning Algorithms
    Jasper Snoek; Hugo Larochelle; Ryan P. Adams · 2012
  2. Gaussian Processes for Machine Learning — Chapter 2: Regression
    Carl Edward Rasmussen; Christopher K. I. Williams · 2006

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-06 · Codex single-AI-author technical check: primary-source scope, explicit assumptions, original calculations, independent mathematical references and bilingual tests; not independent human or second-agent review.

  • Single-AI-author technical check: bounded primary-source reading, explicit assumptions, original calculations, runnable examples and matching bilingual equations, code and exercises. Not an independent human or second-agent review.
  • Four focused CPython 3.12.4 tests passed per chapter, including independent derivatives, integrals, normal equations or exact/literal trajectory references as appropriate. NumPy 1.26.4 is used in six programs; PBT and curriculum use standard-library exact fractions. CPU teaching calculations, not framework or GPU benchmarks.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
  • Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.