【问题标题】:R: Multiclass MatricesR:多类矩阵
【发布时间】:2021-05-04 10:33:48
【问题描述】:

我正在使用 R 编程语言。我正在尝试学习如何为多类变量(例如How to construct the confusion matrix for a multi class variable)制作“混淆矩阵”。

假设我生成一些数据并拟合决策树模型:

#load libraries

library(rpart)
library(caret)
    
#generate data

a <- rnorm(1000, 10, 10)

b <- rnorm(1000, 10, 5)

d <- rnorm(1000, 5, 10)
 


group_1 <- sample( LETTERS[1:3], 1000, replace=TRUE, prob=c(0.33,0.33,0.34) )


e = data.frame(a,b,d, group_1)

e$group_1 = as.factor(d$group_1)

#split data into train and test set
trainIndex <- createDataPartition(e$group_1, p = .8, 
                                  list = FALSE, 
                                  times = 1)
training <- e[trainIndex,]
test  <- e[-trainIndex,]


fitControl <- trainControl(## 10-fold CV
    method = "repeatedcv",
    number = 5,
    ## repeated ten times
    repeats = 1)
    
#fit decision tree model
    TreeFit <- train(group_1 ~ ., data = training, 
                     method = "rpart2", 
                     trControl = fitControl)

从这里,我可以将结果存储到“混淆矩阵”中:

pred <- predict(TreeFit,test)
table_example <- table(pred,test$group_1)

这满足了我的要求——但是这个“表格”需要我手动计算“A”、“B”和“C”的不同准确度指标(以及总准确度)。

我的问题:是否可以使用caret::confusionMatrix() 命令来解决这个问题?

例如

  pred <- predict(TreeFit, test, type = "prob")
  labels_example <- as.factor(ifelse(pred[,2]>0.5, "1", "0"))
  con <- confusionMatrix(labels_example, test$group_1)

这样,我就可以直接从混淆矩阵中访问准确度测量值。例如。 metric = con$overall[1]

谢谢

【问题讨论】:

    标签: r matrix data-manipulation decision-tree r-caret


    【解决方案1】:

    这是你要找的吗?

    pred <- predict(
      TreeFit,
      test)
    con <- confusionMatrix(
      test$group_1,
      pred)
    con
    con$overall[1]
    

    与以下输出相同:

    table(test$group_1, pred)
    

    加上准确度指标。

    【讨论】:

      猜你喜欢
      • 2014-10-02
      • 2016-12-29
      • 1970-01-01
      • 1970-01-01
      • 2018-09-25
      • 1970-01-01
      • 2016-06-29
      • 2019-04-16
      • 2014-09-19
      相关资源
      最近更新 更多