Saving/Resuming Study with RDB Backend

An RDB backend enables persistent experiments (i.e., to save and resume a study) as well as access to history of studies. In addition, we can run multi-node optimization tasks with this feature, which is described in Easy Parallelization.

In this section, let’s try simple examples running on a local environment with SQLite DB.

Note

You can also utilize other RDB backends, e.g., PostgreSQL or MySQL, by setting the storage argument to the DB’s URL. Please refer to SQLAlchemy’s document for how to set up the URL.

New Study

We can create a persistent study by calling create_study() function as follows. An SQLite file example.db is automatically initialized with a new study record.

import logging
import sys

import optuna

# Add stream handler of stdout to show the messages
optuna.logging.get_logger("optuna").addHandler(logging.StreamHandler(sys.stdout))
study_name = "example-study"  # Unique identifier of the study.
storage_name = "sqlite:///{}.db".format(study_name)
study = optuna.create_study(study_name=study_name, storage=storage_name)
A new study created in RDB with name: example-study

To run a study, call optimize() method passing an objective function.

def objective(trial):
    x = trial.suggest_float("x", -10, 10)
    return (x - 2) ** 2


study.optimize(objective, n_trials=3)
Trial 0 finished with value: 65.88001960148613 and parameters: {'x': -6.11665076256741}. Best is trial 0 with value: 65.88001960148613.
Trial 1 finished with value: 91.23079783728012 and parameters: {'x': -7.551481447256238}. Best is trial 0 with value: 65.88001960148613.
Trial 2 finished with value: 56.757816728887825 and parameters: {'x': 9.533778383313901}. Best is trial 2 with value: 56.757816728887825.

Resume Study

To resume a study, instantiate a Study object passing the study name example-study and the DB URL sqlite:///example-study.db.

study = optuna.create_study(study_name=study_name, storage=storage_name, load_if_exists=True)
study.optimize(objective, n_trials=3)
Using an existing study with name 'example-study' instead of creating a new one.
Trial 3 finished with value: 14.248445213226551 and parameters: {'x': -1.7747112754787686}. Best is trial 3 with value: 14.248445213226551.
Trial 4 finished with value: 48.78107871067928 and parameters: {'x': 8.98434525998531}. Best is trial 3 with value: 14.248445213226551.
Trial 5 finished with value: 38.01758418076032 and parameters: {'x': -4.165840103405238}. Best is trial 3 with value: 14.248445213226551.

Note that the storage doesn’t store the state of the instance of samplers and pruners. When we resume a study with a sampler whose seed argument is specified for reproducibility, you need to restore the sampler with using pickle as follows:

import pickle

# Save the sampler with pickle to be loaded later.
with open("sampler.pkl", "wb") as fout:
    pickle.dump(study.sampler, fout)

restored_sampler = pickle.load(open("sampler.pkl", "rb"))
study = optuna.create_study(
    study_name=study_name, storage=storage_name, load_if_exists=True, sampler=restored_sampler
)
study.optimize(objective, n_trials=3)

Experimental History

Note that this section requires the installation of Pandas:

$ pip install pandas

We can access histories of studies and trials via the Study class. For example, we can get all trials of example-study as:

study = optuna.create_study(study_name=study_name, storage=storage_name, load_if_exists=True)
df = study.trials_dataframe(attrs=("number", "value", "params", "state"))
Using an existing study with name 'example-study' instead of creating a new one.

The method trials_dataframe() returns a pandas dataframe like:

print(df)
   number      value  params_x     state
0       0  65.880020 -6.116651  COMPLETE
1       1  91.230798 -7.551481  COMPLETE
2       2  56.757817  9.533778  COMPLETE
3       3  14.248445 -1.774711  COMPLETE
4       4  48.781079  8.984345  COMPLETE
5       5  38.017584 -4.165840  COMPLETE

A Study object also provides properties such as trials, best_value, best_params (see also Lightweight, versatile, and platform agnostic architecture).

print("Best params: ", study.best_params)
print("Best value: ", study.best_value)
print("Best Trial: ", study.best_trial)
print("Trials: ", study.trials)
Best params:  {'x': -1.7747112754787686}
Best value:  14.248445213226551
Best Trial:  FrozenTrial(number=3, state=1, values=[14.248445213226551], datetime_start=datetime.datetime(2025, 4, 14, 5, 24, 41, 831434), datetime_complete=datetime.datetime(2025, 4, 14, 5, 24, 41, 853309), params={'x': -1.7747112754787686}, user_attrs={}, system_attrs={}, intermediate_values={}, distributions={'x': FloatDistribution(high=10.0, log=False, low=-10.0, step=None)}, trial_id=4, value=None)
Trials:  [FrozenTrial(number=0, state=1, values=[65.88001960148613], datetime_start=datetime.datetime(2025, 4, 14, 5, 24, 41, 697238), datetime_complete=datetime.datetime(2025, 4, 14, 5, 24, 41, 726941), params={'x': -6.11665076256741}, user_attrs={}, system_attrs={}, intermediate_values={}, distributions={'x': FloatDistribution(high=10.0, log=False, low=-10.0, step=None)}, trial_id=1, value=None), FrozenTrial(number=1, state=1, values=[91.23079783728012], datetime_start=datetime.datetime(2025, 4, 14, 5, 24, 41, 743587), datetime_complete=datetime.datetime(2025, 4, 14, 5, 24, 41, 758841), params={'x': -7.551481447256238}, user_attrs={}, system_attrs={}, intermediate_values={}, distributions={'x': FloatDistribution(high=10.0, log=False, low=-10.0, step=None)}, trial_id=2, value=None), FrozenTrial(number=2, state=1, values=[56.757816728887825], datetime_start=datetime.datetime(2025, 4, 14, 5, 24, 41, 771739), datetime_complete=datetime.datetime(2025, 4, 14, 5, 24, 41, 786205), params={'x': 9.533778383313901}, user_attrs={}, system_attrs={}, intermediate_values={}, distributions={'x': FloatDistribution(high=10.0, log=False, low=-10.0, step=None)}, trial_id=3, value=None), FrozenTrial(number=3, state=1, values=[14.248445213226551], datetime_start=datetime.datetime(2025, 4, 14, 5, 24, 41, 831434), datetime_complete=datetime.datetime(2025, 4, 14, 5, 24, 41, 853309), params={'x': -1.7747112754787686}, user_attrs={}, system_attrs={}, intermediate_values={}, distributions={'x': FloatDistribution(high=10.0, log=False, low=-10.0, step=None)}, trial_id=4, value=None), FrozenTrial(number=4, state=1, values=[48.78107871067928], datetime_start=datetime.datetime(2025, 4, 14, 5, 24, 41, 868316), datetime_complete=datetime.datetime(2025, 4, 14, 5, 24, 41, 882680), params={'x': 8.98434525998531}, user_attrs={}, system_attrs={}, intermediate_values={}, distributions={'x': FloatDistribution(high=10.0, log=False, low=-10.0, step=None)}, trial_id=5, value=None), FrozenTrial(number=5, state=1, values=[38.01758418076032], datetime_start=datetime.datetime(2025, 4, 14, 5, 24, 41, 894987), datetime_complete=datetime.datetime(2025, 4, 14, 5, 24, 41, 909875), params={'x': -4.165840103405238}, user_attrs={}, system_attrs={}, intermediate_values={}, distributions={'x': FloatDistribution(high=10.0, log=False, low=-10.0, step=None)}, trial_id=6, value=None)]

Total running time of the script: (0 minutes 0.887 seconds)

Gallery generated by Sphinx-Gallery