Sub topic 11
Bayesian optimization and sequential search
This chapter assumes you can run GridSearchCV and RandomizedSearchCV. It also assumes you know why tuning uses cross-validation on training data and keeps the test set for one final check. You should be comfortable with log-scale search spaces. Basic probability (mean, standard deviation) is enough for the math.
Why search sequentially
Grid and random search choose every setting before they see any result. Trial 30 gains nothing from trials 1 to 29. That is fine when each trial takes a second. It wastes budget when one trial means training a model for twenty minutes.
Sequential search changes this. It picks the next setting after looking at the scores so far. Bayesian optimization is the best-known version. The name covers a family of methods called sequential model-based optimization (SMBO). They all share one idea: fit a cheap model of the score surface, then use that model to decide what to try next.
The loop
- Evaluate a few starting settings, usually random ones.
- Fit a surrogate model to the pairs (setting, cross-validated score). The surrogate is a cheap predictor of the real score.
- Apply an acquisition function to the surrogate. It rates how promising each candidate setting is.
- Evaluate the real model at the highest-rated candidate.
- Add the result to the history and go back to step 2 until the budget is spent.
Surrogate models
The surrogate must give two things for any untried setting: a predicted score and a measure of uncertainty about that prediction.
- Gaussian process (GP). It predicts a mean and a standard deviation at every point. It works well with few trials and with continuous parameters. It slows down as trials grow, because fitting costs roughly the cube of the trial count. It also handles categorical and conditional parameters poorly.
- Tree-structured Parzen Estimator (TPE). It does not model score directly. It splits past trials into a "good" group (the top fraction by score) and a "bad" group. It fits a density to each group, then favors settings that are likely under the good density and unlikely under the bad one. It handles integers, categories, and conditional parameters naturally. This is why Optuna uses it by default.
- Random forest surrogates. SMAC uses these. The spread across trees serves as the uncertainty estimate.
Acquisition functions and the exploration trade-off
The acquisition function balances two goals:
- Exploitation: try settings near the best result so far.
- Exploration: try settings where the surrogate is uncertain, because a better score may be hiding there.
Expected improvement (EI) is the common choice. For a candidate with predicted mean mu and standard deviation sigma, and a best observed score best, EI is the average amount by which the candidate would beat best. The closed form for maximization is:
EI = (mu - best) * Phi(z) + sigma * phi(z), where z = (mu - best) / sigma
Phi and phi are the standard normal CDF and density. The first term rewards a high predicted mean. The second rewards high uncertainty. Other options include upper confidence bound (mu + kappa * sigma, where kappa sets how much you explore) and probability of improvement. Probability of improvement ignores the size of the gain and tends to over-exploit.
A minimal implementation
This script tunes one hyperparameter, C of an SVM, on a log10 scale. It uses a Gaussian process and EI. One dimension keeps the code short. The same loop applies to many dimensions, but the candidate grid would need to be replaced by random sampling.
import numpy as np
from scipy.stats import norm
from sklearn.datasets import load_breast_cancer
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import ConstantKernel, Matern, WhiteKernel
from sklearn.model_selection import cross_val_score, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=0, stratify=y
)
def make_model(log_c):
return make_pipeline(StandardScaler(), SVC(C=10 ** log_c, gamma="scale"))
def score(log_c):
return cross_val_score(make_model(log_c), X_train, y_train, cv=5).mean()
rng = np.random.default_rng(0)
candidates = np.linspace(-2, 3, 200).reshape(-1, 1)
observed_x = list(rng.uniform(-2, 3, size=4)) # initial random trials
observed_y = [score(x) for x in observed_x]
for _ in range(11): # 15 trials in total
kernel = ConstantKernel(1.0) * Matern(nu=2.5) + WhiteKernel(1e-4)
gp = GaussianProcessRegressor(
kernel=kernel, normalize_y=True, n_restarts_optimizer=2, random_state=0
)
gp.fit(np.array(observed_x).reshape(-1, 1), observed_y)
mu, sigma = gp.predict(candidates, return_std=True)
best = max(observed_y)
z = (mu - best) / np.maximum(sigma, 1e-9)
ei = (mu - best) * norm.cdf(z) + sigma * norm.pdf(z)
next_x = candidates[np.argmax(ei), 0]
observed_x.append(next_x)
observed_y.append(score(next_x))
i = int(np.argmax(observed_y))
print(f"best log10(C) = {observed_x[i]:.2f}, CV accuracy = {observed_y[i]:.4f}")
final = make_model(observed_x[i]).fit(X_train, y_train)
print("Test accuracy:", final.score(X_test, y_test))Points to notice:
- The
WhiteKernelterm lets the GP treat scores as noisy. Cross-validation scores are noisy estimates, so forcing the surrogate through every point would make it overfit them. - The search runs on
log10(C), so the surrogate sees a smooth, evenly spaced axis. The scale advice from the search-space chapter applies here too. - The test set is touched once, after the search ends.
Sequential versus parallel search
Sequential search has a cost. Trial k waits for trial k-1, so you cannot spread 30 trials across 30 machines the way you can with random search. Workarounds exist. One is to hand out several top candidates per round (batch acquisition). Another is to assign a temporary "fantasy" score to running trials. Both lose some of the sequential advantage. Libraries such as Optuna also let several workers share one study, and each worker asks the sampler for a new setting based on whatever has finished so far.
When it helps and when it does not
| Situation | Better choice |
|---|---|
| Each trial is expensive, budget is 20 to 200 trials | Bayesian optimization |
| Trials are cheap and you have many cores | Random search |
| 1 or 2 parameters with a few values each | Grid search |
| Many categorical or conditional parameters | TPE-based search, not a GP |
| Score is extremely noisy | Random search, or repeat evaluations |
| Many parameters barely affect the score | Random search is competitive |
In published comparisons, Bayesian methods usually beat random search at equal trial counts. The gap is often modest, and it shrinks as the number of dimensions grows. A GP surrogate struggles beyond roughly 10 to 20 continuous dimensions. Do not expect it to rescue a poorly defined search space. A range that excludes the good region will fail under any search method.
Common errors
- Reading the surrogate as the truth. The surrogate is a guess built from a handful of points. Only the cross-validated scores are real measurements.
- Too few initial trials. With 1 or 2 starting points the surrogate has almost nothing to learn from. Use at least a handful, often about as many as there are parameters.
- Optimizing noise. If the gap between the best trial and the runner-up is smaller than the fold-to-fold standard deviation, the winner is partly luck. Later chapters on nested cross-validation and reporting cover this.
- Leaking test data. The history of trial scores must come from cross-validation or a validation split inside the training data. If the objective ever scores on the test set, the final number is no longer an honest estimate.
- Unbounded or badly scaled ranges. The surrogate assumes nearby settings give similar scores. A linear axis for a parameter that spans orders of magnitude breaks that assumption.
Exercise
You have a 12-hour budget. Each trial (5-fold cross-validation of a gradient-boosting model) takes 15 minutes on one machine, and you have 8 machines. Explain the trade-off between running Bayesian optimization one trial at a time and running random search in parallel, and say which you would pick.
Show answer
One machine running sequential Bayesian optimization completes 48 trials in 12 hours (12 hours x 4 trials per hour), and each trial uses everything learned before it. Random search on 8 machines completes about 384 trials (48 x 8) but none of them learns from the others. With only 48 trials, the surrogate sees little data, but 384 blind trials may still beat it when many parameters matter little. A good middle path is to run Bayesian optimization with all 8 machines sharing one study, so each worker proposes settings from the results finished so far. That gives roughly 384 trials, and the sampler still uses earlier results, though proposals made while other trials are running lack their scores. Pure sequential search on one machine is the weakest use of the hardware here.
Exercise
In expected improvement, what happens to the second term, sigma * phi(z), at a candidate with a mean equal to the best score so far (mu = best)? What does this show about exploration?
Show answer
With mu = best, z = 0 and the first term (mu - best) * Phi(z) is zero. EI reduces to sigma * phi(0), which is proportional to sigma. A candidate that is predicted to merely tie the best score is therefore valued only for its uncertainty. A more uncertain candidate gets a higher EI, so the acquisition function explores where the surrogate is unsure.