Sub topic 11
Bayesian optimization and sequential search
This chapter assumes you know how grid and random search work, can use cross-validation in scikit-learn, and understand why tuning must happen on training data only. You do not need any probability background.
Why search sequentially
Grid and random search choose every setting before any result comes back. A trial that scores badly teaches the search nothing. Bayesian optimization, also called sequential model-based optimization, changes this. It picks the next setting using the scores of the earlier trials.
The method works in a loop:
- Evaluate a few starting settings, often chosen at random.
- Fit a cheap surrogate model that predicts the score for any setting, based on the trials so far.
- Use the surrogate to choose the next setting. This choice balances exploitation (try near the best score so far) against exploration (try regions you know little about).
- Run that trial, record its score, and go back to step 2.
Surrogate models
Different tools use different surrogates.
| Method | Surrogate | Notes |
|---|---|---|
| Gaussian process | Smooth function with uncertainty estimates | Works well for few, continuous parameters. Slows down as trials grow. |
| TPE (Tree-structured Parzen Estimator) | Two density models: one for good trials, one for the rest | Handles integer, categorical, and conditional parameters. Optuna's default. |
| Random forest surrogate | Forest predicting score | Used by SMAC. Copes with mixed parameter types. |
TPE splits past trials into a good group (the top scorers) and a bad group. It then proposes settings that are likely under the good group and unlikely under the bad group.
An example with Optuna
Optuna is a tuning library. You write an objective function that takes a trial, asks it for settings, and returns a score. The study runs the objective repeatedly.
import optuna
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score, train_test_split
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 objective(trial):
params = {
"n_estimators": trial.suggest_int("n_estimators", 50, 300),
"max_depth": trial.suggest_int("max_depth", 2, 16),
"min_samples_leaf": trial.suggest_int("min_samples_leaf", 1, 10),
}
model = RandomForestClassifier(random_state=0, **params)
return cross_val_score(model, X_train, y_train, cv=5).mean()
study = optuna.create_study(
direction="maximize",
sampler=optuna.samplers.TPESampler(seed=0),
)
study.optimize(objective, n_trials=30)
print(study.best_params, study.best_value)The objective scores with cross-validation on X_train only. The test set stays untouched until you evaluate the final model once. The seed=0 in the sampler makes the sequence of proposals repeatable.
Common errors and trade-offs
- Expecting a large gain from few trials. With 10 to 20 trials, most of the work is the random starting phase. The advantage over random search grows with more trials.
- Treating the best score as an unbiased estimate. The best cross-validation score is optimistically biased because you picked it as the maximum. Use a held-out test set or nested cross-validation for the final estimate.
- Noisy scores. If cross-validation scores vary a lot between runs, the surrogate chases noise. Use more folds or repeated cross-validation.
- Limited parallelism. Each proposal depends on earlier results, so running many trials at once weakens the benefit. Random search parallelizes more simply.
- Wrong scales. Declare rate-like parameters with
log=True, for exampletrial.suggest_float("lr", 1e-4, 1e-1, log=True). Otherwise the search spends most trials on the largest values.
Exercise
Your tuning run uses 40 trials, and each trial must finish before the next can be proposed. Why might 8 parallel workers give a smaller speedup than they would for random search, and what does the best cross-validation score tell you about test performance?
Show answer
In sequential search, each proposal uses the results of earlier trials. Running trials in parallel means proposals are made with fewer completed results, so they are less informed. Random search has no such dependency, so it scales almost linearly with workers. The best cross-validation score is optimistically biased, because it is the maximum over many noisy estimates. It is not a reliable estimate of test performance. Score the final model once on the held-out test set, or use nested cross-validation.