You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

predict.xgb.Booster("multi:softprob"目标):理解维度矩阵列与输入类别的对应关系

How to Map xgboost 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 category 0 (setosa)
  • V2 = predicted probability for category 1 (versicolor)
  • V3 = predicted probability for category 2 (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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 20:33:14