gpt4 book ai didi

python - 执行 randomizedSearchCV 时通过了多个评估指标

转载 作者:行者123 更新时间:2023-12-05 06:11:06 26 4
gpt4 key购买 nike

我目前正在玩一个关于 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_}")

最佳答案

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

关于python - 执行 randomizedSearchCV 时通过了多个评估指标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64144691/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com