计算R中混淆矩阵的准确度和精度

时间:2012-11-25 03:51:23

标签: r sentiment-analysis confusion-matrix

是否有任何工具/ R包可用于计算R?

中混淆矩阵的准确度和精度

The formula and data structure are here

4 个答案:

答案 0 :(得分:27)

是的,您可以使用confusion matrix计算R中的准确度和精度。它使用Caret package

以下是示例:

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)
# load Caret package for computing Confusion matrix
library(caret) 
confusionMatrix(xtab)

xtab的混淆矩阵将是这样的:

Confusion Matrix and Statistics

          truth
pred       abnormal normal
  abnormal      231     32
  normal         27     54

               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

       'Positive' Class : abnormal

所以这就是你想要的一切。

答案 1 :(得分:11)

@Harsh Trivedi

byClass 允许您从摘要中提取精度召回。 PPV很精确。敏感性是召回。 https://en.wikipedia.org/wiki/Precision_and_recall

library(caret)

result <- confusionMatrix(prediction, truth)
precision <- result$byClass['Pos Pred Value']    
recall <- result$byClass['Sensitivity']

我想你想要提取精度并召回来计算 f-measure 所以就这样了。

f_measure <- 2 * ((precision * recall) / (precision + recall))

我还发现了这个方便的在线计算器,用于健全检查。 http://www.marcovanetti.com/pages/cfmatrix/?noc=2

-bg

答案 2 :(得分:0)

如果有人遇到与我相同的问题,confusionMatrix()中的方法caret确实给出了敏感性/特异性。 然而,如果它被输入train类型的对象,它将运行不同的方法,confusionMatrix.train() 具有此信息。

解决方案是手动将datareferencetrain对象(分别为$pred$pred$$pred$obs)提供给confusionMatrix() } 方法。

答案 3 :(得分:0)

万一有人在看:多亏了BGA的上述回答,我更清楚地了解了如何读取confusionMatrix()输出,并意识到您可以从result$ByClass输出中获得F度量作为F1。 。

 result$byClass
         Sensitivity          Specificity       Pos Pred Value       Neg Pred Value 
           0.9337442            0.8130531            0.8776249            0.8952497 
           Precision               Recall                   F1           Prevalence 
           0.8776249            0.9337442            0.9048152            0.5894641 
      Detection Rate Detection Prevalence    Balanced Accuracy 
           0.5504087            0.6271571            0.8733987 

使用与上面的注释相同的公式计算下面的f_measure也会得出0.9048152。

您也可以从results$overall

获得准确度
result$overall
      Accuracy          Kappa  AccuracyLower  AccuracyUpper   AccuracyNull AccuracyPValue 
  8.841962e-01   7.573509e-01   8.743763e-01   8.935033e-01   5.894641e-01   0.000000e+00 
 McnemarPValue 
  2.745521e-13

或使用results的平衡精度