Sub topic 11
Persisting and resuming studies with a database
This chapter assumes you can write an objective function and run study.optimize, as covered in earlier chapters. You should also know basic Python and what a trial is.
Why in-memory studies are not enough
By default, create_study keeps everything in memory. If your script crashes, your laptop sleeps, or you close the notebook, every finished trial is lost. For tuning runs that take hours, this is costly.
Optuna solves this with a storage argument. Storage is the place where a study keeps its trials. Give it a database URL and each finished trial is written there as it completes.
Creating a persistent study
import optuna
study = optuna.create_study(
study_name="svc-tuning",
storage="sqlite:///optuna.db",
load_if_exists=True,
direction="maximize",
)Three arguments matter here:
storageis a database URL.sqlite:///optuna.dbcreates a SQLite file namedoptuna.dbin the current directory.study_nameidentifies the study inside the database. One database can hold many studies.load_if_exists=Truetells Optuna to reuse a study with that name if it exists. Without it, a second run raisesDuplicatedStudyError.
Resuming a run
Run the script again and Optuna loads the old trials. The new call to optimize adds to them. The sampler also sees the old results, so TPE continues from what it already learned.
import optuna
def objective(trial):
c = trial.suggest_float("c", 1e-3, 1e3, log=True)
return -((c - 10) ** 2)
study = optuna.create_study(
study_name="resume-demo",
storage="sqlite:///optuna.db",
load_if_exists=True,
direction="maximize",
)
print("Trials already stored:", len(study.trials))
study.optimize(objective, n_trials=10)
print("Trials now:", len(study.trials))On the first run you see 0 and then 10. On the second run you see 10 and then 20. Note that n_trials counts trials added in this call, not the total.
To load a study without risking creation of a new one, use optuna.load_study(study_name="resume-demo", storage="sqlite:///optuna.db"). It raises KeyError if the study does not exist.
Inspecting a stored study
You can read the results from any later session, without rerunning anything:
import optuna
study = optuna.load_study(study_name="resume-demo", storage="sqlite:///optuna.db")
print(study.best_params)
print(study.best_value)
print(len(study.trials))Common errors
- Changing the search space between runs. Old trials keep their original parameter ranges. If you change a distribution for a name that already exists, Optuna raises an error or warns, depending on the change. Use a new
study_namewhen the space changes. - Changing the direction. A study's direction is fixed when it is created. Loading it with a different direction raises an error.
- Forgetting to commit to the file path. A relative SQLite path depends on the working directory, so running from another folder creates a different empty database.
- Interrupted trials. A trial that was running when the process died stays in the
RUNNINGstate in the database. It does not count as finished, and it is not used as a result.
Exercise
You run a script with create_study(study_name="a", storage="sqlite:///optuna.db", direction="minimize") twice, with no load_if_exists. What happens on the second run, and how do you fix it?
Show answer
The second run raises optuna.exceptions.DuplicatedStudyError, because a study named "a" is already in the database. Add load_if_exists=True to continue the existing study, or use optuna.load_study to open it.
Exercise
A study already holds 40 finished trials. You call study.optimize(objective, n_trials=25) after loading it. How many trials does len(study.trials) report afterwards?
Show answer
65. The n_trials argument counts only the trials added by this call, so 25 new trials are added to the 40 stored ones.