如何在使用LightGBM进行GridSearchCV时保存每次迭代的预测结果

我正在尝试使用GridSearchCV来调整LightGBM模型的参数,但我对如何在GridSearchCV的每次迭代中保存每个预测结果还不太熟悉。
遗憾的是,我只知道如何保存特定参数下的结果。
这是代码:

param = {    'bagging_freq': 5,    'bagging_fraction': 0.4,    'boost_from_average':'false',    'boost': 'gbdt',    'feature_fraction': 0.05,    'learning_rate': 0.01,    'max_depth': -1,      'metric':'auc',    'min_data_in_leaf': 80,    'min_sum_hessian_in_leaf': 10.0,    'num_leaves': 13,    'num_threads': 8,    'tree_learner': 'serial',    'objective': 'binary',     'verbosity': 1}features = [c for c in train_df.columns if c not in ['ID_code', 'target']]target = train_df['target']folds = StratifiedKFold(n_splits=10, shuffle=False, random_state=44000)oof = np.zeros(len(train_df))predictions = np.zeros(len(test_df))for fold_, (trn_idx, val_idx) in enumerate(folds.split(train_df.values, target.values)):    print("Fold {}".format(fold_))    trn_data = lgb.Dataset(train_df.iloc[trn_idx][features], label=target.iloc[trn_idx])    val_data = lgb.Dataset(train_df.iloc[val_idx][features], label=target.iloc[val_idx])        num_round = 1000000    clf = lgb.train(param, trn_data, num_round, valid_sets = [trn_data, val_data], verbose_eval=1000, early_stopping_rounds = 3000)    oof[val_idx] = clf.predict(train_df.iloc[val_idx][features], num_iteration=clf.best_iteration)            predictions += clf.predict(test_df[features], num_iteration=clf.best_iteration) / folds.n_splitsprint("CV score: {:<8.5f}".format(roc_auc_score(target, oof)))print('Saving the Result File')res= pd.DataFrame({"ID_code": test.ID_code.values})res["target"] = predictionsres.to_csv('result_10fold{}.csv'.format(num_sub), index=False)

这是数据:

train_df.head(3)         ID_code    target    var_0    var_1    ...  var_1990        train_0     0        8.9255   -6.7863       -9.2834     1        train_1     1        11.5006  -4.1473        7.0433  2        train_2     0        8.6093   -2.7457       -9.0837 train_df.head(3)         ID_code    var_0   var_1    ... var_1990        test_0     9.4292  11.4327      -2.3805          1        test_1     5.0930  11.4607      -9.2834      2        train_2    7.8928  10.5825      -9.0837      

我想保存GridSearchCV每次迭代的predictions,我已经搜索了一些类似的问题和使用LightGBM中的GridSearchCV的相关信息。
但是我仍然无法正确编写代码。
所以,如果不介意的话,能有人帮助我并提供一些相关教程吗?
非常感谢。


回答:

您可以使用sklearn中的ParameterGridParameterSampler来进行参数采样 – 它们分别对应于GridSearchCVRandomSearchCV。例如,

def train_lgb(num_folds=11, param=param_original):    ...    return predictions, subparams = {# your base parameters}# define the grid for parameter samplingfrom sklearn.model_selection import ParameterGridpar_grid = ParameterGrid([{'bagging_freq':[6,7]},                          {'num_leaves': [13,15]}                         ])prediction_list = {}sub_list = {}import copyfor i, ps in enumerate(par_grid):    print('This is param{}'.format(i))    # copy the base params dictionary and update with sampled values    val = copy.deepcopy(params)    val.update(ps)    # main training loop    prediction, sub = train_lgb(param=val)     prediction_list.update({key: prediction})    sub_list.update({key: sub})

编辑:顺便说一下,我最近也在研究同样的问题,并且正在学习如何使用一些机器学习工具来解决这个问题。我已经创建了一个页面,总结了如何使用MLflow来完成这项任务:https://mlisovyi.github.io/KaggleSantander2019/(以及相关的GitHub页面,其中包含实际代码)。请注意,这恰好是基于您正在处理的相同数据:)。希望这会对您有帮助。

Related Posts

在使用k近邻算法时,有没有办法获取被使用的“邻居”?

我想找到一种方法来确定在我的knn算法中实际使用了哪些…

Theano在Google Colab上无法启用GPU支持

我在尝试使用Theano库训练一个模型。由于我的电脑内…

准确性评分似乎有误

这里是代码: from sklearn.metrics…

Keras Functional API: “错误检查输入时:期望input_1具有4个维度,但得到形状为(X, Y)的数组”

我在尝试使用Keras的fit_generator来训…

如何使用sklearn.datasets.make_classification在指定范围内生成合成数据?

我想为分类问题创建合成数据。我使用了sklearn.d…

如何处理预测时不在训练集中的标签

已关闭。 此问题与编程或软件开发无关。目前不接受回答。…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注