【问题标题】:How to obtain class labels of xgboost predictions?如何获取 xgboost 预测的类标签?
【发布时间】:2020-03-18 07:00:51
【问题描述】:

我正在使用类似于以下示例的 xgboost,其中我将一些数值“重新编码”为 0、1、2 中的(数字)值,指示类标签。请注意,我没有将其转换为因子变量。

然后我使用 xgboost 来拟合模型并产生预测。

library(xgboost)

iris$Species <- runif(nrow(iris))

recode <- function(x){
  if(x >= 0 & x <= 0.33){
    x <- 0
  } else if(x > 0.33 & x <= 0.66){
    x <- 1
  } else if(x > 0.66){
    x <- 2
  }
} 

train <- xgb.DMatrix(data = as.matrix(iris[,-5]), 
                     label = sapply(iris$Species, FUN = recode))

bst <- xgboost(data = train,
               max_depth = 4, eta = 0.5, nrounds = 10, 
               objective = "multi:softprob",
               num_class = 3)

pred <- predict(bst, as.matrix(iris[, -5]), reshape = TRUE)

str(pred)

是否可以获取预测矩阵的列标签?或者我可以确定它们是根据我重新编码输入的数值排序的吗?

【问题讨论】:

    标签: r xgboost


    【解决方案1】:

    列的顺序与您的标签相同,因此是 0,1 和 2。可以肯定的是,您可以做一个混淆矩阵来检查您的预测是否正确:

    library(xgboost)
    set.seed(100)
    iris$Species <- runif(nrow(iris))
    
    train <- xgb.DMatrix(data = as.matrix(iris[,-5]), 
                         label = sapply(iris$Species, FUN = recode))
    
    bst <- xgboost(data = train,
                   max_depth = 4, eta = 0.5, nrounds = 10, 
                   objective = "multi:softprob",
                   num_class = 3)
    
    pred <- predict(bst, as.matrix(iris[, -5]), reshape = TRUE)
    # which.max tells you which column is most probable
    # we convert them back to 0-2, assuming column 1 corresponds to 0
    predicted = apply(pred,1,which.max)-1
    actual = sapply(iris$Species,recode)
    table(predicted,actual)
    

    结果是:

         actual
    predicted  0  1  2
            0 36  2  2
            1  4 48  4
            2  6  3 45
    

    因此,大多数预测为 0,1 或 2 的人都遵循预测的最高可能类别。

    或者如果你使用插入符号:

    caret::confusionMatrix(factor(predicted,levels=1:3),factor(actual,levels=1:3))
    

    【讨论】:

    • 这是我的预期,但我想知道,因为我没有在文档中找到关于此的具体信息。使用混淆矩阵是个好主意!
    • yes xgboost sux 有点数字编码。希望这对你有帮助:)
    猜你喜欢
    • 2017-08-19
    • 2017-12-19
    • 2022-01-25
    • 2017-09-15
    • 2020-03-07
    • 2018-11-05
    • 2018-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多