Python XGBoost 分类器无法`预测`:`TypeError:不支持数据类型`

问题描述

我有一个这样的数据集:

print(X_test.dtypes)
metric1                    int64
rank                     float64
device_type                 int8
NA_estimate              float64

当我尝试对该数据集进行预测时,出现以下错误

y_test_pred_xgb = clf_xgb.predict(xgb.DMatrix(X_test))
TypeError: Not supported type for data.<class 'xgboost.core.DMatrix'>

我进行了一些搜索,但只找到了导致问题的 object 变量数据类型的讨论。我的数据是否有其他问题,还是其他问题?我看过各种博客kaggle 代码,但运气不佳。

解决方法

在将数据帧传递给 .values 之前,使用 xgb.DMatrix 将数据帧转换为 numpy 数组时遇到了同样的错误。

dtest = xgb.DMatrix(X_test.values)

根据以下帖子 https://datascience.stackexchange.com/a/43805/87921,我发现 xgboost 从 0.81 版开始直接支持 pandas DataFrames,因此不需要调用 DMatrix。这在我的情况下有效(我使用的是 1.3.3 版)

model = XGBRegressor().fit(X_train,y_train)  # X_train,y_train and X_test are DataFrames
predictions = model.predict(X_test)

希望有帮助!