R:多类矩阵

R: Multiclass Matrices

我正在使用 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)

这满足了我的要求 - 但这个“table”需要我手动计算“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]

谢谢

这是您要找的吗?

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

与以下相同的输出:

table(test$group_1, pred)

加上准确性指标。