如何在使用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折交叉验证的直观问题

我在使用交叉验证检查预测能力时遇到了一些直观问题,我认…

调整numpy数组大小以使用sklearn的train_test_split函数?

我正在尝试使用sklearn中的test_train_…

如何转换二维张量和索引张量以便用于torch.nn.utils.rnn.pack_sequence

我有一组序列,格式如下: sequences = to…

模型预测值的含义是什么?

我在网上找到一个数字识别器的CNN模型并进行了训练,当…

锯齿张量作为LSTM的输入

了解锯齿张量以及如何在TensorFlow中使用它们。…

如何告诉SciKit的LinearRegression模型预测值不能小于零?

我有以下代码,尝试根据非价格基础特征来估值股票。 pr…

发表回复

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