Sub topic 17
Best practices and common pitfalls
This chapter collects habits that keep Optuna results trustworthy. It assumes you can write an objective function, define search spaces with suggest_*, and have read the earlier chapters on pruning, storage and visualisation. You should also know how train/validation splits and cross-validation work.
Keep the test set out of the search
Every trial is scored on validation data, and the sampler uses those scores to choose the next trial. After many trials the best score is optimistic, because the search has partly fitted the validation split. This is overfitting to the validation data.
The fix is to hold out a test set that the search never sees. Tune on the development data only, refit once with the best parameters, and score on the test set once.
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_dev, X_test, y_dev, y_test = train_test_split(
X, y, test_size=0.2, random_state=0, stratify=y
)
def objective(trial):
model = RandomForestClassifier(
n_estimators=trial.suggest_int("n_estimators", 50, 300, step=50),
max_depth=trial.suggest_int("max_depth", 2, 16),
min_samples_leaf=trial.suggest_int("min_samples_leaf", 1, 10),
random_state=0,
)
return cross_val_score(model, X_dev, y_dev, cv=5).mean()
optuna.logging.set_verbosity(optuna.logging.WARNING)
sampler = optuna.samplers.TPESampler(seed=42)
study = optuna.create_study(direction="maximize", sampler=sampler)
study.optimize(objective, n_trials=25)
final = RandomForestClassifier(random_state=0, **study.best_params)
final.fit(X_dev, y_dev)
print("cross-validated best:", round(study.best_value, 4))
print("test score:", round(final.score(X_test, y_test), 4))Expect the test score to be a little lower than the cross-validated best, or at least not reliably higher. A large gap means the search has overfit, or the validation scheme is too noisy.
If you must report an unbiased estimate of the whole tuning procedure on a small dataset, use nested cross-validation. Run a full study inside each outer fold. This costs many more trials, so use it only when a single held-out set is too small.
Design the search space with care
The search space decides how much the search can find. These are the common mistakes.
- Linear scale for scale-like parameters. Learning rates, regularisation strengths and
Cspan orders of magnitude. Uselog=True. A linear range of 1e-5 to 1 puts about 90% of the samples above 0.1. - Ranges that are too wide. Each extra decade of range dilutes the trial budget. Start from known sensible values.
- Best value on the boundary. If the best trial sits at the edge of a range, the true optimum is probably outside it. Widen that range and continue.
- Parameters that do nothing. Searching a parameter that has no effect adds noise. The importance plot can reveal these.
- Changing a parameter's distribution under the same name. In one study, a name such as
"lr"must always keep the same distribution. If you change the range, start a new study, or give the parameter a new name.
Narrow the space in stages. Run a broad study, look at plot_param_importances and plot_slice, then start a second study with tighter ranges on the parameters that mattered.
Spend the trial budget deliberately
TPE needs some random-looking early trials before its model is useful. By default TPESampler uses 10 startup trials. With a budget of 20 trials, half of the search is close to random search. Below roughly 30 to 50 trials, a fixed grid or plain random search can be just as good.
Use timeout when wall-clock time matters more than trial count. You can set both. The study stops at whichever limit is reached first.
study.optimize(objective, n_trials=200, timeout=600)Handle failures in the objective
By default, an exception in the objective stops the whole optimize call. For known, harmless failures, such as an invalid parameter combination, tell Optuna to record the trial as failed and carry on.
import optuna
def objective(trial):
x = trial.suggest_float("x", -2, 2)
if x < 0:
raise ValueError("negative x is not supported")
return (x - 1) ** 2
optuna.logging.set_verbosity(optuna.logging.WARNING)
study = optuna.create_study(direction="minimize")
study.optimize(objective, n_trials=20, catch=(ValueError,))
states = [t.state.name for t in study.trials]
print(states.count("COMPLETE"), "complete,", states.count("FAIL"), "failed")Catch only the exceptions you expect. A broad catch=(Exception,) hides real bugs, and a study whose trials all fail has no best_trial.
Returning float("nan") also marks a trial as failed. A diverged model should therefore return nan or raise. Do not return a made-up large number, because the sampler would treat it as a real observation.
Use pruning correctly
- Call
trial.report(value, step)with a strictly increasing, meaningful step such as the epoch, and always report the same metric. - Report on the same data you return at the end. If you report the training loss but return the validation score, the pruner compares unlike quantities.
- Pruning needs intermediate values. Calling
cross_val_scoreas a single call gives you none. To prune with cross-validation, run the folds in a loop and report the running mean after each fold. - Warm-up settings matter. With
MedianPruner, setn_startup_trialsandn_warmup_stepsso that noisy early steps do not kill good trials. - A pruned trial is not a failure. It counts toward
n_trialsand appears instudy.trialswith statePRUNED. Usestudy.get_trials(states=[optuna.trial.TrialState.COMPLETE])when you need only finished trials.
Make runs reproducible, within limits
Seed the sampler (TPESampler(seed=...)) and the model (random_state=...). Both are needed, because the sampler only controls which parameters are suggested, not what the model does with them.
Seeding does not give identical results in these cases.
| Situation | Why results can differ |
|---|---|
| Parallel workers (`n_jobs > 1` or several processes) | The order in which trials finish changes what the sampler sees. |
| Timing-based pruning or `timeout` | Machine speed changes how many trials run. |
| Non-deterministic libraries (some GPU operations) | The objective is not repeatable for the same parameters. |
| Resuming a stored study | The sampler state is not restored, so a seeded sampler restarts its random stream. |
For results you must be able to audit, record study.best_params, the library versions and the data split. Store the study in a database so the full trial history is kept.
Storage and parallel pitfalls
- An in-memory study disappears when the process ends. Use
storage="sqlite:///optuna.db"withload_if_exists=Truefor anything you cannot afford to lose. - SQLite is fine for a few workers on one machine. With many workers or several machines, use a client-server database such as PostgreSQL or MySQL. SQLite locks the file on writes and can produce "database is locked" errors.
- Do not share one
studyobject across processes. Each process should load the study by name from shared storage. - Parallel workers cannot see trials that are still running, so TPE may suggest similar parameters to several workers at once. Keep the worker count small relative to the total trial count.
Read the results before trusting them
Before refitting, look at the optimisation history and the importance plots.
- A history that is still improving at the last trial means the budget was too small.
- A history that is flat after a few trials means the space is too easy or the metric is insensitive.
- A very small spread between the best and median trial suggests the metric is mostly noise, and a different set of parameters would do equally well.
- If the metric is noisy, prefer a simpler or more regular configuration among the near-best trials. Do not pick the single top trial by a tiny margin.
Quick checklist
- Split off a test set before any tuning.
- Use
log=Truefor scale-like parameters, and widen ranges whose best value sits at an edge. - Seed both the sampler and the model.
- Catch only expected exceptions, and return nan or raise for diverged runs.
- Report a consistent metric at increasing steps when pruning.
- Store the study in a database and use a client-server database for many workers.
- Check the history and importance plots before trusting the best trial.
- Refit on all development data and score the test set once.
Exercise
A study with 15 trials, TPESampler(seed=1) and the default 10 startup trials finds a best value of 0.93 at the upper boundary of max_depth. Give two problems with this setup and one change for each.
Show answer
First, only about 5 trials are guided by the TPE model, so the search behaves almost like random search. Raise the budget to 50 or more trials, or use plain random search for such a small budget. Second, the best value sits on the boundary of max_depth, so the true optimum is probably higher. Widen the upper limit of max_depth and run again. As an additional check, the 0.93 comes from validation scores, so confirm it once on a held-out test set.
Exercise
You call cross_val_score(model, X, y, cv=5).mean() inside an objective and want to prune weak trials early. Why does trial.should_prune() never fire, and how do you fix it?
Show answer
The pruner only compares values that were passed to trial.report(value, step). A single cross_val_score call reports nothing, so there is nothing to compare. Fix it by looping over the folds yourself, for example with KFold. After each fold, report the running mean score with the fold index as the step, call trial.should_prune(), and raise optuna.TrialPruned() if it returns True. Return the mean over all folds at the end.