我在将合适的 XGBRegressor 模型投入生产时遇到了这个问题,因此我提供了一个答案。因此,对于无法从 y 训练或测试 DataFrame 中选择列名的情况,这是一个解决方案,尽管可能存在交叉,这可能会有所帮助。
该模型适合 Pandas DataFrame,我试图将单行值作为 np.array 传递给 predict 函数。已经对数组的值进行了处理(反向标签编码等),数组都是数值。
我得到了熟悉的错误:
ValueError: feature_names mismatch后跟特征列表,后跟相同长度的列表:['f0', 'f1' ....]
虽然毫无疑问有更直接的解决方案,但我没有多少时间,这解决了问题:
- 将输入向量设为 Pandas 数据框:
series = {'feature1': [value],
'feature2': [value],
'feature3': [value],
'feature4': [value],
'feature5': [value],
'feature6': [value],
'feature7': [value],
'feature8': [value],
'feature9': [value],
'feature10': [value]
}
self.vector = pd.DataFrame(series)
- 获取训练模型知道的特征名称:
names = model.get_booster().feature_names
- 从输入向量 DataFrame(如上定义)中选择那些特征,并执行 iloc 索引:
result = model.predict(vector[names].iloc[[-1]])
我找到的iloc转换here。
选择特征名称——因为 Scikit Learn 实现中的模型没有feature_names 属性——使用我在上面的@Athar 帖子中找到的get_booster( ).feature_names。
查看the documentation 了解更多信息。
希望这会有所帮助。