optuna.trial.Trial

class optuna.trial.Trial(study, trial_id)[source]

トライアルとは、目的関数を評価するプロセスです。

このオブジェクトは目的関数に渡され、パラメータの提案取得、 トライアルの状態管理、ユーザー定義属性の設定/取得を行うためのインターフェースを提供します。

このコンストラクタを直接使用することは推奨されません。 このオブジェクトは optuna.study.Study.optimize() メソッドの内部でシームレスに生成され、 目的関数に渡されるため、ライブラリユーザーはこのオブジェクトの生成を意識する必要はありません。

Parameters:

メソッド

report(value, step)

Report an objective function value for a given step.

set_system_attr(key, value)

Set system attributes to the trial.

set_user_attr(key, value)

Set user attributes to the trial.

should_prune()

Suggest whether the trial should be pruned or not.

suggest_categorical()

Suggest a value for the categorical parameter.

suggest_discrete_uniform(name, low, high, q)

Suggest a value for the discrete parameter.

suggest_float(name, low, high, *[, step, log])

Suggest a value for the floating point parameter.

suggest_int(name, low, high, *[, step, log])

Suggest a value for the integer parameter.

suggest_loguniform(name, low, high)

Suggest a value for the continuous parameter.

suggest_uniform(name, low, high)

Suggest a value for the continuous parameter.

属性

datetime_start

Return start datetime.

distributions

Return distributions of parameters to be optimized.

number

Return trial's number which is consecutive and unique in a study.

params

Return parameters to be optimized.

relative_params

system_attrs

Return system attributes.

user_attrs

Return user attributes.

property datetime_start: datetime | None

開始日時を返します。

Returns:

Trial が開始された日時

property distributions: dict[str, BaseDistribution]

最適化対象のパラメータ分布を返します。

Returns:

すべての分布を含む辞書

property number: int

スタディ内で連番かつ一意のトライアル番号を返します。

Returns:

トライアル番号

property params: dict[str, Any]

最適化対象のパラメータを返します。

Returns:

すべてのパラメータを含む辞書

report(value, step)[source]

指定されたステップにおける目的関数の値を報告します。

報告された値は、プルーナーがこのトライアルをプルーニングすべきかどうかを判断するのに使用されます。

See also

BasePruner を参照してください。

Note

報告値は内部で float() 関数によって float 型に変換されます。 したがって、すべての浮動小数点数型(例:numpy.float32)が受け入れ可能です。 変換に失敗した場合、TypeError が発生します。

Note

トライアル内で同じ step に対して複数回このメソッドが呼び出された場合、 最初の報告値のみが保存され、それ以降の報告値は無視されます。

Note

report() は多目的最適化をサポートしていません。

使用例

SGDClassifier の学習における中間スコアを報告します。

import numpy as np
from sklearn.datasets import load_iris
from sklearn.linear_model import SGDClassifier
from sklearn.model_selection import train_test_split

import optuna

X, y = load_iris(return_X_y=True)
X_train, X_valid, y_train, y_valid = train_test_split(X, y)


def objective(trial):
    clf = SGDClassifier(random_state=0)
    for step in range(100):
        clf.partial_fit(X_train, y_train, np.unique(y))
        intermediate_value = clf.score(X_valid, y_valid)
        trial.report(intermediate_value, step=step)
        if trial.should_prune():
            raise optuna.TrialPruned()

    return clf.score(X_valid, y_valid)


study = optuna.create_study(direction="maximize")
study.optimize(objective, n_trials=3)
Parameters:
  • value (float) – 目的関数から返された値。

  • step (int) – トライアルのステップ(例:ニューラルネットワークのエポック数)。 プルーナーは step が0から始まると仮定します。例えば、 MedianPruner はウォームアップ機構として stepn_warmup_steps 未満かどうかを単純にチェックします。 step は正の整数である必要があります。

Return type:

None

set_system_attr(key, value)[source]

トライアルにシステム属性を設定します。

Optuna は内部でこのメソッドを使用して、トライアルの失敗理由などのシステムメッセージを保存します。 ユーザー属性を設定するには set_user_attr() を使用してください。

Parameters:
  • key (str) – 属性のキー文字列。

  • value (Any) – 属性の値。値は JSON シリアライズ可能である必要があります。

Return type:

None

Warning

v3.1.0 で非推奨となりました。この機能は将来的に削除される予定です。 現在の削除予定は v5.0.0 ですが、スケジュールは変更される可能性があります。 詳細は https://github.com/optuna/optuna/releases/tag/v3.1.0 を参照してください。

set_user_attr(key, value)[source]

トライアルにユーザー属性を設定します。

トライアル内のユーザー属性は optuna.trial.Trial.user_attrs() でアクセス可能です。

See also

ユーザー属性 のレシピを参照してください。

使用例

ニューラルネットワークの学習における固定ハイパーパラメータを保存します。

import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier

import optuna

X, y = load_iris(return_X_y=True)
X_train, X_valid, y_train, y_valid = train_test_split(X, y, random_state=0)


def objective(trial):
    trial.set_user_attr("BATCHSIZE", 128)
    momentum = trial.suggest_float("momentum", 0, 1.0)
    clf = MLPClassifier(
        hidden_layer_sizes=(100, 50),
        batch_size=trial.user_attrs["BATCHSIZE"],
        momentum=momentum,
        solver="sgd",
        random_state=0,
    )
    clf.fit(X_train, y_train)

    return clf.score(X_valid, y_valid)


study = optuna.create_study(direction="maximize")
study.optimize(objective, n_trials=3)
assert "BATCHSIZE" in study.best_trial.user_attrs.keys()
assert study.best_trial.user_attrs["BATCHSIZE"] == 128
Parameters:
  • key (str) – 属性のキー文字列。

  • value (Any) – 属性の値。値は JSON シリアライズ可能である必要があります。

Return type:

None

should_prune()[source]

トライアルをプルーニングすべきかどうかを提案します。

この提案はトライアルに関連付けられたプルーニングアルゴリズムによって行われ、 以前に報告された値に基づいています。アルゴリズムは Study の 構築時に指定できます。

Note

まだ値が報告されていない場合、アルゴリズムは意味のある提案を行えません。 同様に、この方法を同じ報告値のセットで複数回呼び出した場合、提案は同じになります。

See also

optuna.trial.Trial.report() の使用例を参照してください。

Note

should_prune() は多目的最適化をサポートしていません。

Returns:

ブール値。True の場合、設定されたプルーニングアルゴリズムに従って トライアルをプルーニングする必要があります。それ以外の場合、トライアルは継続されます。

Return type:

bool

suggest_categorical(name: str, choices: Sequence[None]) None[source]
suggest_categorical(name: str, choices: Sequence[bool]) bool
suggest_categorical(name: str, choices: Sequence[int]) int
suggest_categorical(name: str, choices: Sequence[float]) float
suggest_categorical(name: str, choices: Sequence[str]) str
suggest_categorical(name: str, choices: Sequence[None | bool | int | float | str]) None | bool | int | float | str

カテゴリカルパラメータの値を提案します。

値は choices からサンプリングされます。

SVC のカーネル関数を提案します。

import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC

import optuna

X, y = load_iris(return_X_y=True)
X_train, X_valid, y_train, y_valid = train_test_split(X, y)


def objective(trial):
    kernel = trial.suggest_categorical("kernel", ["linear", "poly", "rbf"])
    clf = SVC(kernel=kernel, gamma="scale", random_state=0)
    clf.fit(X_train, y_train)
    return clf.score(X_valid, y_valid)


study = optuna.create_study(direction="maximize")
study.optimize(objective, n_trials=3)
Parameters:
  • name – パラメータ名。

  • choices – パラメータ値の候補。

Returns:

提案された値。

See also

Pythonic な探索空間 チュートリアルでは、より詳細な使用方法と柔軟な設定について説明しています。

suggest_discrete_uniform(name, low, high, q)[source]

離散パラメータの値を提案します。

値は範囲 \([\mathsf{low}, \mathsf{high}]\) からサンプリングされ、 離散化のステップは \(q\) です。具体的には、 このメソッドは \(\mathsf{low}, \mathsf{low} + q, \mathsf{low} + 2 q, \dots, \mathsf{low} + k q \le \mathsf{high}\) の範囲の値を返します。 ここで \(k\) は整数です。\(q\) が整数でない場合、 丸め誤差により \(high\) の値が変更される可能性があります。 変更された値を確認するには警告メッセージを確認してください。

Parameters:
  • name (str) – パラメータ名。

  • low (float) – 提案値の範囲の下限。low は範囲に含まれます。

  • high (float) – 提案値の範囲の上限。high は範囲に含まれます。

  • q (float) – 離散化のステップ。

Returns:

提案された浮動小数点数。

Return type:

float

Warning

v3.0.0 で非推奨となりました。この機能は将来的に削除される予定です。 現在の削除予定は v6.0.0 ですが、スケジュールは変更される可能性があります。 詳細は https://github.com/optuna/optuna/releases/tag/v3.0.0 を参照してください。

代わりに suggest_float(…, step=…) を使用してください。

suggest_float(name, low, high, *, step=None, log=False)[source]

浮動小数点数パラメータの値を提案します。

ニューラルネットワークの学習におけるモメンタム、学習率、 学習率スケーリング係数を提案します。

import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier

import optuna

X, y = load_iris(return_X_y=True)
X_train, X_valid, y_train, y_valid = train_test_split(X, y, random_state=0)


def objective(trial):
    momentum = trial.suggest_float("momentum", 0.0, 1.0)
    learning_rate_init = trial.suggest_float(
        "learning_rate_init", 1e-5, 1e-3, log=True
    )
    power_t = trial.suggest_float("power_t", 0.2, 0.8, step=0.1)
    clf = MLPClassifier(
        hidden_layer_sizes=(100, 50),
        momentum=momentum,
        learning_rate_init=learning_rate_init,
        solver="sgd",
        random_state=0,
        power_t=power_t,
    )
    clf.fit(X_train, y_train)

    return clf.score(X_valid, y_valid)


study = optuna.create_study(direction="maximize")
study.optimize(objective, n_trials=3)
Parameters:
  • name (str) – パラメータ名

  • low (float) – 提案値の範囲の下限。low は範囲に含まれます。 lowhigh 以下でなければなりません。logTrue の場合、 low は 0 より大きくなければなりません。

  • high (float) – 提案値の範囲の上限。high は範囲に含まれます。 highlow 以上でなければなりません。

  • step (float | None) –

    離散化のステップ幅

    Note

    steplog 引数は同時に使用できません。step 引数を浮動小数点数に設定する場合、 log 引数を False に設定してください。

  • log (bool) –

    対数領域から値をサンプリングするかどうかのフラグ。 log が true の場合、値は対数領域の範囲でサンプリングされます。 それ以外の場合、値は線形領域の範囲でサンプリングされます。

    Note

    steplog 引数は同時に使用できません。log 引数を True に設定する場合、 step 引数を None に設定してください。

Returns:

提案された浮動小数点数の値

Return type:

float

See also

Pythonic な探索空間 チュートリアルでは、より詳細な説明と柔軟な使用方法を説明しています。

suggest_int(name, low, high, *, step=1, log=False)[source]

整数パラメータの値を提案します。

値は \([\mathsf{low}, \mathsf{high}]\) の整数からサンプリングされます。

RandomForestClassifier の ツリー数を提案します。

import numpy as np
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split

import optuna

X, y = load_iris(return_X_y=True)
X_train, X_valid, y_train, y_valid = train_test_split(X, y)


def objective(trial):
    n_estimators = trial.suggest_int("n_estimators", 50, 400)
    clf = RandomForestClassifier(n_estimators=n_estimators, random_state=0)
    clf.fit(X_train, y_train)
    return clf.score(X_valid, y_valid)


study = optuna.create_study(direction="maximize")
study.optimize(objective, n_trials=3)
Parameters:
  • name (str) – パラメータ名

  • low (int) – 提案値の範囲の下限。low は範囲に含まれます。lowhigh 以下でなければなりません。logTrue の場合、low は 0 より大きくなければなりません。

  • high (int) – 提案値の範囲の上限。high は範囲に含まれます。highlow 以上でなければなりません。

  • step (int) –

    離散化のステップ幅

    Note

    範囲が \(\mathsf{step}\) で割り切れない場合、\(\mathsf{high}\) が変更されます。変更された値を確認するには、警告メッセージを確認してください。

    Note

    このメソッドは、\(\mathsf{low}, \mathsf{low} + \mathsf{step}, \mathsf{low} + 2 * \mathsf{step}, \dots, \mathsf{low} + k * \mathsf{step} \le \mathsf{high}\) の範囲から値を返します。ここで、\(k\) は整数です。

    Note

    step != 1log 引数は同時に使用できません。step 引数を \(\mathsf{step} \ge 2\) に設定する場合、log 引数を False に設定してください。

  • log (bool) –

    値を対数ドメインからサンプリングするかどうかのフラグ

    Note

    log が true の場合、まず提案値の範囲が幅 1 のグリッドポイントに分割されます。その後、提案値の範囲が対数ドメインに変換され、値をサンプリングします。サンプリングされた値は元のドメインに変換され、分割したグリッドポイントに丸められ、提案値が決定されます。例えば、low = 2high = 8 の場合、提案値の範囲は [2, 3, 4, 5, 6, 7, 8] となり、低い値ほどサンプリングされやすくなります。

    Note

    step != 1log 引数は同時に使用できません。log 引数を True に設定する場合、step 引数を 1 に設定してください。

Return type:

int

See also

Pythonic な探索空間 チュートリアルでは、より詳細な情報と柔軟な使用方法について説明しています。

suggest_loguniform(name, low, high)[source]

連続パラメータの値を提案します。

値は、対数ドメインの範囲 \([\mathsf{low}, \mathsf{high})\) からサンプリングされます。\(\mathsf{low} = \mathsf{high}\) の場合、\(\mathsf{low}\) の値が返されます。

Parameters:
  • name (str) – パラメータ名

  • low (float) – 提案値の範囲の下限。low は範囲に含まれます。

  • high (float) – 提案値の範囲の上限。high は範囲に含まれます。

Returns:

提案された浮動小数点数

Return type:

float

Warning

v3.0.0 で非推奨となりました。この機能は将来的に削除される予定です。現在の削除予定は v6.0.0 ですが、変更される可能性があります。 詳細は https://github.com/optuna/optuna/releases/tag/v3.0.0 を参照してください。

代わりに suggest_float(…, log=True) を使用してください。

suggest_uniform(name, low, high)[source]

連続パラメータの値を提案します。

値は、線形ドメインの範囲 \([\mathsf{low}, \mathsf{high})\) からサンプリングされます。\(\mathsf{low} = \mathsf{high}\) の場合、\(\mathsf{low}\) の値が返されます。

Parameters:
  • name (str) – パラメータ名

  • low (float) – 提案値の範囲の下限。low は範囲に含まれます。

  • high (float) – 提案値の範囲の上限。high は範囲に含まれます。

Returns:

提案された浮動小数点数

Return type:

float

Warning

v3.0.0 で非推奨となりました。この機能は将来的に削除される予定です。現在の削除予定は v6.0.0 ですが、変更される可能性があります。 詳細は https://github.com/optuna/optuna/releases/tag/v3.0.0 を参照してください。

代わりに suggest_float を使用してください。

property system_attrs: dict[str, Any]

システム属性を取得します。

Returns:

すべてのシステム属性を含む辞書

Warning

v3.1.0 で非推奨となりました。この機能は将来的に削除される予定です。現在の削除予定は v5.0.0 ですが、変更される可能性があります。 詳細は https://github.com/optuna/optuna/releases/tag/v3.1.0 を参照してください。

property user_attrs: dict[str, Any]

ユーザー属性を取得します。

Returns:

すべてのユーザー属性を含む辞書