TExcelTAD
Home › Training Mechanics, Evaluation & Model Improvement › Bayesian Optimisation and Optuna

Bayesian Optimisation and Optuna

Grid and random search ignore what they have already seen: trial 20 is chosen exactly as trial 1 was. When each trial is expensive (minutes or hours of training), that is wasteful. Bayesian optimisation keeps a cheap statistical model of the objective, a surrogate, fitted to the trials so far, and uses it to choose the next trial where improvement is most likely. It typically needs far fewer trials than random search to reach the same quality. This lesson builds the classic version, a Gaussian-process surrogate with the expected-improvement rule, in NumPy, tunes a real SVM with it in your browser, and then shows Optuna, the library most projects use.

The loop

  1. Evaluate a few starting configurations.
  2. Fit the surrogate to all (configuration, score) pairs so far. It gives, for any untried configuration, a predicted score μ(x)\mu(x) and an uncertainty s(x)s(x).
  3. Pick the configuration that maximises an acquisition function, which trades a high μ\mu (exploitation) against a high ss (exploration).
  4. Evaluate it, add it to the data, repeat.

The Gaussian-process surrogate

A Gaussian process treats the unknown objective as a random function whose values at any finite set of points are jointly Gaussian, with a covariance given by a kernel. The RBF kernel says nearby configurations have similar scores:

k(x,x′)=exp⁡(−(x−x′)22ℓ2)k(x, x') = \exp\left(-\frac{(x - x')^2}{2\ell^2}\right)

where the length scale ℓ\ell says how far "nearby" reaches. Given observations y\mathbf{y} at points XX, the prediction at a new point x∗x_* is Gaussian with

μ(x∗)=k∗⊤(K+σn2I)−1y,s2(x∗)=k(x∗,x∗)−k∗⊤(K+σn2I)−1k∗\mu(x_*) = \mathbf{k}_*^\top (K + \sigma_n^2 I)^{-1} \mathbf{y}, \qquad s^2(x_*) = k(x_*, x_*) - \mathbf{k}_*^\top (K + \sigma_n^2 I)^{-1} \mathbf{k}_*

with Kij=k(xi,xj)K_{ij} = k(x_i, x_j), (k∗)i=k(xi,x∗)(\mathbf{k}_*)_i = k(x_i, x_*) and a small noise variance σn2\sigma_n^2. This is the conditional distribution of a multivariate Gaussian, the same algebra as Bayesian linear regression. In code, a Cholesky factorisation replaces the inverse:

python · try it yourself
import numpy as np

def rbf(a, b, ell):
    return np.exp(-0.5 * (a[:, None] - b[None, :]) ** 2 / ell ** 2)

def gp_posterior(x, y, xs, ell=0.15, noise=1e-6):
    m, s = y.mean(), y.std()                      # standardise the targets
    t = (y - m) / s
    L = np.linalg.cholesky(rbf(x, x, ell) + noise * np.eye(len(x)))
    alpha = np.linalg.solve(L.T, np.linalg.solve(L, t))
    Ks = rbf(x, xs, ell)
    mu = Ks.T @ alpha
    v = np.linalg.solve(L, Ks)
    var = np.clip(1.0 - (v ** 2).sum(axis=0), 1e-12, None)
    return m + s * mu, s * np.sqrt(var)

f = lambda x: x * np.sin(6 * x)                   # pretend we do not know this
x_obs = np.array([0.1, 0.4, 0.5, 0.9])
mu, sd = gp_posterior(x_obs, f(x_obs), np.array([0.1, 0.25, 0.45, 0.7, 1.0]))
for xq, m_, s_ in zip([0.1, 0.25, 0.45, 0.7, 1.0], mu, sd):
    print(f"x = {xq:.2f}  true {f(xq):6.3f}  GP mean {m_:6.3f}  GP sd {s_:.3f}")
x = 0.10  true  0.056  GP mean  0.056  GP sd 0.000
x = 0.25  true  0.249  GP mean  0.240  GP sd 0.182
x = 0.45  true  0.192  GP mean  0.185  GP sd 0.028
x = 0.70  true -0.610  GP mean -0.374  GP sd 0.279
x = 1.00  true -0.279  GP mean -0.568  GP sd 0.220

At an observed point (x=0.1x = 0.1) the GP reproduces the value with zero uncertainty. Between close observations (x=0.45x = 0.45, between 0.4 and 0.5) it is nearly right and confident (sd 0.028). In the gap between 0.5 and 0.9 (x=0.7x = 0.7) and beyond the last point (x=1.0x = 1.0) it is wrong by 0.24 and 0.29, but it knows it is unsure: the standard deviations, 0.279 and 0.220, are about the size of the errors. That honest uncertainty is what makes the search work.

Expected improvement

Let y+y^+ be the best score so far (we maximise). The improvement of a new trial is max⁡(0,Y−y+)\max(0, Y - y^+); its expectation under the Gaussian prediction has a closed form:

EI(x)=(μ−y+−ξ) Φ(z)+s φ(z),z=μ−y+−ξs\text{EI}(x) = (\mu - y^+ - \xi)\, \Phi(z) + s\, \varphi(z), \qquad z = \frac{\mu - y^+ - \xi}{s}

with Φ\Phi and φ\varphi the standard normal CDF and density and a small margin ξ\xi (0.01 here) that nudges towards exploration. EI is large where the mean is high or the uncertainty is large, and zero where the model is sure the point is worse.

Tuning an SVM in the browser

The objective: 3-fold CV accuracy of an RBF SVM on 600 handwritten digits, as a function of log⁡10γ∈[−5,0]\log_{10} \gamma \in [-5, 0] (rescaled to u∈[0,1]u \in [0, 1] for the GP). Three starting points, then seven trials chosen by EI:

python · try it yourself
import numpy as np
from scipy.stats import norm
from sklearn.datasets import load_digits
from sklearn.model_selection import cross_val_score, StratifiedKFold
from sklearn.svm import SVC

def rbf(a, b, ell):
    return np.exp(-0.5 * (a[:, None] - b[None, :]) ** 2 / ell ** 2)

def gp_posterior(x, y, xs, ell=0.15, noise=1e-4):
    m, s = y.mean(), y.std()
    t = (y - m) / s
    L = np.linalg.cholesky(rbf(x, x, ell) + noise * np.eye(len(x)))
    alpha = np.linalg.solve(L.T, np.linalg.solve(L, t))
    Ks = rbf(x, xs, ell)
    v = np.linalg.solve(L, Ks)
    return m + s * (Ks.T @ alpha), s * np.sqrt(np.clip(1.0 - (v ** 2).sum(axis=0), 1e-12, None))

def expected_improvement(mu, sd, best, xi=0.01):
    z = (mu - best - xi) / sd
    return (mu - best - xi) * norm.cdf(z) + sd * norm.pdf(z)

X, y = load_digits(return_X_y=True)
X, y = X[:600], y[:600]
cv = StratifiedKFold(3, shuffle=True, random_state=0)
def objective(u):                                   # u in [0, 1]  ->  gamma = 10^(-5 + 5u)
    return cross_val_score(SVC(C=10, gamma=10 ** (-5 + 5 * u)), X, y, cv=cv).mean()

cand = np.linspace(0, 1, 201)
us = [0.1, 0.5, 0.9]
scores = [objective(u) for u in us]
for u, sc in zip(us, scores):
    print(f"start     log10 gamma {-5 + 5 * u:6.3f}  CV accuracy {sc:.3f}")
for it in range(7):
    mu, sd = gp_posterior(np.array(us), np.array(scores), cand)
    u = cand[np.argmax(expected_improvement(mu, sd, max(scores)))]
    us.append(u); scores.append(objective(u))
    print(f"trial {it + 4:2d}  log10 gamma {-5 + 5 * u:6.3f}  CV accuracy {scores[-1]:.3f}  best so far {max(scores):.3f}")
start     log10 gamma -4.500  CV accuracy 0.982
start     log10 gamma -2.500  CV accuracy 0.983
start     log10 gamma -0.500  CV accuracy 0.105
trial  4  log10 gamma -3.475  CV accuracy 0.987  best so far 0.987
trial  5  log10 gamma -5.000  CV accuracy 0.963  best so far 0.987
trial  6  log10 gamma -2.950  CV accuracy 0.990  best so far 0.990
trial  7  log10 gamma -4.000  CV accuracy 0.983  best so far 0.990
trial  8  log10 gamma -1.850  CV accuracy 0.530  best so far 0.990
trial  9  log10 gamma -2.700  CV accuracy 0.987  best so far 0.990
trial 10  log10 gamma  0.000  CV accuracy 0.138  best so far 0.990

The starting points show the shape of the problem: fine for small γ\gamma, a collapse to chance (0.105 with ten classes) at log⁡10γ=−0.5\log_{10}\gamma = -0.5. The first EI trial goes between the two good starting points (−3.475-3.475, 0.987), the second explores the unexplored left edge (−5.0-5.0, 0.963), and the third finds the best value, log⁡10γ=−2.95\log_{10}\gamma = -2.95 with 0.990. The remaining trials refine near the best and check the uncertain regions on the right (0.530 at −1.85-1.85, 0.138 at 00), which a smarter acquisition with a fitted length scale would skip. Ten evaluations located the optimum to within about a quarter of a decade.

Optuna

Optuna is the most used tuning library in Python. You write an objective that asks a trial object for values; Optuna's default sampler, TPE (tree-structured Parzen estimator), is a Bayesian method too: instead of modelling the score as a function of xx, it models the density of good configurations, ℓ(x)\ell(x), and of bad ones, g(x)g(x), and proposes points where ℓ(x)/g(x)\ell(x)/g(x) is high. It handles integers, categories and conditional parameters, runs trials in parallel, and can prune unpromising trials early (like successive halving). Optuna is not available in the browser, so this example is recorded:

python · try it yourself
import optuna
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import cross_val_score, StratifiedKFold
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC

optuna.logging.set_verbosity(optuna.logging.WARNING)      # no line per trial
X, y = load_breast_cancer(return_X_y=True)
cv = StratifiedKFold(5, shuffle=True, random_state=0)

def objective(trial):
    C = trial.suggest_float("C", 1e-1, 1e3, log=True)
    gamma = trial.suggest_float("gamma", 1e-4, 1.0, log=True)
    return cross_val_score(make_pipeline(StandardScaler(), SVC(C=C, gamma=gamma)), X, y, cv=cv).mean()

study = optuna.create_study(direction="maximize", sampler=optuna.samplers.TPESampler(seed=0))
study.optimize(objective, n_trials=40)
values = [t.value for t in study.trials]
for n in [5, 10, 20, 40]:
    print(f"best CV accuracy after {n:2d} trials: {max(values[:n]):.4f}")
print(f"best C {study.best_params['C']:.3g}, gamma {study.best_params['gamma']:.3g}")
best CV accuracy after  5 trials: 0.9789
best CV accuracy after 10 trials: 0.9789
best CV accuracy after 20 trials: 0.9824
best CV accuracy after 40 trials: 0.9824
best C 5.25, gamma 0.00554

TPE's first trials are random (it needs some history to build its densities); the best score improves from 0.9789 to 0.9824 by trial 20, at C≈5.25C \approx 5.25, γ≈0.0055\gamma \approx 0.0055, the same ridge the grid search found in the previous lesson. Here the extra 20 trials found nothing better: on 569 tumours, CV accuracies within about 0.005 of each other are indistinguishable. Useful extras: study.trials_dataframe() for analysis, optuna.visualization for plots, optuna.pruners.MedianPruner with trial.report and trial.should_prune() for early stopping of epoch-based training, and storage="sqlite:///study.db" to resume or parallelise a study.

When it pays off, and when it does not

  • Expensive trials, few hyperparameters (up to about 20): Bayesian methods shine. Deep-learning learning rates and weight decay, boosting parameters.
  • Cheap trials: random search with many trials is just as good and trivially parallel.
  • The surrogate has its own hyperparameters (the kernel's length scale here was fixed at 0.15; real libraries fit it by maximum likelihood). A badly chosen length scale makes the search either myopic or erratic.
  • Noise: CV scores are noisy. A GP with a noise term, or repeated folds, keeps the search from chasing lucky folds. The final score still needs nested CV or a test set.

Practice

  1. Where is EI zero, and where is it largest?
Answer

It approaches zero where the model is confident (s→0s \to 0) that the score is below y++ξy^+ + \xi. It is large where the predicted mean is above the best so far, or where the uncertainty is large enough that a big improvement is plausible.

  1. What happens to the GP's uncertainty at a point that has been evaluated, with almost no noise term?
Answer

It drops to nearly zero: the posterior passes through the observation. That is why EI does not propose the same point again unless the noise term allows the score to be different.

  1. Why rescale log⁡10γ\log_{10} \gamma to [0,1][0, 1] before fitting the GP?
Answer

So a single length scale (ℓ=0.15\ell = 0.15, about 15 % of the range) has a clear meaning, and because the score varies smoothly in log⁡γ\log \gamma, not in γ\gamma. With several hyperparameters, rescaling each to [0,1][0, 1] lets one kernel treat them alike.

Test yourself

What does the surrogate model in Bayesian optimisation provide?

  1. The exact objective value everywhere
  2. A predicted score and an uncertainty for untried configurations
  3. The gradient of the training loss
  4. A list of grid points

Expected improvement is high at a point with a mediocre predicted mean but a very large uncertainty. Why?

  1. It is a bug
  2. Large uncertainty means a large improvement is plausible: this is exploration
  3. EI ignores the mean
  4. Because ξ\xi is negative

Which statement about Optuna's default TPE sampler is right?

  1. It is a grid search
  2. It models the densities of good and bad configurations and samples where their ratio is high
  3. It needs gradients of the objective
  4. It only handles continuous parameters

When is plain random search usually just as good as Bayesian optimisation?

  1. When trials are expensive
  2. When trials are cheap and many can run in parallel
  3. Never
  4. When there are only two hyperparameters