python - 执行 randomSearchCV 时传递了多个评估指标
问题描述
我目前正在玩一个关于xgboost
. 在以下示例中,我将执行以下步骤:
- 从 sklearn 加载 iris 数据集并将其拆分为训练集和测试集。
- 声明一个我想探索的参数网格。
- 鉴于问题的多标签分类性质,我想根据 f1 分数评估我的模型。现在,要做到这一点,我声明了一种
xgb_f1
方法(假设 f1 分数不在 xgboost 中的默认评估指标中),以将算法目标指标与交叉验证中的指标对齐。 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
在您的参数中使用?
推荐阅读
- android - 如何使用 OKHTTP 在 Kotlin 中发出 post 请求?
- javascript - 如何在 JavaScript 中执行计算并将其显示在输入框中?
- python - 如果存在重复值,则合并所有子列表,同时删除所有重复项
- android - 应用程序可以检测到适用于 Android 的 UiAutomator2 驱动程序吗?
- asp.net-mvc-4 - 视图模型中的 IFormfile 未绑定
- reactjs - 如何使用酶/Jest 测试 useState
- python - 如何在 Django 中添加 SQLServer 全文搜索?
- unity3d - 无法冻结具有平移功能的对象的旋转
- scala - 如何异步管理表单请求
- angular - 如何使用角度剑道限制日期选择器中的范围选择