optuna.study.Study

class optuna.study.Study(study_name, storage, sampler=None, pruner=None)[源代码]

一个研究对应于一个优化任务,即一组试验。

此对象提供运行新 Trial 的接口,访问试验历史记录,设置/获取研究本身的用户定义属性。

请注意,不推荐直接使用此构造函数。要创建和加载研究,请分别参考 create_study()load_study() 的文档。

方法

add_trial(trial)

将试用添加到研究中。

add_trials(trials)

将试验添加到研究中。

ask([fixed_distributions])

从新试验中可以建议超参数。

enqueue_trial(params[, user_attrs, ...])

使用给定的参数值将试验加入队列。

get_trials([deepcopy, states])

返回研究中的所有试验。

optimize(func[, n_trials, timeout, n_jobs, ...])

优化一个目标函数。

set_metric_names(metric_names)

设置指标名称。

set_system_attr(key, value)

将系统属性设置为研究对象。

set_user_attr(key, value)

为研究设置一个用户属性。

stop()

在当前优化循环中的运行试验完成后退出。

tell(trial[, values, state, skip_if_finished])

完成使用 ask() 创建的试验。

trials_dataframe([attrs, multi_index])

将试验导出为 pandas DataFrame

属性

best_params

返回研究中最佳试验的参数。

best_trial

返回研究中的最佳试验。

best_trials

返回研究中位于帕累托前沿的试验。

best_value

返回研究中的最佳目标值。

direction

返回研究的方向。

directions

返回研究的方向。

metric_names

返回指标名称。

system_attrs

返回系统属性。

trials

返回研究中的所有试验。

user_attrs

返回用户属性。

参数:
  • study_name (str)

  • storage (str | storages.BaseStorage)

  • sampler ('samplers.BaseSampler' | None)

  • pruner (pruners.BasePruner | None)

add_trial(trial)[源代码]

将试用添加到研究中。

试验在添加之前会进行验证。

示例

import optuna
from optuna.distributions import FloatDistribution


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


study = optuna.create_study()
assert len(study.trials) == 0

trial = optuna.trial.create_trial(
    params={"x": 2.0},
    distributions={"x": FloatDistribution(0, 10)},
    value=4.0,
)

study.add_trial(trial)
assert len(study.trials) == 1

study.optimize(objective, n_trials=3)
assert len(study.trials) == 4

other_study = optuna.create_study()

for trial in study.trials:
    other_study.add_trial(trial)
assert len(other_study.trials) == len(study.trials)

other_study.optimize(objective, n_trials=2)
assert len(other_study.trials) == len(study.trials) + 2

参见

此方法通常应用于添加已经评估过的试验(trial.state.is_finished() == True)。如需将试验加入评估队列,请参考 enqueue_trial()

参见

参见 create_trial() 了解如何创建试验。

参见

请参考 第二种场景:让 Optuna 利用已经评估过的超参数 以获取手动指定评估值的超参数教程。

参数:

trial (FrozenTrial) – 尝试添加。

返回类型:

None

add_trials(trials)[源代码]

将试验添加到研究中。

试验在添加之前会经过验证。

示例

import optuna


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


study = optuna.create_study()
study.optimize(objective, n_trials=3)
assert len(study.trials) == 3

other_study = optuna.create_study()
other_study.add_trials(study.trials)
assert len(other_study.trials) == len(study.trials)

other_study.optimize(objective, n_trials=2)
assert len(other_study.trials) == len(study.trials) + 2

参见

参见 add_trial() 以添加每个试验。

参数:

trials (Iterable[FrozenTrial]) – 待添加的试验。

返回类型:

None

ask(fixed_distributions=None)[源代码]

从新试验中可以建议超参数。

此方法是 optimize() 的替代方案的一部分,允许在 func 的作用域之外控制试验的生命周期。每次调用此方法后,应紧接着调用 tell() 以完成创建的试验。

参见

The 询问-告知接口 tutorial provides use-cases with examples.

示例

使用 ask() 方法获取试验对象。

import optuna


study = optuna.create_study()

trial = study.ask()

x = trial.suggest_float("x", -1, 1)

study.tell(trial, x**2)

示例

将先前定义的分布传递给 ask() 方法。

import optuna


study = optuna.create_study()

distributions = {
    "optimizer": optuna.distributions.CategoricalDistribution(["adam", "sgd"]),
    "lr": optuna.distributions.FloatDistribution(0.0001, 0.1, log=True),
}

# You can pass the distributions previously defined.
trial = study.ask(fixed_distributions=distributions)

# `optimizer` and `lr` are already suggested and accessible with `trial.params`.
assert "optimizer" in trial.params
assert "lr" in trial.params
参数:

fixed_distributions (dict[str, BaseDistribution] | None) – A dictionary containing the parameter names and parameter’s distributions. Each parameter in this dictionary is automatically suggested for the returned trial, even when the suggest method is not explicitly invoked by the user. If this argument is set to None, no parameter is automatically suggested.

返回:

一个 Trial

返回类型:

Trial

property best_params: dict[str, Any]

返回研究中最佳试验的参数。

备注

此功能仅可用于单目标优化。

返回:

包含最佳试验参数的字典。

property best_trial: FrozenTrial

返回研究中的最佳试验。

备注

此功能仅用于单目标优化。如果你的研究是多目标的,请改用 best_trials

返回:

最佳试验的 FrozenTrial 对象。

参见

The 重用最佳试验 tutorial provides a detailed example of how to use this method.

property best_trials: list[FrozenTrial]

返回研究中位于帕累托前沿的试验。

如果没有任何试验支配该试验,则该试验位于帕累托前沿。如果 all(v0 <= v1) for v0, v1 in zip(t0.values, t1.values)any(v0 < v1) for v0, v1 in zip(t0.values, t1.values) 成立,则称试验 t0 支配另一个试验 t1

返回:

一个 FrozenTrial 对象的列表。

property best_value: float

返回研究中的最佳目标值。

备注

此功能仅可用于单目标优化。

返回:

一个表示最佳目标值的浮点数。

property direction: StudyDirection

返回研究的方向。

备注

此功能仅可用于单目标优化。如果你的研究是多目标的,请使用 directions 代替。

返回:

一个 StudyDirection 对象。

property directions: list[StudyDirection]

返回研究的方向。

返回:

一个 StudyDirection 对象的列表。

enqueue_trial(params, user_attrs=None, skip_if_exists=False)[源代码]

使用给定的参数值将试验加入队列。

您可以修复下一个采样参数,这些参数将在您的目标函数中进行评估。

示例

import optuna


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


study = optuna.create_study()
study.enqueue_trial({"x": 5})
study.enqueue_trial({"x": 0}, user_attrs={"memo": "optimal"})
study.optimize(objective, n_trials=2)

assert study.trials[0].params == {"x": 5}
assert study.trials[1].params == {"x": 0}
assert study.trials[1].user_attrs == {"memo": "optimal"}
参数:
  • params (dict[str, Any]) – 传递给目标函数的参数值。

  • user_attrs (dict[str, Any] | None) – 一个包含用户特定属性(除了 params 之外)的字典。

  • skip_if_exists (bool) –

    When True, prevents duplicate trials from being enqueued again.

    备注

    如果在同一时间由多个进程同时调用并使用相同的 params 字典,此方法可能会产生重复的试验。

返回类型:

None

参见

请参考 第一个场景:使用 Optuna 评估你的超参数 以获取手动指定超参数的教程。

get_trials(deepcopy=True, states=None)[源代码]

返回研究中的所有试验。

返回的试验按试验编号排序。

参见

相关属性请参见 trials

示例

import optuna


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


study = optuna.create_study()
study.optimize(objective, n_trials=3)

trials = study.get_trials()
assert len(trials) == 3
参数:
  • deepcopy (bool) – Flag to control whether to apply copy.deepcopy() to the trials. Note that if you set the flag to False, you shouldn’t mutate any fields of the returned trial. Otherwise the internal state of the study may corrupt and unexpected behavior may happen.

  • states (Container[TrialState] | None) – Trial states to filter on. If None, include all states.

返回:

一个 FrozenTrial 对象的列表。

返回类型:

list[FrozenTrial]

property metric_names: list[str] | None

返回指标名称。

备注

使用 set_metric_names() 首先设置指标名称。

返回:

目标函数返回值的每个维度的名称列表。

optimize(func, n_trials=None, timeout=None, n_jobs=1, catch=(), callbacks=None, gc_after_trial=False, show_progress_bar=False)[源代码]

优化一个目标函数。

优化是通过从给定范围内选择一组合适超参数值来完成的。使用一个采样器,该采样器根据指定的分布实现值建议的任务。采样器在 create_study() 中指定,采样器的默认选择是 TPE。有关 ‘TPE’ 的更多详细信息,请参见 TPESampler

当接收到终止信号(如 SIGINT 和 SIGTERM)时,优化将会停止。与其他信号不同,当接收到 SIGINT(Ctrl+C)时,试验会自动且干净地失败。如果 n_jobs 大于一或使用了其他信号而非 SIGINT,中断的试验状态将不会被正确更新。

示例

import optuna


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


study = optuna.create_study()
study.optimize(objective, n_trials=3)
参数:
  • func (ObjectiveFuncType) – 实现目标函数的可调用对象。

  • n_trials (int | None) –

    The number of trials for each process. None represents no limit in terms of the number of trials. The study continues to create trials until the number of trials reaches n_trials, timeout period elapses, stop() is called, or a termination signal such as SIGTERM or Ctrl+C is received.

    参见

    optuna.study.MaxTrialsCallback 可以确保在所有进程中执行试验的次数。

  • timeout (float | None) – Stop study after the given number of second(s). None represents no limit in terms of elapsed time. The study continues to create trials until the number of trials reaches n_trials, timeout period elapses, stop() is called or, a termination signal such as SIGTERM or Ctrl+C is received.

  • n_jobs (int) –

    并行作业的数量。如果此参数设置为 -1,则作业数设置为 CPU 数量。

    备注

    n_jobs allows parallelization using threading and may suffer from Python’s GIL. It is recommended to use process-based parallelization if func is CPU bound.

  • catch (Iterable[type[Exception]] | type[Exception]) – 即使试验引发了此参数中指定的某个异常,研究仍会继续运行。默认值是一个空元组,即研究将停止任何异常,除了 TrialPruned

  • callbacks (Iterable[Callable[[Study, FrozenTrial], None]] | None) – 在每次试验结束时调用的回调函数列表。每个函数必须接受两个参数,其类型按以下顺序为:StudyFrozenTrial。 .. seealso:

  • gc_after_trial (bool) –

    Flag to determine whether to automatically run garbage collection after each trial. Set to True to run the garbage collection, False otherwise. When it runs, it runs a full collection by internally calling gc.collect(). If you see an increase in memory consumption over several trials, try setting this flag to True.

    参见

    内存不足-gc-收集

  • show_progress_bar (bool) – Flag to show progress bars or not. To show progress bar, set this True. Note that it is disabled when n_trials is None, timeout is not None, and n_jobs \(\ne 1\).

抛出:

RuntimeError – 如果此方法发生嵌套调用。

返回类型:

None

set_metric_names(metric_names)[源代码]

设置指标名称。

此方法为目标函数返回值的每个维度命名。在多目标优化中特别有用。指标名称主要由可视化函数引用。

示例

import optuna
import pandas


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


study = optuna.create_study(directions=["minimize", "minimize"])
study.set_metric_names(["x**2", "x+1"])
study.optimize(objective, n_trials=3)

df = study.trials_dataframe(multi_index=True)
assert isinstance(df, pandas.DataFrame)
assert list(df.get("values").keys()) == ["x**2", "x+1"]

参见

此方法设置的名称用于 trials_dataframe()plot_pareto_front()

参数:

metric_names (list[str]) – 目标函数的指标名称列表。

返回类型:

None

备注

作为实验性功能添加于 v3.2.0。接口可能会在新版本中发生变化,恕不另行通知。参见 https://github.com/optuna/optuna/releases/tag/v3.2.0

set_system_attr(key, value)[源代码]

将系统属性设置为研究对象。

请注意,Optuna 内部使用此方法来保存系统消息。请使用 set_user_attr() 来设置用户属性。

参数:
  • key (str) – 属性的关键字符串。

  • value (Any) – 属性的值。该值应为可JSON序列化的。

返回类型:

None

警告

在 v3.1.0 中已弃用。此功能将在未来被移除。该功能的移除目前计划在 v5.0.0 进行,但此时间表可能会更改。请参阅 https://github.com/optuna/optuna/releases/tag/v3.1.0

set_user_attr(key, value)[源代码]

为研究设置一个用户属性。

参见

相关属性请参见 user_attrs

参见

参见 用户属性 上的配方。

示例

import optuna


def objective(trial):
    x = trial.suggest_float("x", 0, 1)
    y = trial.suggest_float("y", 0, 1)
    return x**2 + y**2


study = optuna.create_study()

study.set_user_attr("objective function", "quadratic function")
study.set_user_attr("dimensions", 2)
study.set_user_attr("contributors", ["Akiba", "Sano"])

assert study.user_attrs == {
    "objective function": "quadratic function",
    "dimensions": 2,
    "contributors": ["Akiba", "Sano"],
}
参数:
  • key (str) – 属性的关键字符串。

  • value (Any) – 属性的值。该值应为可JSON序列化的。

返回类型:

None

stop()[源代码]

在当前优化循环中的运行试验完成后退出。

此方法使得正在运行的 optimize() 方法在所有由 optimize() 方法生成的试验完成后立即返回。此方法不影响任何并行或连续的研究过程的行为。此方法仅在目标函数或回调内部调用时有效。

示例

import optuna


def objective(trial):
    if trial.number == 4:
        trial.study.stop()
    x = trial.suggest_float("x", 0, 10)
    return x**2


study = optuna.create_study()
study.optimize(objective, n_trials=10)
assert len(study.trials) == 5
返回类型:

None

property system_attrs: dict[str, Any]

返回系统属性。

返回:

包含所有系统属性的字典。

警告

在 v3.1.0 中已弃用。此功能将在未来被移除。该功能的移除目前计划在 v5.0.0 进行,但此时间表可能会更改。请参阅 https://github.com/optuna/optuna/releases/tag/v3.1.0

tell(trial, values=None, state=None, skip_if_finished=False)[源代码]

完成使用 ask() 创建的试验。

参见

The 询问-告知接口 tutorial provides use-cases with examples.

示例

import optuna
from optuna.trial import TrialState


def f(x):
    return (x - 2) ** 2


def df(x):
    return 2 * x - 4


study = optuna.create_study()

n_trials = 30

for _ in range(n_trials):
    trial = study.ask()

    lr = trial.suggest_float("lr", 1e-5, 1e-1, log=True)

    # Iterative gradient descent objective function.
    x = 3  # Initial value.
    for step in range(128):
        y = f(x)

        trial.report(y, step=step)

        if trial.should_prune():
            # Finish the trial with the pruned state.
            study.tell(trial, state=TrialState.PRUNED)
            break

        gy = df(x)
        x -= gy * lr
    else:
        # Finish the trial with the final value after all iterations.
        study.tell(trial, y)
参数:
  • trial (Trial | int) – 一个 Trial 对象或试验编号。

  • values (float | Sequence[float] | None) – Optional objective value or a sequence of such values in case the study is used for multi-objective optimization. Argument must be provided if state is COMPLETE and should be None if state is FAIL or PRUNED.

  • state (TrialState | None) – State to be reported. Must be None, COMPLETE, FAIL or PRUNED. If state is None, it will be updated to COMPLETE or FAIL depending on whether validation for values reported succeed or not.

  • skip_if_finished (bool) – Flag to control whether exception should be raised when values for already finished trial are told. If True, tell is skipped without any error when the trial is already finished.

返回:

一个表示结果试验的 FrozenTrial。返回的试验是深度复制的,因此用户可以根据需要修改它。

返回类型:

FrozenTrial

property trials: list[FrozenTrial]

返回研究中的所有试验。

返回的试验按试验编号排序。

这是 self.get_trials(deepcopy=True, states=None) 的简写形式。

返回:

一个 FrozenTrial 对象的列表。 .. seealso:: 参见 get_trials() 相关方法。

trials_dataframe(attrs=('number', 'value', 'datetime_start', 'datetime_complete', 'duration', 'params', 'user_attrs', 'system_attrs', 'state'), multi_index=False)[源代码]

将试验导出为 pandas DataFrame

DataFrame 提供了各种分析研究的功能。它还用于绘制目标值的直方图并将试验导出为CSV文件。如果没有试验,则返回一个空的 DataFrame

示例

import optuna
import pandas


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


study = optuna.create_study()
study.optimize(objective, n_trials=3)

# Create a dataframe from the study.
df = study.trials_dataframe()
assert isinstance(df, pandas.DataFrame)
assert df.shape[0] == 3  # n_trials.
参数:
  • attrs (tuple[str, ...]) – 指定 FrozenTrial 的字段名称,以将它们包含在试验的 DataFrame 中。

  • multi_index (bool) – Specifies whether the returned DataFrame employs MultiIndex or not. Columns that are hierarchical by nature such as (params, x) will be flattened to params_x when set to False.

返回:

一个包含 Study 中试验的 pandas DataFrame

返回类型:

pd.DataFrame

备注

如果在多目标优化期间,attrs 中存在 value,它将被隐式替换为 values

备注

如果调用了 set_metric_names()valuevalues 将被隐式替换为以目标名称为键、目标值为值的字典。

property user_attrs: dict[str, Any]

返回用户属性。

参见

参见 set_user_attr() 相关方法。

示例

import optuna


def objective(trial):
    x = trial.suggest_float("x", 0, 1)
    y = trial.suggest_float("y", 0, 1)
    return x**2 + y**2


study = optuna.create_study()

study.set_user_attr("objective function", "quadratic function")
study.set_user_attr("dimensions", 2)
study.set_user_attr("contributors", ["Akiba", "Sano"])

assert study.user_attrs == {
    "objective function": "quadratic function",
    "dimensions": 2,
    "contributors": ["Akiba", "Sano"],
}
返回:

包含所有用户属性的字典。