XGBoost运行报typestr格式校验错误,该错误的含义是什么
XGBoost二分类建模
typestr校验报错说明 建模流程代码
- 特征集定义:
X = df[df.columns.drop("month_5_still_here")]
- 目标变量定义:
y = df["month_5_still_here"]
- 拆分数据集为训练集与测试集:
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size = 0.5, random_state = 12)
- 实例化XGBClassifier分类器:
xg_cl = xgb.XGBClassifier(n_estimators = 10, objective = "binary:logistic")
- 拟合训练集:
xg_cl.fit(x_train, y_train)
- 预测测试集标签:
y_pred = xg_cl.predict(x_test)
- 对比真实值与预测值:
pd.DataFrame({"Actual": y_test, "Predicted": y_pred})
触发的报错信息
XGBoostError: [16:42:58] c:\users\administrator\workspace\xgboost-win64_release_1.4.0\src\data\array_interface.h:139: Check failed: typestr.size() == 3 (2 vs. 3) : `typestr' should be of format <endian><type><size of type in bytes>.
报错具体含义
该错误是XGBoost解析输入数据的内存结构时触发的硬性校验失败:
- XGBoost要求输入的数组(由pandas DataFrame转换生成)的numpy类型描述符
typestr必须为3位字符,格式为「字节序标识 + 数据类型标识 + 单元素字节长度」 - 本次运行中XGBoost拿到的
typestr仅为2位,不符合格式要求,因此抛出异常
常见触发原因
- 特征集中存在非原生数值类型的列,比如category类型、object类型、布尔类型未做编码转换
- 低版本pandas与XGBoost 1.4.0存在兼容性问题,pandas输出的数组类型描述符格式不满足XGBoost的校验规则
- 数据存在未处理的缺失值、自定义扩展dtype等非常规数据结构
解决步骤
- 先将所有特征列转换为XGBoost兼容的标准数值类型:
for col in x_train.columns: x_train[col] = x_train[col].astype("float32") x_test[col] = x_test[col].astype("float32")
- 若存在类别型特征,先完成独热编码或标签编码再做类型转换:
# 独热编码示例 X = pd.get_dummies(X, drop_first=True)
- 填充所有缺失值:
# 均值填充示例 X = X.fillna(X.mean())
- 兼容性调整:可升级pandas至1.3.0以上版本,或降级XGBoost至1.3.x版本,适配双方的类型描述符规则
内容的提问来源于stack exchange,提问作者Sarmad Hassan
相关产品推荐
相关产品推荐

