optuna.pruners.PercentilePruner

optuna.pruners.PercentilePruner(percentile, n_startup_trials=5, n_warmup_steps=0, interval_steps=1, *, n_min_trials=1)[source]

剪枝器,用于保留指定百分位数的试验(trials)。

如果在同一步骤中,最佳中间值处于试验的最低百分位数,则进行剪枝。

示例

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)
classes = np.unique(y)


def objective(trial):
    alpha = trial.suggest_float("alpha", 0.0, 1.0)
    clf = SGDClassifier(alpha=alpha)
    n_train_iter = 100

    for step in range(n_train_iter):
        clf.partial_fit(X_train, y_train, classes=classes)

        intermediate_value = clf.score(X_valid, y_valid)
        trial.report(intermediate_value, step)

        if trial.should_prune():
            raise optuna.TrialPruned()

    return clf.score(X_valid, y_valid)


study = optuna.create_study(
    direction="maximize",
    pruner=optuna.pruners.PercentilePruner(
        25.0, n_startup_trials=5, n_warmup_steps=30, interval_steps=10
    ),
)
study.optimize(objective, n_trials=20)
参数:
  • percentile (float) – 百分位数,必须介于 0 到 100 之间(含两端)。例如,当给定 25.0 时,保留前 25% 的试验。

  • n_startup_trials (int) – 在同一个研究(study)中,直到完成给定数量的试验后,才会启用剪枝。

  • n_warmup_steps (int) – 在试验超过给定步骤数之前,剪枝是禁用的。请注意,此功能假设 step 从零开始。

  • interval_steps (int) – 两次剪枝检查之间的步数间隔,从热身步数之后开始计算。如果在剪枝检查时没有报告任何值,该次检查将推迟到报告值时进行。该值必须至少为 1。

  • n_min_trials (int) – 在某个步骤中,判断是否进行剪枝所需的最小已报告试验结果数量。如果在当前步骤中,所有试验报告的中间值数量少于 n_min_trials,则该试验不会被剪枝。这可以用于确保至少有一定数量的试验能完整运行而不被剪枝。

方法

prune(study, trial)

根据报告的值判断是否应剪枝该试验。

prune(study, trial)[source]

根据报告的值判断是否应剪枝该试验。

请注意,库的用户不应该调用此方法。相反,optuna.trial.Trial.report()optuna.trial.Trial.should_prune() 提供了用户接口,用于在目标函数中实现剪枝机制。

参数:
  • study (Study) – 目标研究(study)的对象。

  • trial (FrozenTrial) – 目标试验(trial)的 FrozenTrial 对象。在修改此对象之前请先创建副本。

返回值:

一个布尔值,表示是否应对该试验进行剪枝。

返回类型:

bool