python - 在XGB中使用F分数

标签 python xgboost evaluation-function

我正在尝试使用scikit-learn中的f分数作为xgb分类器中的评估指标。这是我的代码:

clf = xgb.XGBClassifier(max_depth=8, learning_rate=0.004,
                            n_estimators=100,
                            silent=False,   objective='binary:logistic',
                            nthread=-1, gamma=0,
                            min_child_weight=1, max_delta_step=0, subsample=0.8,
                            colsample_bytree=0.6,
                            base_score=0.5,
                            seed=0, missing=None)
scores = []
predictions = []
for train, test, ans_train, y_test in zip(trains, tests, ans_trains, ans_tests):
        clf.fit(train, ans_train, eval_metric=xgb_f1,
                    eval_set=[(train, ans_train), (test, y_test)],
                    early_stopping_rounds=900)
        y_pred = clf.predict(test)
        predictions.append(y_pred)
        scores.append(f1_score(y_test, y_pred))

def xgb_f1(y, t):
    t = t.get_label()
    return "f1", f1_score(t, y)

但是有一个错误:Can't handle mix of binary and continuous

最佳答案

问题在于f1_score试图比较非二进制目标和二进制目标,默认情况下,此方法进行二进制平均。来自documentation平均:字符串,[无,'二进制'(默认),'micro','macro','samples','weighted']”。

无论如何,错误是说您的预测像[0.001, 0.7889,0.33...]这样是连续的,但是您的目标是二进制[0,1,0...]。因此,如果您知道阈值,建议您在将结果发送到f1_score函数之前对其进行预处理。阈值的通常值为0.5

评估功能的测试示例。不再输出错误:

def xgb_f1(y, t, threshold=0.5):
    t = t.get_label()
    y_bin = [1. if y_cont > threshold else 0. for y_cont in y] # binarizing your output
    return 'f1',f1_score(t,y_bin)

如@smci所建议的,less_verbose/more_efficiency解决方案可以是:
def xgb_f1(y, t, threshold=0.5):
    t = t.get_label()
    y_bin = (y > threshold).astype(int) # works for both type(y) == <class 'numpy.ndarray'> and type(y) == <class 'pandas.core.series.Series'>
    return 'f1',f1_score(t,y_bin)

关于python - 在XGB中使用F分数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35400372/

相关文章:

python - 在 Numpy(或 Scipy)中计算斜率

r - xgboost泊松回归: label must be nonnegative

python - XGBoost/lightGBM 如何评估 ndcg 的排名任务?

python - 如何在 MacOS 上的 python 中安装 xgboost?

python - 使用 tf.optimizers.Adam.minimize() 时,对象不可调用

python - 为什么这个 Sqlite 日期比较有效?

python-3.6 - 用于Xgboost的基于F1的自定义评估功能-Python API

machine-learning - 如何为游戏创建良好的评估功能?

python - 在 Python 中实现类似缓冲区的结构