xgboost报错 ValueError: feature_names mismatch

@创建于:20210107
@修改于:20210107,20210108

1、背景

XGBClassifier自带fit()、predict()方法。

当通过网格搜索,交叉验证后,获得了最佳的参数,形成模型,并保存。

当再次加载模型,对测试集进行预测时候,使用XGBClassifier自带predict()方法时候,发现出现该问题。即:ValueError(“feature_names mismatch: [‘ntp’, ‘pg’, ‘dbp’, ‘tsft’, ‘si’, ‘bmi’, ‘dpf’, ‘age’] [‘f0’, ‘f1’, ‘f2’, ‘f3’, ‘f4’, ‘f5’, ‘f6’, ‘f7’]\nexpected bmi, age, si, dpf, ntp, dbp, tsft, pg in input data\ntraining data did not have the following fields: f5, f3, f1, f4, f6, f7, f0, f2”,)

2、predict()介绍 ( xgboost==0.90)

(1)用法
predict(self, data, output_margin=False, ntree_limit=None, validate_features=True)

(2)参数及其含义

参数类型介绍
dataDMatrixThe dmatrix storing the input.
output_marginboolWhether to output the raw untransformed margin value.
ntree_limitintLimit number of trees in the prediction; defaults to best_ntree_limit if defined(i.e. it has been trained with early stopping), otherwise 0 (use all trees).
validate_featuresboolWhen this is True, validate that the Booster’s and data’s feature_names are identical. Otherwise, it is assumed that the feature_names are the same.
3、解决办法
3.1 把validate_features设置为False

预测时候代码为:model_xgb.predict(X_test.values, validate_features=False),X_test是dataframe格式,X_test.values是ndarray格式。

此时的假设是,模型训练时用的训练数据集的特征名称、特征数据和特征顺序,与验证集的数据特征名称、特征数据和特征顺序完全一致。

在训练集和验证集通过dataframe格式,用train_test_split来划分的时候,是一致的。

3.2 把输入的数据(dataframe类型)的列名进行对应修改

预测时候代码为:model_xgb.predict(X_test.values),X_test是dataframe格式,X_test.values是ndarray格式。

在数据(以dataframe结构)进行划分之前,对列名进行重命名。重命名为[‘f0’, ‘f1’, ‘f2’, ‘f3’, ‘f4’, ‘f5’, ‘f6’, ‘f7’]形式。这是XGB特征的命名格式。可通过model.get_booster().feature_names进行查看。

# 重命名,与featuer name一致
print('df_tmp columns original names are {}'.format(df_tmp.columns))
rename_dict = dict()
for index, value in enumerate(df_tmp.columns.values):
    rename_dict[value] = "f" + str(index)
df_tmp.rename(columns=rename_dict, inplace=True)
print('df_tmp columns new names are {}'.format(df_tmp.columns))
3.3 变更predit输入数据的格式

X_test是dataframe格式,修改下面代码。


y_pred = model_xgb.predict(data=X_test.values)
改成
y_pred = model_xgb.predict(data=X_test)

3.4 思考

(1)predict中的data,要求是DMatrix格式,但可以兼容dataframe格式。
(2)当data是dataframe类型时,XGBoost的特征名称就是列名。
(3)当data是ndarray类型时,XGBoost的特征名称默认是[‘f0’, ‘f1’, ‘f2’]样式。

  • 可修改dataframe的列名成[‘f0’, ‘f1’, ‘f2’]样式;
  • 可把validate_features设置成False。
4、参考链接

(1)解决xgboost报错 : ValueError: feature_names mismatch
(2)ValueError:feature_names不匹配
(3)成功解决 ValueError: feature_names mismatch training data did not have the following fields

  • 10
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值