2 votes

What is the reason for the Error: label must be in [0, num_class)

I am running a model using XGboost. I have the following error:

Error in xgb.iter.update(bst$handle, dtrain, iteration - 1, obj) : [12:23:02] amalgamation/../src/objective/multiclass_obj.cu:110: SoftmaxMultiClassObj: label must be in [0, num_class).

What could be the problem?

The code is as follows:

answer <- train$fine_labels
remove <- c("fine_labels")
trainning2 <- train[!(names(train) %in% remove)]
trainning_matrix <- as.matrix(trainning2)
dtrain <- xgb.DMatrix(data = trainning_matrix, label = answer)

nc <- length(unique(train$fine_labels))
nc <- as.numeric(as.character(nc))
xgb_params <- list("booster" = "gbtree", 
                   "eta" = 0.9944512, 
                   "max_depth" = 4, 
                   "subsample" = 0.8622684, 
                   "min_child_weight" = 0.7336961, 
                   "colsample_bytree" = 0.9545101, 
                   "gamma" = 8, 
                   "num_class" = nc - 1
model_xgb <- xgboost(data = dtrain, params = xgb_params, nrounds = 8, objective = "multi:softprob", eval_metric = "mlogloss")
pred <- predict(model_xgb, dtest)

1 votes

Welcome @ María Raquel Gómez López to Stack Overflow in Spanish, I suggest that you do the tour and win your first medal, it is also very important for you to read How to ask in order to improve your question and make it well received by the community, favoring your chances of getting good answers.


Hubert Ronald Points 1660

Viewing the report indicates that it is being assigned to dtrain a label that is not supported by the library XGBoost .

If you look at the previous link to the above library, the variable answer which will be the label from dtrain should be a vector of numeric type ({0,1}) i.e. the [0, num_class) that appears in the report.

For example answer <- c("1","2") it must be ensured that it starts with cero and that it is of numeric type:

    answer <- as.numeric(answer)-1
    class(answer); answer
    0 1

1 votes

Thanks @HubertRonald for your reply, I did indeed change the value of the "classes" to start from zero and it worked!


HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by: