Note
Go to the end to download the full example code
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: 11.838831059924171 and parameters: {'x': 5.440760244469843}. Best is trial 0 with value: 11.838831059924171.
Trial 1 finished with value: 132.03904292750383 and parameters: {'x': -9.490824292778296}. Best is trial 0 with value: 11.838831059924171.
Trial 2 finished with value: 24.80339453737208 and parameters: {'x': 6.9803006472874785}. Best is trial 0 with value: 11.838831059924171.
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: 0.05659761114588827 and parameters: {'x': 1.762097475536958}. Best is trial 3 with value: 0.05659761114588827.
Trial 4 finished with value: 125.49550631203114 and parameters: {'x': -9.202477686299185}. Best is trial 3 with value: 0.05659761114588827.
Trial 5 finished with value: 75.65002879203274 and parameters: {'x': -6.69770250077759}. Best is trial 3 with value: 0.05659761114588827.
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
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 11.838831 5.440760 COMPLETE
1 1 132.039043 -9.490824 COMPLETE
2 2 24.803395 6.980301 COMPLETE
3 3 0.056598 1.762097 COMPLETE
4 4 125.495506 -9.202478 COMPLETE
5 5 75.650029 -6.697703 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.762097475536958}
Best value: 0.05659761114588827
Best Trial: FrozenTrial(number=3, state=1, values=[0.05659761114588827], datetime_start=datetime.datetime(2023, 10, 17, 7, 28, 54, 87023), datetime_complete=datetime.datetime(2023, 10, 17, 7, 28, 54, 113364), params={'x': 1.762097475536958}, 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=[11.838831059924171], datetime_start=datetime.datetime(2023, 10, 17, 7, 28, 53, 920815), datetime_complete=datetime.datetime(2023, 10, 17, 7, 28, 53, 958418), params={'x': 5.440760244469843}, 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=[132.03904292750383], datetime_start=datetime.datetime(2023, 10, 17, 7, 28, 53, 978933), datetime_complete=datetime.datetime(2023, 10, 17, 7, 28, 53, 998226), params={'x': -9.490824292778296}, 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=[24.80339453737208], datetime_start=datetime.datetime(2023, 10, 17, 7, 28, 54, 14301), datetime_complete=datetime.datetime(2023, 10, 17, 7, 28, 54, 33773), params={'x': 6.9803006472874785}, 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=[0.05659761114588827], datetime_start=datetime.datetime(2023, 10, 17, 7, 28, 54, 87023), datetime_complete=datetime.datetime(2023, 10, 17, 7, 28, 54, 113364), params={'x': 1.762097475536958}, 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=[125.49550631203114], datetime_start=datetime.datetime(2023, 10, 17, 7, 28, 54, 131902), datetime_complete=datetime.datetime(2023, 10, 17, 7, 28, 54, 151733), params={'x': -9.202477686299185}, 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=[75.65002879203274], datetime_start=datetime.datetime(2023, 10, 17, 7, 28, 54, 167548), datetime_complete=datetime.datetime(2023, 10, 17, 7, 28, 54, 186619), params={'x': -6.69770250077759}, 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.666 seconds)