Xgboost 错误:标签必须位于 [0, num_class), num_class=2

Kum*_*esh 3 r xgboost

在为泰坦尼克号问题实施 XGboost 时出现此错误

xgb.iter.update(bst$handle, dtrain, iteration - 1, obj) 中的错误:
[03:26:03] amalgamation/../src/objective/multiclass_obj.cc:75:检查失败:label_error >= 0 && label_error < nclass SoftmaxMultiClassObj: 标签必须在 [0, num_class), num_class=2 但在标签中发现 2。

以下是我的代码:

#Parameter  ie no of class
nc <- length(unique(train_label))
nc
xgb_params <- list("objective"="multi:softprob",
                       "eval_metric"="mlogloss",
                       "num_class"=nc)
watchlist <- list(train=train_matix,test=test_matix)


#XGB Model
bst_model <- xgb.train(params = xgb_params,data = train_matix, nrounds = 100,watchlist = watchlist)
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?

小智 6

我是这样解决的。我的班级标签是 -1、0 和 1。所以我的 num_class=3。我必须将类标签增加 1 才能与范围 [0,3) 兼容。请注意,在此范围内,3 被排除,有效标签为 0、1、2。因此我转换后的类标签为 0、1、2。

此外,我更改了用于多类分类的代码。

目标已更改为“multi:softmax”,并添加了“num_class”参数。

xgb1 = XGBClassifier(
    learning_rate=0.1,
    n_estimators=1000,
    max_depth=5,
    min_child_weight=1,
    gamma=0,
    subsample=0.8,
    colsample_bytree=0.8,
    objective='multi:softmax',
    nthread=4,
    scale_pos_weight=1,
    seed=27,
    num_class=3,
    )
Run Code Online (Sandbox Code Playgroud)

在 modelfit() 函数中,'auc' 被替换为 'merror'

def modelfit(alg, dtrain, predictors, useTrainCV=True, cv_folds=5, early_stopping_rounds=50):
if useTrainCV:
    xgb_param = alg.get_xgb_params()
    #change the class labels
    dtrain[target] = dtrain[target] + 1
    xgtrain = xgb.DMatrix(dtrain[predictors].values, label=dtrain[target].values)

    cvresult = xgb.cv(xgb_param, xgtrain, num_boost_round=xgb_param['n_estimators'], nfold=cv_folds,
                      metrics='merror', early_stopping_rounds=early_stopping_rounds)
    alg.set_params(n_estimators=cvresult.shape[0])
    print(cvresult.shape[0])

# Fit the algorithm on the data
alg.fit(dtrain[predictors], dtrain[target], eval_metric='merror')

# Predict training set:
dtrain_predictions = alg.predict(dtrain[predictors])

# Print model report:
print("\nModel Report")
print("Accuracy : %.4g" % metrics.accuracy_score(dtrain[target].values, dtrain_predictions))
Run Code Online (Sandbox Code Playgroud)