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
- Evaluate a few starting configurations.
- Fit the surrogate to all (configuration, score) pairs so far. It gives, for any untried configuration, a predicted score and an uncertainty .
- Pick the configuration that maximises an acquisition function, which trades a high (exploitation) against a high (exploration).
- 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:
where the length scale says how far "nearby" reaches. Given observations at points , the prediction at a new point is Gaussian with
with , and a small noise variance . This is the conditional distribution of a multivariate Gaussian, the same algebra as Bayesian linear regression. In code, a Cholesky factorisation replaces the inverse:
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 () the GP reproduces the value with zero uncertainty. Between close observations (, between 0.4 and 0.5) it is nearly right and confident (sd 0.028). In the gap between 0.5 and 0.9 () and beyond the last point () 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 be the best score so far (we maximise). The improvement of a new trial is ; its expectation under the Gaussian prediction has a closed form:
with and the standard normal CDF and density and a small margin (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 (rescaled to for the GP). Three starting points, then seven trials chosen by EI:
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 , a collapse to chance (0.105 with ten classes) at . The first EI trial goes between the two good starting points (, 0.987), the second explores the unexplored left edge (, 0.963), and the third finds the best value, with 0.990. The remaining trials refine near the best and check the uncertain regions on the right (0.530 at , 0.138 at ), 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 , it models the density of good configurations, , and of bad ones, , and proposes points where 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:
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 , , 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
- Where is EI zero, and where is it largest?
Answer
It approaches zero where the model is confident () that the score is below . 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.
- 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.
- Why rescale to before fitting the GP?
Answer
So a single length scale (, about 15 % of the range) has a clear meaning, and because the score varies smoothly in , not in . With several hyperparameters, rescaling each to lets one kernel treat them alike.
Test yourself
What does the surrogate model in Bayesian optimisation provide?
- The exact objective value everywhere
- A predicted score and an uncertainty for untried configurations
- The gradient of the training loss
- A list of grid points
Expected improvement is high at a point with a mediocre predicted mean but a very large uncertainty. Why?
- It is a bug
- Large uncertainty means a large improvement is plausible: this is exploration
- EI ignores the mean
- Because is negative
Which statement about Optuna's default TPE sampler is right?
- It is a grid search
- It models the densities of good and bad configurations and samples where their ratio is high
- It needs gradients of the objective
- It only handles continuous parameters
When is plain random search usually just as good as Bayesian optimisation?
- When trials are expensive
- When trials are cheap and many can run in parallel
- Never
- When there are only two hyperparameters