如何将一个tibble传递给caret :: confusionmatrix()?

时间:2018-06-06 15:31:02

标签: r dplyr r-caret confusion-matrix yardstick

考虑这个简单的例子:

data_frame(truth = c(1,1,0,0),
           prediction = c(1,0,1,0),
           n_obs = c(100,10,90,50))
# A tibble: 4 x 3
  truth prediction n_obs
  <dbl>      <dbl> <dbl>
1     1          1   100
2     1          0    10
3     0          1    90
4     0          0    50

我想将此tibble传递给caret::confusionMatrix,以便我一次拥有所需的所有指标(accuracyrecall等。)

如您所见,tibble包含计算性能统计信息所需的所有信息。例如,您可以在测试数据集中看到(此处不可用),有100个观察值,其中预测标签1与真实标签1匹配。但是,预测值90的{​​{1}}观察值实际上是误报。

我不想手动计算所有指标,并希望诉诸1

然而,事实证明这是令人惊讶的困难。在caret::confusionMatrix()上方拨打confusionMatrix(.)无效。这里有解决方案吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以使用以下内容。你必须将正类设置为1,否则0将被视为正类。

confusionMatrix(xtabs(n_obs ~ prediction + truth , df), positive = "1")

Confusion Matrix and Statistics

          truth
prediction   0   1
         0  50  10
         1  90 100

               Accuracy : 0.6             
                 95% CI : (0.5364, 0.6612)
    No Information Rate : 0.56            
    P-Value [Acc > NIR] : 0.1128          

                  Kappa : 0.247           
 Mcnemar's Test P-Value : 2.789e-15       

            Sensitivity : 0.9091          
            Specificity : 0.3571          
         Pos Pred Value : 0.5263          
         Neg Pred Value : 0.8333          
             Prevalence : 0.4400          
         Detection Rate : 0.4000          
   Detection Prevalence : 0.7600          
      Balanced Accuracy : 0.6331          

       'Positive' Class : 1    
相关问题