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

将XGBClassifier模型转换为ONNX时如何解决特征名称错误?

问题原因

你训练XGBClassifier时使用了自定义特征名(比如报错里的state),但onnxmltools的convert_xgboost方法默认要求特征名必须是f0、f1、f2这类数字索引格式,所以解析自定义特征名时触发了错误。

解决方法

方法1:重置模型特征名为默认格式

直接把XGBoost模型的特征名改成f%d格式,匹配转换器的要求:

import onnxmltools 
from skl2onnx.common.data_types import FloatTensorType

# 获取特征总数
num_features = X_train.shape[1]
# 重置模型的特征名为f0、f1...fn-1
xgb.xgb_category_cls._Booster.feature_names = [f"f{i}" for i in range(num_features)]

# 执行转换
initial_types = [('float_input', FloatTensorType([None, num_features]))]
xgb_onnx = onnxmltools.convert_xgboost(xgb.xgb_category_cls, initial_types=initial_types)
onnxmltools.utils.save_model(xgb_onnx, 'xgb_onnx.onnx')

方法2:改用skl2onnx转换(推荐)

onnxmltools的很多功能已整合到skl2onnx,后者对自定义特征名的支持更友好,无需修改特征名即可转换:

from skl2onnx import convert_sklearn
from skl2onnx.common.data_types import FloatTensorType

initial_types = [('float_input', FloatTensorType([None, X_train.shape[1]]))]
# XGBClassifier兼容scikit-learn接口,直接用convert_sklearn转换
xgb_onnx = convert_sklearn(xgb.xgb_category_cls, initial_types=initial_types)
onnxmltools.utils.save_model(xgb_onnx, 'xgb_onnx.onnx')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 13:33:10