Skip to content

StudyDataset

StudyDataset loads and saves data from/to an Optuna study.

kedro_datasets_experimental.optuna.StudyDataset

StudyDataset(
    *,
    backend,
    database,
    study_name,
    load_args=None,
    version=None,
    credentials=None,
    metadata=None
)

Bases: AbstractVersionedDataset[Study, Study]

StudyDataset loads/saves data from/to an optuna Study.

Examples:

Using the YAML API:

review_prediction_study:
  type: kedro_datasets_experimental.optuna.StudyDataset
  backend: sqlite
  database: data/05_model_input/review_prediction_study.db
  load_args:
    sampler:
      class: TPESampler
      n_startup_trials: 10
      n_ei_candidates: 5
    pruner:
      class: NopPruner
  versioned: true

price_prediction_study:
  type: kedro_datasets_experimental.optuna.StudyDataset
  backend: postgresql
  database: optuna_db
  credentials: dev_optuna_postgresql

Using the Python API:

>>> from kedro_datasets_experimental.optuna import StudyDataset
>>> from optuna.distributions import FloatDistribution
>>> import optuna
>>>
>>> study = optuna.create_study()
>>> trial = optuna.trial.create_trial(
...     params={"x": 2.0},
...     distributions={"x": FloatDistribution(0, 10)},
...     value=4.0,
... )
>>> study.add_trial(trial)
>>>
>>> dataset = StudyDataset(backend="sqlite", database="optuna.db")
>>> dataset.save(study)
>>> reloaded = dataset.load()
>>> assert len(reloaded.trials) == 1
>>> assert reloaded.trials[0].params["x"] == 2.0

Parameters:

  • backend (str) –

    Name of the database backend. This name should correspond to a module in SQLAlchemy.

  • database (str) –

    Name of the database.

  • study_name (str) –

    Name of the optuna Study.

  • load_args (dict[str, Any] | None, default: None ) –

    Optuna options for loading studies. Accepts a sampler and a pruner. If either are provided, a class matching any Optuna sampler, respecitively pruner class name should be provided, optionally with their argyments. Here you can find all available samplers and pruners and their arguments: - https://optuna.readthedocs.io/en/stable/reference/samplers/index.html - https://optuna.readthedocs.io/en/stable/reference/pruners.html All defaults are preserved.

  • version (Version, default: None ) –

    If specified, should be an instance of kedro.io.core.Version. If its load attribute is None, the latest version will be loaded. If its save attribute is None, save version will be autogenerated.

  • credentials (dict[str, Any] | None, default: None ) –

    Credentials required to get access to the underlying RDB. They can include username, password, host, and port.

  • metadata (dict[str, Any] | None, default: None ) –

    Any arbitrary metadata. This is ignored by Kedro, but may be consumed by users or external plugins.

Source code in kedro_datasets_experimental/optuna/study_dataset.py
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
def __init__(  # noqa: PLR0913
    self,
    *,
    backend: str,
    database: str,
    study_name: str,
    load_args: dict[str, Any] | None = None,
    version: Version = None,
    credentials: dict[str, Any] | None = None,
    metadata: dict[str, Any] | None = None,
) -> None:
    """Creates a new instance of ``StudyDataset`` pointing to a concrete optuna
    Study on a specific relational database.

    Args:
        backend: Name of the database backend. This name should correspond to a module
            in ``SQLAlchemy``.
        database: Name of the database.
        study_name: Name of the optuna Study.
        load_args: Optuna options for loading studies. Accepts a `sampler` and a
            `pruner`. If either are provided, a `class` matching any Optuna `sampler`,
            respecitively `pruner` class name should be provided, optionally with
            their argyments. Here you can find all available samplers and pruners
            and their arguments:
            - https://optuna.readthedocs.io/en/stable/reference/samplers/index.html
            - https://optuna.readthedocs.io/en/stable/reference/pruners.html
            All defaults are preserved.
        version: If specified, should be an instance of
            ``kedro.io.core.Version``. If its ``load`` attribute is
            None, the latest version will be loaded. If its ``save``
            attribute is None, save version will be autogenerated.
        credentials: Credentials required to get access to the underlying RDB.
            They can include `username`, `password`, `host`, and `port`.
        metadata: Any arbitrary metadata.
            This is ignored by Kedro, but may be consumed by users or external plugins.
    """
    self._backend = self._validate_backend(backend=backend)
    self._database = self._validate_database(backend=backend, database=database)
    self._study_name = self._validate_study_name(study_name=study_name)

    credentials = self._validate_credentials(backend=backend, credentials=credentials)
    storage_url = URL.create(
        drivername=backend,
        database=database,
        **credentials,
    )

    self._storage_url = storage_url
    self.metadata = metadata

    filepath = None
    if backend == "sqlite":
        filepath = PurePosixPath(os.path.realpath(database))

    super().__init__(
        filepath=filepath,
        version=version,
        exists_function=self._study_name_exists,
        glob_function=self._study_name_glob,
    )

    # Handle default load and save and fs arguments
    self._load_args = {**self.DEFAULT_LOAD_ARGS, **(load_args or {})}

DEFAULT_LOAD_ARGS class-attribute instance-attribute

DEFAULT_LOAD_ARGS = {'sampler': None, 'pruner': None}

metadata instance-attribute

metadata = metadata

load

load()
Source code in kedro_datasets_experimental/optuna/study_dataset.py
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
def load(self) -> optuna.Study:
    load_args = deepcopy(self._load_args)
    sampler_config = load_args.pop("sampler")
    sampler = self._get_sampler(sampler_config)

    pruner_config = load_args.pop("pruner")
    pruner = self._get_pruner(pruner_config)

    storage_url_str = self._storage_url.render_as_string(hide_password=False)
    storage = optuna.storages.RDBStorage(url=storage_url_str)
    study = optuna.load_study(
        storage=storage,
        study_name=self._get_load_study_name(),
        sampler=sampler,
        pruner=pruner,
    )

    return study

resolve_load_version

resolve_load_version()

Compute the version the dataset should be loaded with.

Source code in kedro_datasets_experimental/optuna/study_dataset.py
184
185
186
187
188
189
190
def resolve_load_version(self) -> str | None:
    """Compute the version the dataset should be loaded with."""
    if not self._version:
        return None
    if self._version.load:
        return self._version.load
    return self._fetch_latest_load_version()

save

save(study)
Source code in kedro_datasets_experimental/optuna/study_dataset.py
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
def save(self, study: optuna.Study) -> None:
    save_study_name = self._get_save_study_name()

    storage_url_str = self._storage_url.render_as_string(hide_password=False)
    if self._backend == "sqlite":
        os.makedirs(os.path.dirname(self._filepath), exist_ok=True)

        if not os.path.isfile(self._filepath):
            optuna.create_study(
                storage=storage_url_str,
            )

    storage = optuna.storages.RDBStorage(url=storage_url_str)

    # To overwrite an existing study, we need to first delete it if it exists
    if self._study_name_exists(save_study_name):
        optuna.delete_study(
            storage=storage,
            study_name=save_study_name,
        )

    optuna.copy_study(
        from_study_name=study.study_name,
        from_storage=study._storage,
        to_storage=storage,
        to_study_name=save_study_name,
    )