You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Optuna的trial.suggest_int/float从指定列表选取超参数值?

解决Optuna中从自定义列表选整数/浮点超参数的问题

要让trial.suggest_int或trial.suggest_float实现类似trial.suggest_categorical的自定义列表选值效果,核心有两种实用方案:

方案1:直接使用trial.suggest_categorical

Optuna的suggest_categorical并不限制候选值类型,整数、浮点数、字符串都可以直接传入列表。这是处理非等差自定义离散参数最直接的方式,完全匹配你的需求。

修改后的目标函数代码如下:

def objective(trial):
    DL_param = {
        'learning_rate': trial.suggest_float('learning_rate', 1e-3, 1e-1),
        'optimizer': trial.suggest_categorical('optimizer', ["Adam", "RMSprop", "SGD"]),
        'h_units': trial.suggest_int('h_units', 50, 250, step = 50),
        # 用suggest_categorical处理浮点候选列表
        'alpha': trial.suggest_categorical('alpha', [0.001, 0.01, 0.1, 0.2, 0.3]),
        # 用suggest_categorical处理整数候选列表
        'batch_size': trial.suggest_categorical('batch_size', [16, 32, 64, 128, 256]),
    }
    DL_model = build_model(DL_param)
    DL_model.compile(optimizer=DL_param['optimizer'], loss='mean_squared_error')
    DL_model.fit(x_train, y_train, validation_split = 0.3, shuffle = True,
                              batch_size = DL_param['batch_size'], epochs = 30)
    y_pred_2 = DL_model.predict(x_test)
    return mse(y_test_2, y_pred_2, squared=True)

方案2:针对等差序列用suggest_int/suggest_float的step参数

如果你的参数列表是严格等差序列(比如[10,20,30,40]),可以通过low+high+step的组合实现,就像你代码中h_units的写法。但如果是像alpha这种非等差的离散值,该方案不适用。

举个等差序列的例子(假设batch_size是[16,32,48,64]):

'batch_size': trial.suggest_int('batch_size', 16, 64, step=16)

但你的batch_size是2的幂(等比序列),用suggest_categorical反而更直观,避免step计算出错。

内容的提问来源于stack exchange,提问作者Bhanu Chander

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 22:55:56