在sklearn管道中拟合自定义LGBM参数

2024-06-26 00:04:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用LightGBM开发一个二进制分类器。我的分类器定义如下所示:

# sklearn version, for the sake of calibration
bst_ = LGBMClassifier(**search_params, **static_params, n_estimators = 1500)

bst_.fit(X = X_train, y = y_train, sample_weight = TRAIN_WEIGHTS,
         eval_set = (X_test, y_test), eval_sample_weight = [TEST_WEIGHTS],
         eval_metric = my_scorer,
         early_stopping_rounds = 150, 
         callbacks = [lgb.reset_parameter(learning_rate = lambda current_round: learning_rate_decay(current_round, 
                                                                                                    base_learning_rate = learning_rate,
                                                                                                    decay_power = decay_power))],
         categorical_feature = cat_vars)

其中**search_params是由Optuna优化的超参数,**static_params是预定义的参数,例如'objective''random_state'

除此之外,我使用sample_weight定义每个目标的权重,我使用定制的目标函数my_scorer,早期停止和衰减学习率定义如下:

def learning_rate_decay(current_iter, base_learning_rate = 0.05, decay_power = 0.99):
    lr = base_learning_rate  * np.power(decay_power, current_iter)
    return lr if lr > 1e-3 else 1e-3

由于我希望通过建模得到概率,所以我希望使用等渗回归作为预测管道的最后一部分。我知道我可以使用以下代码:

# Calibrate 
calibrated_clf = CalibratedClassifierCV(
    base_estimator=bst_,
    method = 'isotonic',
    cv="prefit"
)
calibrated_clf.fit(X_train, y_train)

但根据{a1},我不应该在火车数据集上使用“prefit”。我想创建一个管道,它将维护在我的分类器.fit(例如回调)中定义的所有参数,如下所示:

calibrated_clf = CalibratedClassifierCV(
    base_estimator=bst_,
    method='isotonic',
    cv=5
)
calibrated_clf.fit(X_train, y_train)
calibrated_clf.set_params(**customized_lgbm_params)

然而,很明显,它不起作用,因为这些是将数据拟合到模型中的特定参数

我的问题是:如何定义一个包含我已经定义的LGBMClassifier.fit的所有特性(例如提前停止、应用权重、回调)的管道


Tags: base参数定义rate分类器trainparamscurrent