首页 > 解决方案 > 执行 randomSearchCV 时传递了多个评估指标

问题描述

我目前正在玩一个关于xgboost. 在以下示例中,我将执行以下步骤:

  1. 从 sklearn 加载 iris 数据集并将其拆分为训练集和测试集。
  2. 声明一个我想探索的参数网格。
  3. 鉴于问题的多标签分类性质,我想根据 f1 分数评估我的模型。现在,要做到这一点,我声明了一种xgb_f1方法(假设 f1 分数不在 xgboost 中的默认评估指标中),以将算法目标指标与交叉验证中的指标对齐。
  4. f1_macro使用我的评分函数(与分类器相同)实例化并拟合 RandomizedSearchCV 。

现在,在拟合搜索时,训练实例中会弹出以下消息:

Multiple eval metrics have been passed: 'validation_0-f1' will be used for early stopping.

一切似乎都得到了顺利的训练,但为什么在我的评估集上merror没有被覆盖eval_metric并被计算呢?

此外,据我从 xgboost 文档中可以看出,该算法通过默认最小化给定目标指标来工作,我是否应该在使用 f1 分数的情况下更改此行为?

完整的工作示例

import xgboost as xgb
from sklearn.model_selection import train_test_split, RandomizedSearchCV
from sklearn.metrics import f1_score
from sklearn.datasets import load_iris
import numpy as np

data = load_iris()
x = data.data
y = data.target
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.33)

param_grid = {
    "n_estimators": [100, 200, 300, 500, 600, 800],
    "max_depth":        [2, 4, 8, 16, 32, 70, 100, 150],
    "min_child_weight": [1],
    "subsample":        [1]
}


def xgb_f1(y, t, threshold=0.5):
    t = t.get_label()
    y_bin = (y > threshold).astype(int)
    y_bin = np.argmax(y_bin, axis=1)
    return "f1", f1_score(t, y_bin, average="macro")


fit_params = {
    "early_stopping_rounds": 42,
    "eval_set": [[x_test, y_test]],
    "eval_metric": xgb_f1
}

clf = xgb.XGBClassifier(objective="multi:softmax")
grid = RandomizedSearchCV(clf, param_grid, n_jobs=-1, cv=2, verbose=1, scoring="f1_macro")
grid.fit(x_train, y_train, **fit_params, verbose=True)
print(f"Best f1-score: {grid.best_score_}")
print(f"best params: {grid.best_params_}")

标签: pythonxgboost

解决方案


尝试"disable_default_eval_metric": 1在您的参数中使用?


推荐阅读