Saving output of confusionMatrix as a .csv table

纵然是瞬间 提交于 2019-12-05 21:54:55

Ok, so if you inspect the output of confusionMatrix(xtab, prevalence = 0.25) , it's a list:

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"

From here on you select the appropriate objects that you want to create a csv from and make a data.frame that will have a column for each variable. In your case, this will be:

tocsv <- data.frame(cbind(t(cm$overall),t(cm$byClass)))

# You can then use
write.csv(tocsv,file="file.csv")

Using caret package

results <- confusionMatrix(pred, truth)

as.table(results) gives

         Reference
Prediction  X1  X0
        X1  36  29
        X0 218 727

as.matrix(results,what="overall") gives

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

and as.matrix(results, what = "classes") gives

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

Using these and write.csv command you can get the entire confusionMatrix info

The absolute easiest solution is to simply write out using readr::write_rds. You can export and import all while keeping the confusionMatrix structure intact.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!