optuna.trial.Trial
- class optuna.trial.Trial(study, trial_id)[source]
试验 (Trial) 是评估目标函数的过程。
此对象被传递给目标函数,并提供接口以获取参数建议、管理试验状态以及设置/获取用户定义的试验属性。
注意,不建议直接使用此构造函数。此对象在
optuna.study.Study.optimize()
方法背后被无缝实例化并传递给目标函数;因此库用户无需关心此对象的实例化。- 参数:
study (optuna.study.Study) – 一个
Study
对象。trial_id (int) – 自动生成的试验 ID。
方法
report
(value, step)报告给定步骤的目标函数值。
set_system_attr
(key, value)为试验设置系统属性。
set_user_attr
(key, value)为试验设置用户属性。
建议是否应该剪枝此试验。
为分类参数建议一个值。
suggest_discrete_uniform
(name, low, high, q)为离散参数建议一个值。
suggest_float
(name, low, high, *[, step, log])为浮点参数建议一个值。
suggest_int
(name, low, high, *[, step, log])为整数参数建议一个值。
suggest_loguniform
(name, low, high)为连续参数建议一个值。
suggest_uniform
(name, low, high)为连续参数建议一个值。
属性
返回开始日期时间。
返回待优化参数的分布。
返回试验在研究中连续且唯一的编号。
返回待优化参数。
relative_params
返回系统属性。
返回用户属性。
- report(value, step)[source]
报告给定步骤的目标函数值。
报告的值由剪枝器(pruner)用于确定是否应剪枝此试验。
另请参阅
请参阅
BasePruner
。注意
报告的值在内部通过应用
float()
函数转换为float
类型。因此,它接受所有类似 float 的类型(例如,numpy.float32
)。如果转换失败,则会引发TypeError
。注意
如果在试验中的同一
step
多次调用此方法,则仅第一次报告的value
会被存储,从第二次开始报告的值将被忽略。注意
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)
- 参数:
value (float) – 目标函数返回的值。
step (int) – 试验的步骤(例如,神经网络训练的 Epoch)。注意,剪枝器假设
step
从零开始。例如,MedianPruner
作为热身机制,简单地检查step
是否小于n_warmup_steps
。step
必须是正整数。
- 返回类型:
无
- set_system_attr(key, value)[source]
为试验设置系统属性。
请注意,Optuna 内部使用此方法保存系统消息,例如试验失败原因。请使用
set_user_attr()
设置用户属性。警告
自 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()
访问试验中的用户属性。另请参阅
请参阅有关 用户属性 的攻略。
示例
保存神经网络训练的固定超参数。
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
时指定该算法。注意
如果未报告任何值,则该算法无法给出有意义的建议。类似地,如果多次使用完全相同的报告值集合调用此方法,则建议将是相同的。
另请参阅
请参阅
optuna.trial.Trial.report()
中的示例代码。注意
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)
- 参数:
name – 参数名称。
choices – 参数值候选项。
另请参阅
- 返回:
建议的值。
另请参阅
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\) 可能会由于舍入误差而改变。请检查警告消息以查找更改的值。
- 参数:
- 返回:
建议的浮点值。
- 返回类型:
警告
自 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)
- 参数:
name (str) – 参数名称。
low (float) – 建议值范围的下限。
low
包含在范围内。low
必须小于或等于high
。如果log
为True
,则low
必须大于 0。high (float) – 建议值范围的上限。
high
包含在范围内。high
必须大于或等于low
。step (float | None) –
离散化的步长。
注意
step
和log
参数不能同时使用。要将step
参数设置为浮点数,请将log
参数设置为False
。log (bool) –
一个标志,指示是否从对数域采样值。如果
log
为 true,则从对数域范围采样值。否则,从线性域范围采样值。
- 返回:
建议的浮点值。
- 返回类型:
另请参阅
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)
- 参数:
name (str) – 参数名称。
low (int) – 建议值范围的下限。
low
包含在范围内。low
必须小于或等于high
。如果log
为True
,则low
必须大于 0。high (int) – 建议值范围的上限。
high
包含在范围内。high
必须大于或等于low
。step (int) –
离散化的步长。
注意
请注意,如果范围不能被 \(\mathsf{step}\) 整除,则 \(\mathsf{high}\) 会被修改。请检查警告消息以查找更改的值。
注意
此方法返回序列 \(\mathsf{low}, \mathsf{low} + \mathsf{step}, \mathsf{low} + 2 * \mathsf{step}, \dots, \mathsf{low} + k * \mathsf{step} \le \mathsf{high}\) 中的一个值,其中 \(k\) 表示一个整数。
注意
当
step != 1
时,step
和log
参数不能同时使用。要将step
参数设置为 \(\mathsf{step} \ge 2\),请将log
参数设置为False
。log (bool) –
一个标志,指示是否从对数域采样值。
注意
如果
log
为 true,则首先将建议值范围划分为宽度为 1 的网格点。然后将建议值范围转换为对数域,从中采样一个值。将均匀采样到的值重新转换回原始域,并四舍五入到我们刚才划分的最接近的网格点,从而确定建议值。例如,如果 low = 2 且 high = 8,则建议值范围为 [2, 3, 4, 5, 6, 7, 8],并且较低的值倾向于比较高的值被更多地采样。注意
当
step != 1
时,step
和log
参数不能同时使用。要将log
参数设置为True
,请将step
参数设置为 1。
- 返回类型:
另请参阅
Pythonic 搜索空间 教程介绍了更多详细信息和灵活用法。
- suggest_loguniform(name, low, high)[source]
为连续参数建议一个值。
该值从对数域范围 \([\mathsf{low}, \mathsf{high})\) 中采样得到。当 \(\mathsf{low} = \mathsf{high}\) 时,将返回 \(\mathsf{low}\) 的值。
- 参数:
- 返回:
建议的浮点值。
- 返回类型:
警告
自 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}\) 的值。
- 参数:
- 返回:
建议的浮点值。
- 返回类型:
警告
自 v3.0.0 起已弃用。此功能将来会被移除。目前计划在 v6.0.0 中移除此功能,但此计划可能会更改。请参阅 https://github.com/optuna/optuna/releases/tag/v3.0.0。
请改用 suggest_float。
- property system_attrs: dict[str, Any]
返回系统属性。
- 返回:
包含所有系统属性的字典。
警告
自 v3.1.0 起已弃用。此功能将来会被移除。目前计划在 v5.0.0 中移除此功能,但此计划可能会更改。请参阅 https://github.com/optuna/optuna/releases/tag/v3.1.0。