业务场景为多标签分类预测,传闻xgboost拿下了kaggle赛场大部分非xx数据的冠军,于是初试牛刀xgboost。
xgboost模型训练报错,百度翻了一圈没找到对应的解决方案,最终通过猜测可能的堵点以及逐个尝试破解,试出了解决方案。
本着开荒分享促进交流的原则,谨写此帖。
报错背景及内容
报错提示行是“xgb.train(plst, dtrain, num_rounds)”:
# xgboost模型训练
model = xgb.train(plst, dtrain, num_rounds)
报错关键提示,
简单版:
SoftmaxMultiClassObj: label must be in [0, num_class)
复杂版:
“xgboost.core.XGBoostError: [14:54:48] /opt/concourse/worker/volumes/live/7a2b9f41-3287-451b-6691-43e9a6c0910f/volume/xgboost-split_1619728204606/work/src/objective/multiclass_obj.cu:120: SoftmaxMultiClassObj: label must be in [0, num_class).”
报错提示详情如下2图:
较全代码如下:
# 模型调用
import time
from sklearn.datasets import load_iris
import xgboost as xgb
from xgboost import plot_importance, plot_tree
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score # 准确率
import matplotlib.pyplot as plt
import matplotlib
# %matplotlib inline
from sklearn.datasets import load_iris
from sklearn.datasets import load_boston
# # 记载样本数据集
# iris = load_iris()
# X, y = iris.data, iris.target
# print('X:\n',X,'\nY:\n',y)
# print('X.shape:\n',X.shape,'\ny.shape:\n',y.shape)
# 记载样本数据集
X, y = dt_sample, dt_label
print('X:\n',X,'\nY:\n',y)
print('X.shape:\n',X.shape,'\ny.shape:\n',y.shape)
# 数据集分割
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1234565)
# 算法参数
params = {
# 通用参数
'booster': 'gbtree',
'nthread': 4,
'silient': 0,
# 'num_feature': 5, # Boosting过程中用到的特征维数,设置为特征个数,xgboost会自动设置,无需人为设置。
'seed': 1000,
# 任务参数
'objective': 'multi:softmax', # 多分类问题
'num_class': 6, #类别总数,与multi softmax并用 6
# 提升参数
'gamma': 0.1,
'max_depth': 6,
'lambda': 2,
'subsample': 0.7,
'colsample_bytree': 0.7,
'min_child_weight': 3,
'eta': 0.1,
# 'eval_metric': 'auc'
}
plst = params.items()
print("plst:\n", plst)
plst = list(params.items())
print("list(plst):\n", plst)
# 生成数据集格式
dtrain = xgb.DMatrix(X_train, y_train)
#迭代次数,对于分类问题,每个类别的迭代次数。所以总的基学习器的个数 = 迭代次数*类别个数
num_rounds = 500
# xgboost模型训练
model = xgb.train(plst, dtrain, num_rounds)
# 对测试集进行预测
dtest = xgb.DMatrix(X_test)
y_pred = model.predict(dtest)
print("y_pred:\n", y_pred)
# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print('accuarcy:%.2f%%' % (accuracy * 100))
# 显示重要特征
plot_importance(model)
plt.show()
解决方案
把数据源中,所需预测的label标签列的数据取值范围,从1~6(即1,2,3,4,5,6),改成0~5(即0,1,2,3,4,5)。同样的代码,无需改动,重新运行一遍,即可成功。
PS:其实对于所有的分类,甚至是中文名称的分类,貌似有个数据处理过程,把所有的分类都转换成0~N的取值,再输入xgboost训练器。暂未有时间细看,如无意外应该就是one-hot(可以自行使用搜索引擎来确认)。
附数据源标签列改动前:取值1~6(模型训练报错)
数据源标签列改动后:取值0~5(模型训练正常)
解决过程
根据提示“label must be in [0, num_class)“,这似乎提示的是标签数据,即需要预测的多标签分类结果。
在报错前,label标签数据取值范围是1~6,即1,2,3,4,5,6等6种数字。
猜测有几种可能。
第一种:导入使用的数据集形态与xgboost训练器所需的数据集形态/格式有差异,例如dataframe与xgb专用数据集DMatrix的差异。
第二种,导入使用的数据集的数据,未经过分箱、one-hot等处理。后经尝试,是第二种。
完毕。