predict.xgb.Booster("multi:softprob"目标):理解维度矩阵列与输入类别的对应关系
multi:softprob Predictions to Original Categories & Generate Class Labels Great question—this is a common point of confusion when working with multiclass xgboost models, so let's break it down clearly.
Step 1: Understand the Category Mapping Between pred Columns and Original Species
The key here lies in how you encoded your labels before training the model:
iris$Species <- as.factor(iris$Species) # Then you converted labels to numeric with: as.numeric(iris$Species)-1
When you convert a factor to numeric in R, it uses the order of the factor's levels as the numeric code. For the iris dataset, the default levels of Species are:
levels(iris$Species) # Output: [1] "setosa" "versicolor" "virginica"
Since you subtracted 1 from the numeric factor values, your model's internal category codes are:
0→ "setosa"1→ "versicolor"2→ "virginica"
The predict() output with reshape = TRUE returns columns in the same order as the model's internal category codes:
V1= predicted probability for category0(setosa)V2= predicted probability for category1(versicolor)V3= predicted probability for category2(virginica)
To confirm this, you can always check the original factor levels directly in your code—this is the single most reliable way to map predictions back to your original classes.
Step 2: Generate the Vector of Highest-Probability Classes
Once you have the mapping sorted, generating the class labels is straightforward. Here are two common approaches:
Option 1: Get Numeric Class Codes (matching your training labels)
Use max.col() to find the index of the highest probability in each row, then subtract 1 to match your 0-based encoding:
# Get numeric class codes (0, 1, 2) pred_class_num <- max.col(pred) - 1
Option 2: Map Back to Original Species Names
Directly use the factor levels to convert the column indices into human-readable class names:
# Get original species names pred_class_name <- levels(iris$Species)[max.col(pred)]
For your example output where all rows have the highest probability in V1, pred_class_name will be a vector filled with "setosa"—which matches the first few rows of the iris dataset (all setosa).
Quick Validation Tip
To double-check the mapping, you can compare the predictions for a few known rows. For example, take the first row of the iris dataset (which is setosa):
# Predict for just the first row single_pred <- predict(mod, newdata = xgb.DMatrix(data.matrix(iris[1, 1:4])), reshape = TRUE) # The highest probability should be in V1, which maps to setosa
This confirms that the column order aligns with the original factor levels.
内容的提问来源于stack exchange,提问作者umbe1987

