gpt4 book ai didi

Python:如何从 Optuna LightGBM 研究中检索最佳模型?

转载 作者:行者123 更新时间:2023-12-03 23:27:12 24 4
gpt4 key购买 nike

我想获得稍后在笔记本中使用的最佳模型,以使用不同的测试批次进行预测。

可重现的示例(取自 Optuna Github):

import lightgbm as lgb
import numpy as np
import sklearn.datasets
import sklearn.metrics
from sklearn.model_selection import train_test_split

import optuna


# FYI: Objective functions can take additional arguments
# (https://optuna.readthedocs.io/en/stable/faq.html#objective-func-additional-args).
def objective(trial):
data, target = sklearn.datasets.load_breast_cancer(return_X_y=True)
train_x, valid_x, train_y, valid_y = train_test_split(data, target, test_size=0.25)
dtrain = lgb.Dataset(train_x, label=train_y)
dvalid = lgb.Dataset(valid_x, label=valid_y)

param = {
"objective": "binary",
"metric": "auc",
"verbosity": -1,
"boosting_type": "gbdt",
"lambda_l1": trial.suggest_loguniform("lambda_l1", 1e-8, 10.0),
"lambda_l2": trial.suggest_loguniform("lambda_l2", 1e-8, 10.0),
"num_leaves": trial.suggest_int("num_leaves", 2, 256),
"feature_fraction": trial.suggest_uniform("feature_fraction", 0.4, 1.0),
"bagging_fraction": trial.suggest_uniform("bagging_fraction", 0.4, 1.0),
"bagging_freq": trial.suggest_int("bagging_freq", 1, 7),
"min_child_samples": trial.suggest_int("min_child_samples", 5, 100),
}

# Add a callback for pruning.
pruning_callback = optuna.integration.LightGBMPruningCallback(trial, "auc")
gbm = lgb.train(
param, dtrain, valid_sets=[dvalid], verbose_eval=False, callbacks=[pruning_callback]
)

preds = gbm.predict(valid_x)
pred_labels = np.rint(preds)
accuracy = sklearn.metrics.accuracy_score(valid_y, pred_labels)
return accuracy


我的理解是,下面的研究将调整准确性。我想以某种方式从研究中检索最佳模型(不仅仅是参数)而不将其保存为泡菜,我只想在笔记本中的其他地方使用该模型。

if __name__ == "__main__":
study = optuna.create_study(
pruner=optuna.pruners.MedianPruner(n_warmup_steps=10), direction="maximize"
)
study.optimize(objective, n_trials=100)

print("Best trial:")
trial = study.best_trial

print(" Params: ")
for key, value in trial.params.items():
print(" {}: {}".format(key, value))


期望的输出将是
best_model = ~model from above~
new_target_pred = best_model.predict(new_data_test)
metrics.accuracy_score(new_target_test, new__target_pred)

最佳答案

我认为您可以使用 callback Study.optimize 参数来保存最佳模型。在以下代码示例中,回调检查给定试验是否对应于最佳试验,并将模型保存为全局变量 best_booster

best_booster = None
gbm = None

def objective(trial):
global gbm
# ...

def callback(study, trial):
global best_booster
if study.best_trial == trial:
best_booster = gbm

if __name__ == "__main__":
study = optuna.create_study(
pruner=optuna.pruners.MedianPruner(n_warmup_steps=10), direction="maximize"
)
study.optimize(objective, n_trials=100, callbacks=[callback])


如果将目标函数定义为类,则可以删除全局变量。我创建了一个笔记本作为代码示例。请看一下:
https://colab.research.google.com/drive/1ssjXp74bJ8bCAbvXFOC4EIycBto_ONp_?usp=sharing

I would like to somehow retrieve the best model from the study (not just the parameters) without saving it as a pickle



仅供引用,如果您可以腌制助推器,我认为您可以通过遵循 this FAQ 来简化代码。

关于Python:如何从 Optuna LightGBM 研究中检索最佳模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62144904/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com