如何在optuna中采样参数而不重复?

2024-03-29 12:38:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用optuna对我的定制模型进行参数优化。你知道吗

有没有办法在当前参数集之前对参数进行采样?我的意思是,如果过去有一些试验使用同一组参数,请尝试对另一个参数进行取样。你知道吗

在某些情况下,这是不可能的,例如,当存在类别分布且n_trials大于可能的唯一采样值的数目时。你知道吗

我想要的是:有一些像num_attempts这样的配置参数,以便在for循环中对num_attempts以内的参数进行采样,直到有一个之前没有测试过的集,否则-对最后一个采样的集运行试用。你知道吗

为什么我需要这个:只是因为在相同的参数下运行几次重型模型花费太多。你知道吗

我现在要做的是:只做这个“循环”的东西,但它很混乱。你知道吗

如果有另一个聪明的方法做这件事-将非常感谢的信息。你知道吗

谢谢!你知道吗


Tags: 方法模型信息for参数情况类别num
1条回答
网友
1楼 · 发布于 2024-03-29 12:38:22

据我所知,目前没有直接的方法来处理你的案子。 作为一种解决方法,您可以检查参数重复并跳过计算,如下所示:

import optuna

def objective(trial: optuna.Trial):
    # Sample parameters.
    x = trial.suggest_int('x', 0, 10)
    y = trial.suggest_categorical('y', [-10, -5, 0, 5, 10])

    # Check duplication and skip if it's detected.
    for t in trial.study.trials:
        if t.state != optuna.structs.TrialState.COMPLETE:
            continue

        if t.params == trial.params:
            return t.value  # Return the previous value without re-evaluating it.

            # # Note that if duplicate parameter sets are suggested too frequently,
            # # you can use the pruning mechanism of Optuna to mitigate the problem.
            # # By raising `TrialPruned` instead of just returning the previous value,
            # # the sampler is more likely to avoid sampling the parameters in the succeeding trials.
            #
            # raise optuna.structs.TrialPruned('Duplicate parameter set')

    # Evaluate parameters.
    return x + y

# Start study.
study = optuna.create_study()

unique_trials = 20
while unique_trials > len(set(str(t.params) for t in study.trials)):
    study.optimize(objective, n_trials=1)

相关问题 更多 >