【问题标题】:Saving output of confusionMatrix as a .csv table将confusionMatrix的输出保存为.csv表
【发布时间】:2016-04-22 22:07:57
【问题描述】:

我有以下代码导致类似表格的输出

 lvs <- c("normal", "abnormal")
 truth <- factor(rep(lvs, times = c(86, 258)),
                 levels = rev(lvs))
 pred <- factor(
                c(
                  rep(lvs, times = c(54, 32)),
                  rep(lvs, times = c(27, 231))),               
                levels = rev(lvs))

 xtab <- table(pred, truth)

 library(caret)
 confusionMatrix(xtab)

 confusionMatrix(pred, truth)
 confusionMatrix(xtab, prevalence = 0.25)   

我想将输出的以下部分导出为.csv

               Accuracy : 0.8285          
                 95% CI : (0.7844, 0.8668)
    No Information Rate : 0.75            
    P-Value [Acc > NIR] : 0.0003097       

                  Kappa : 0.5336          
 Mcnemar's Test P-Value : 0.6025370       

            Sensitivity : 0.8953          
            Specificity : 0.6279          
         Pos Pred Value : 0.8783          
         Neg Pred Value : 0.6667          
             Prevalence : 0.7500          
         Detection Rate : 0.6715          
   Detection Prevalence : 0.7645          
      Balanced Accuracy : 0.7616  

尝试将其写入.csv 表会导致错误消息:

write.csv(confusionMatrix(xtab),file="file.csv")
Error in as.data.frame.default(x[[i]], optional = TRUE, stringsAsFactors = stringsAsFactors) : 
cannot coerce class ""confusionMatrix"" to a data.frame

出于显而易见的原因,手动完成整个工作是不切实际的,而且容易出现人为错误。

关于如何将其导出为.csv 的任何建议?

【问题讨论】:

  • 你想写成“key:value”形式的东西吗? write.csv 根据错误期待一个 data.frame,所以你必须将你的结果按摩成它可以接受的东西。
  • 澄清一下,您必须获取confusionMatrix 的结果并将您需要的数据放入data.frame。
  • @steveb 是的,我现在明白了。 mroto 在下面的回复中非常清楚地概述了它。

标签: r csv export-to-csv confusion-matrix


【解决方案1】:

使用插入符号包

results <- confusionMatrix(pred, truth)

as.table(results)给了

         Reference
Prediction  X1  X0
        X1  36  29
        X0 218 727

as.matrix(results,what="overall")给了

Accuracy       7.554455e-01
Kappa          1.372895e-01
AccuracyLower  7.277208e-01
AccuracyUpper  7.816725e-01
AccuracyNull   7.485149e-01
AccuracyPValue 3.203599e-01
McnemarPValue  5.608817e-33

as.matrix(results, what = "classes")给了

Sensitivity          0.8953488
Specificity          0.6279070
Pos Pred Value       0.8783270
Neg Pred Value       0.6666667
Precision            0.8783270
Recall               0.8953488
F1                   0.8867562
Prevalence           0.7500000
Detection Rate       0.6715116
Detection Prevalence 0.7645349
Balanced Accuracy    0.7616279

使用这些和 write.csv 命令,您可以获得整个混淆矩阵信息

【讨论】:

    【解决方案2】:

    好的,所以如果您检查 confusionMatrix(xtab, prevalence = 0.25) 的输出,它是一个列表:

    cm <- confusionMatrix(pred, truth)
    str(cm)
    
        List of 5
     $ positive: chr "abnormal"
     $ table   : 'table' int [1:2, 1:2] 231 27 32 54
      ..- attr(*, "dimnames")=List of 2
      .. ..$ Prediction: chr [1:2] "abnormal" "normal"
      .. ..$ Reference : chr [1:2] "abnormal" "normal"
     $ overall : Named num [1:7] 0.828 0.534 0.784 0.867 0.75 ...
      ..- attr(*, "names")= chr [1:7] "Accuracy" "Kappa" "AccuracyLower" "AccuracyUpper" ...
     $ byClass : Named num [1:8] 0.895 0.628 0.878 0.667 0.75 ...
      ..- attr(*, "names")= chr [1:8] "Sensitivity" "Specificity" "Pos Pred Value" "Neg Pred Value" ...
     $ dots    : list()
     - attr(*, "class")= chr "confusionMatrix"
    

    从这里开始,您选择要从中创建 csv 的适当对象,并创建一个 data.frame,其中每个变量都有一个列。在你的情况下,这将是:

    tocsv <- data.frame(cbind(t(cm$overall),t(cm$byClass)))
    
    # You can then use
    write.csv(tocsv,file="file.csv")
    

    【讨论】:

    • 谢谢,这非常接近。实际上,我稍微更改了您的代码以获得我想要的:tocsv&lt;-as.data.frame(t(data.frame(cbind(t(cm$byClass),t(cm$overall))))) 但是,如果我可以问您,为什么您首先要转置?此外,在我们到达tocsv 阶段之前是否需要对数值进行四舍五入?我知道之后我可以命名列,将其舍入,然后替换它,但我想知道在初始阶段是否有更有效的方法。
    • 我还注意到代码更改了原始行95% CI : (0.7844, 0.8668),而是显示这两行:AccuracyLower 0.7844134380AccuracyUpper 0.8667985207。有没有办法保持原来的方式95% CI : (0.7844, 0.8668)
    • 默认情况下,byClassoverall 被命名为数字向量,它们不能以当前的形式绑定在一起。如果您转置它们,您将在值旁边创建名称的字符向量。至于四舍五入,可能是的,但如果你有新问题,通常最好提出新问题,而不是把它们塞进 cmets。
    【解决方案3】:

    我发现 capture.output 最适合我。

    它只是将您的输出复制为 .csv 文件

    (你也可以用.txt)

    capture.output(
    confusionMatrix(xtab, prevalence = 0.25),
     file = "F:/Home Office/result.csv")
    

    【讨论】:

      【解决方案4】:

      最简单的解决方案是使用readr::write_rds 简单地写出。您可以在保持confusionMatrix 结构完整的同时导出和导入所有内容。

      【讨论】:

        【解决方案5】:

        如果Acaret::confusionMatrix 对象,则:

        broom::tidy(A) %>% writexl::write_xlsx("mymatrix.xlsx")
        


        可选择将writexl 替换为write.csv()

        要将表格也包含在单独的工作表中:

        broom::tidy(A) %>% list(as.data.frame(A$table)) %>% writexl::write_xlsx("mymatrix.xlsx")
        

        【讨论】:

          猜你喜欢
          • 2020-09-19
          • 1970-01-01
          • 1970-01-01
          • 2015-08-07
          • 2022-11-25
          • 2020-10-26
          • 2018-07-07
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多