命令行界面

命令

描述

ask

创建一个新的 trial 并建议参数。

best-trial

显示最佳 trial。

best-trials

显示位于帕累托前沿的 trial 列表。

create-study

创建一个新的 study。

delete-study

删除指定的 study。

storage upgrade

升级 storage 的 schema。

studies

显示 study 列表。

study set-user-attr

为 study 设置用户属性。

tell

完成由 ask 命令创建的 trial。

trials

显示 trial 列表。

Optuna 提供如上表所示的命令行界面。

假设您不在 IPython shell 中,而是正在编写 Python 脚本文件。编写如下脚本完全没问题

import optuna


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


if __name__ == "__main__":
    study = optuna.create_study()
    study.optimize(objective, n_trials=100)
    print("Best value: {} (params: {})\n".format(study.best_value, study.best_params))
Best value: 2.165817188862262e-05 (params: {'x': 1.9953461658937364})

然而,如果我们不能在 Python 代码中显式地编写 objective,比如在实验室开发新药,那么交互式方式就很适合。在 Optuna CLI 中,Ask-and-Tell 接口 风格的命令提供了这种交互式且灵活的接口。

假设我们在 \([-10, 10]\) 范围内,根据参数 x 来最小化目标值,并且目标值是通过一些手工实验计算得出的。即使如此,我们也可以如下调用优化。暂时不用管 --storage sqlite:///example.db,这将在 使用 RDB 后端保存/恢复 Study 中进行描述。

$ STUDY_NAME=`optuna create-study --storage sqlite:///example.db`
$ optuna ask --storage sqlite:///example.db --study-name $STUDY_NAME --sampler TPESampler \
     --search-space '{"x": {"name": "FloatDistribution", "attributes": {"step": null, "low": -10.0, "high": 10.0, "log": false}}}'


[I 2022-08-20 06:08:53,158] Asked trial 0 with parameters {'x': 2.512238141966016}.
{"number": 0, "params": {"x": 2.512238141966016}}

例如,可以使用 optuna.distributions.distribution_to_json() 生成 --search-space 选项的参数,例如 optuna.distributions.distribution_to_json(optuna.distributions.FloatDistribution(-10, 10))。有关参数的详细解释,请参考 optuna.distributions.FloatDistributionoptuna.distributions.IntDistribution

在实验室中使用建议的参数进行实验后,我们如下将结果存储到 Optuna 的 study 中

$ optuna tell --storage sqlite:///example.db --study-name $STUDY_NAME --trial-number 0 --values 0.7 --state complete
[I 2022-08-20 06:22:50,888] Told trial 0 with values [0.7] and state TrialState.COMPLETE.

脚本总运行时间: (0 分 0.098 秒)

由 Sphinx-Gallery 生成的画廊