You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

XGBoost eval_metric参数使用遇两类报错,求解决方案

解决XGBoost中eval_metric参数的两类TypeError错误

错误原因分析

错误1:TypeError: fit() got an unexpected keyword argument 'eval_metric'

XGBoost的scikit-learn兼容接口(如XGBClassifier)的fit()方法不支持传入eval_metric参数,这个参数只能在模型初始化时设置,或者通过set_params()方法修改。

错误2:TypeError: 2 different eval_metricare provided. Use the one in constructor orset_params instead.

你在初始化XGBClassifier时已经指定了eval_metric,若后续尝试重复设置(哪怕是错误地在fit()里传参),就会触发冲突提示。另外代码存在变量名错误:eval_metric_list未定义,应为之前定义的eval_metric。

修复后的代码示例

# 定义评估指标
eval_metric = ["error", "logloss"]

# 初始化模型时设置eval_metric
classifier = XGBClassifier(
    objective=objective,
    booster="gbtree",
    eval_metric=eval_metric,
    subsample=0.8,
    colsample_bytree=1,
    random_state=1,
    use_label_encoder=False
)

# 拟合模型,仅传入eval_set和verbose,不要传eval_metric
eval_set = [(X_train, y_train), (X_test, y_test)]
classifier.fit(X_train, y_train, eval_set=eval_set, verbose=False)

可选:后续修改评估指标的方式

如果需要在初始化后修改eval_metric,可以用set_params()方法:

classifier.set_params(eval_metric=["auc", "error"])
classifier.fit(X_train, y_train, eval_set=eval_set, verbose=False)

内容的提问来源于stack exchange,提问作者Hamza Elbrek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 19:54:40