optuna.trial.Trial
- class optuna.trial.Trial(study, trial_id)[source]
トライアルとは、目的関数を評価するプロセスです。
このオブジェクトは目的関数に渡され、パラメータの提案取得、 トライアルの状態管理、ユーザー定義属性の設定/取得を行うためのインターフェースを提供します。
このコンストラクタを直接使用することは推奨されません。 このオブジェクトは
optuna.study.Study.optimize()
メソッドの内部でシームレスに生成され、 目的関数に渡されるため、ライブラリユーザーはこのオブジェクトの生成を意識する必要はありません。- Parameters:
study (optuna.study.Study) –
Study
オブジェクトtrial_id (int) – 自動的に生成されるトライアルID
メソッド
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.
Suggest whether the trial should be pruned or not.
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.
属性
Return start datetime.
Return distributions of parameters to be optimized.
Return trial's number which is consecutive and unique in a study.
Return parameters to be optimized.
relative_params
Return system attributes.
Return user attributes.
- 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
はウォームアップ機構としてstep
がn_warmup_steps
未満かどうかを単純にチェックします。step
は正の整数である必要があります。
- Return type:
None
- set_system_attr(key, value)[source]
トライアルにシステム属性を設定します。
Optuna は内部でこのメソッドを使用して、トライアルの失敗理由などのシステムメッセージを保存します。 ユーザー属性を設定するには
set_user_attr()
を使用してください。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
- should_prune()[source]
トライアルをプルーニングすべきかどうかを提案します。
この提案はトライアルに関連付けられたプルーニングアルゴリズムによって行われ、 以前に報告された値に基づいています。アルゴリズムは
Study
の 構築時に指定できます。Note
まだ値が報告されていない場合、アルゴリズムは意味のある提案を行えません。 同様に、この方法を同じ報告値のセットで複数回呼び出した場合、提案は同じになります。
See also
optuna.trial.Trial.report()
の使用例を参照してください。Note
should_prune()
は多目的最適化をサポートしていません。
- 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 – パラメータ値の候補。
See also
- 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:
- Returns:
提案された浮動小数点数。
- Return type:
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
は範囲に含まれます。low
はhigh
以下でなければなりません。log
がTrue
の場合、low
は 0 より大きくなければなりません。high (float) – 提案値の範囲の上限。
high
は範囲に含まれます。high
はlow
以上でなければなりません。step (float | None) –
離散化のステップ幅
Note
step
とlog
引数は同時に使用できません。step
引数を浮動小数点数に設定する場合、log
引数をFalse
に設定してください。log (bool) –
対数領域から値をサンプリングするかどうかのフラグ。
log
が true の場合、値は対数領域の範囲でサンプリングされます。 それ以外の場合、値は線形領域の範囲でサンプリングされます。
- Returns:
提案された浮動小数点数の値
- Return type:
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
は範囲に含まれます。low
はhigh
以下でなければなりません。log
がTrue
の場合、low
は 0 より大きくなければなりません。high (int) – 提案値の範囲の上限。
high
は範囲に含まれます。high
はlow
以上でなければなりません。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 != 1
とlog
引数は同時に使用できません。step
引数を \(\mathsf{step} \ge 2\) に設定する場合、log
引数をFalse
に設定してください。log (bool) –
値を対数ドメインからサンプリングするかどうかのフラグ
Note
log
が true の場合、まず提案値の範囲が幅 1 のグリッドポイントに分割されます。その後、提案値の範囲が対数ドメインに変換され、値をサンプリングします。サンプリングされた値は元のドメインに変換され、分割したグリッドポイントに丸められ、提案値が決定されます。例えば、low = 2 で high = 8 の場合、提案値の範囲は [2, 3, 4, 5, 6, 7, 8] となり、低い値ほどサンプリングされやすくなります。Note
step != 1
とlog
引数は同時に使用できません。log
引数をTrue
に設定する場合、step
引数を 1 に設定してください。
- Return type:
See also
Pythonic な探索空間 チュートリアルでは、より詳細な情報と柔軟な使用方法について説明しています。
- suggest_loguniform(name, low, high)[source]
連続パラメータの値を提案します。
値は、対数ドメインの範囲 \([\mathsf{low}, \mathsf{high})\) からサンプリングされます。\(\mathsf{low} = \mathsf{high}\) の場合、\(\mathsf{low}\) の値が返されます。
- Parameters:
- Returns:
提案された浮動小数点数
- Return type:
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:
- Returns:
提案された浮動小数点数
- Return type:
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 を参照してください。