Sub topic 2
Studies and trials: the core objects
This chapter assumes you can write Python functions and handle exceptions. It also assumes you know the difference between parameters and hyperparameters, and that you have validated a scikit-learn model with a train/validation split or cross-validation. Optuna has two central objects. If you know what each one owns, most of the rest of the library is easy to follow.
The two objects and who owns what
A study is one optimisation job. It holds the direction (minimise or maximise), the sampler that proposes parameters, the pruner that stops weak runs, and the full history of attempts.
A trial is one attempt inside a study. It is a single evaluation of your objective function with one set of hyperparameter values. The study creates a trial, passes it to your function, and records what comes back.
The study is the long-lived record. A trial is short-lived and mostly exists while your function runs.
| Question | Where to look |
|---|---|
| Are we minimising or maximising? | Study |
| Which algorithm proposes values? | Study (its sampler) |
| What was the best result so far? | Study |
| Which values did this attempt use? | Trial |
| What score did this attempt get? | Trial |
| Was this attempt stopped early? | Trial |
The smallest working study
This example minimises a one-variable function. Run it, because the sections below inspect what it produces.
import optuna
def objective(trial):
x = trial.suggest_float("x", -10, 10)
return (x - 2) ** 2
study = optuna.create_study(direction="minimize")
study.optimize(objective, n_trials=50)
print(study.best_params)
print(study.best_value)create_study builds the study. optimize runs the loop: ask the sampler for values, call objective with a fresh trial, and store the returned number. After 50 rounds, best_params and best_value summarise the winner. The best value should be close to 0, with x near 2.
direction defaults to "minimize". If you tune an accuracy score and forget direction="maximize", Optuna searches for the worst model. Nothing warns you, because the code is valid.
What happens in one trial
Each call to your objective follows the same cycle.
These states are the members of optuna.trial.TrialState:
RUNNING: the objective is executing now.COMPLETE: the objective returned a valid value.PRUNED: the objective raisedoptuna.TrialPruned. Pruning is covered in a later chapter.FAIL: the objective raised another exception, or returnednan.WAITING: the trial was queued with fixed values and has not started. This also appears later.
Only COMPLETE trials can be the best trial. Pruned and failed trials stay in the history but never win.
Reading a study after the run
The study keeps every trial. Each stored trial is a FrozenTrial, a read-only snapshot you can inspect freely.
import optuna
from optuna.trial import TrialState
optuna.logging.set_verbosity(optuna.logging.WARNING)
def objective(trial):
x = trial.suggest_float("x", -10, 10)
trial.set_user_attr("abs_x", abs(x))
return (x - 2) ** 2
study = optuna.create_study(direction="minimize", study_name="demo")
study.optimize(objective, n_trials=20)
study.optimize(objective, n_trials=10)
print(len(study.trials))
best = study.best_trial
print(best.number, best.state, best.params, best.value, best.user_attrs)
done = study.get_trials(states=(TrialState.COMPLETE,))
print(len(done))
first = study.trials[0]
print(first.datetime_start, first.datetime_complete)
print(first.distributions)Several points are worth noting:
- The first
printshows 30, not 10. Callingoptimizeagain continues the same study. Then_trialsargument counts trials in that call only. best_trial.numberis the zero-based index of the trial in the study. It matches the position instudy.trials.paramsis a dictionary of the values the trial chose.valueis the returned score. Multi-objective studies usevalues(plural), andvalueis not available for them. They are covered in a later chapter.distributionsrecords the range each parameter was drawn from. Optuna uses this to compare parameters across trials.user_attrsholds anything you attach withtrial.set_user_attr. Use it for facts you want to keep but not optimise, such as training time or a fold-by-fold score breakdown.
If pandas is installed, study.trials_dataframe() returns the same history as a table, with one row per trial. This is often the quickest way to sort and filter results.
What `optimize` does with errors and limits
study.optimize takes more than n_trials:
| Argument | Effect |
|---|---|
| `n_trials` | Stop after this many trials in this call. |
| `timeout` | Stop starting new trials after this many seconds. |
| `catch` | A tuple of exception types. Matching errors mark the trial `FAIL` and the loop continues. |
| `callbacks` | Functions called after each trial with the study and the finished trial. |
If neither n_trials nor timeout is set, the loop runs until you interrupt it.
By default, an exception in your objective is marked FAIL and then re-raised, which stops the whole optimize call. This is deliberate, because a bug in your code should not hide behind 100 silent failures. If some parameter combinations legitimately crash, for example an invalid solver and penalty pairing, catch only that error:
study.optimize(objective, n_trials=50, catch=(ValueError,))Do not catch Exception broadly. You would lose the signal from real bugs.
The failure state also covers a returned nan. A model that diverges and produces nan is recorded as FAIL, not as a very bad score.
Where the study lives: storage
By default, a study exists only in memory. It disappears when the Python process ends. To keep it, pass a storage URL and a name:
import optuna
study = optuna.create_study(
study_name="svc-tuning",
storage="sqlite:///optuna.db",
load_if_exists=True,
direction="maximize",
)With load_if_exists=True, running the script again attaches to the existing study and keeps adding trials. Without it, creating a study with a name that already exists raises DuplicatedStudyError. To open a study without creating one, use optuna.load_study(study_name="svc-tuning", storage="sqlite:///optuna.db").
A later chapter covers storage and parallel runs in full. For now, remember that the study object is a view onto a storage backend, and the trials belong to the storage.
Common errors
- Wrong direction. Check
study.directionif results look backwards. - Reading
best_valuebefore any trial completes. If every trial failed or was pruned,best_trialraisesValueError. Check for completed trials first. - Assuming a second
optimizecall starts fresh. It does not. Make a new study if you want a clean slate. - Reusing a study name against old storage. The sampler will learn from earlier trials, including ones from a different search space or objective. Use a new name when the problem changes.
- Storing large objects in
user_attrs. Each value is saved to the storage. Keep to small, serialisable values such as numbers and short strings.
Exercise
You run study.optimize(objective, n_trials=20), and 3 of those trials are pruned and 2 raise a ValueError that you did not catch. What happens, and how many trials are in study.trials if the ValueError first occurs on the 8th trial of the call?
Show answer
An uncaught ValueError stops the optimize call at once. The failing trial is stored with state FAIL, and the exception is re-raised. The study therefore holds 8 trials: the 7 earlier ones (some of which may be PRUNED or COMPLETE) and the failed 8th. The remaining 12 trials never run. Passing catch=(ValueError,) would let the loop continue, and the study would then hold all 20 trials, with the two ValueError trials marked FAIL.
Exercise
A script uses create_study(study_name="exp", storage="sqlite:///exp.db", direction="maximize") and is run twice. What happens on the second run, and which argument fixes it if you want to continue the study?
Show answer
The second run raises DuplicatedStudyError, because a study named "exp" already exists in that database. Adding load_if_exists=True makes create_study load the existing study and continue adding trials to it.