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

如何让Optuna调参结果具备可复现性?

让Optuna调优LGBM结果具备可复现性的方法

以下是针对你的代码的具体修改方案,解决多次运行结果不一致的问题:

1. 固定全局随机种子

在代码开头(或脚本最顶部)设置Python内置随机模块和numpy的种子,覆盖Optuna和LightGBM依赖的全局随机源:

import random
import numpy as np

# 固定全局随机种子
random.seed(10)
np.random.seed(10)

2. 为Hyperband剪枝器添加随机种子

你使用的HyperbandPruner本身带有随机性,必须显式设置seed参数才能保证剪枝逻辑的可复现:

study = optuna.create_study(
    direction="maximize",
    pruner=optuna.pruners.HyperbandPruner(seed=10),  # 新增seed参数
    sampler=optuna.samplers.TPESampler(seed=10),
    study_name='lgbm_hpo'
)

3. 启用LightGBM的确定性模式

即使设置了random_state,多线程下的LightGBM仍可能出现非确定性结果,添加deterministic=True参数强制模型训练过程完全确定:

params = {
    "objective": "binary",
    "metric": "auc",
    "random_state": 10,
    "verbosity": -1,
    "boosting": "gbdt",
    "num_threads": 4,
    "deterministic": True,  # 启用确定性模式
    # 其余超参数保持不变
    "num_leaves": trial.suggest_int("num_leaves", 4, 30),
    "learning_rate": trial.suggest_loguniform("learning_rate", 0.005, 1.0),
    "bagging_fraction": trial.suggest_uniform("bagging_fraction", 0.1, 1.0),
    "feature_fraction": trial.suggest_uniform("feature_fraction", 0.1, 1.0),
    "bagging_freq": trial.suggest_int("bagging_freq", 10, 30),
    "min_data_in_leaf": trial.suggest_int("min_data_in_leaf", 1000, 3000),
    "num_iterations": trial.suggest_int("num_iterations", 1000, 3000)
}

4. 验证数据集稳定性

确保传入函数的opt_X_train、opt_X_val、opt_y_train、opt_y_val在每次运行时完全一致,避免外部代码对数据集进行随机拆分或修改。

完成以上修改后,重启内核再次运行,Optuna的调优结果将具备可复现性。

内容的提问来源于stack exchange,提问作者Cherry Wu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 04:01:28