2013-05-02 133 views
28

我有一些模型,使用ROCR包预测类百分比的矢量,我有一个性能对象。用规范“tpr”,“fpr”绘制性能对象给我一个ROC曲线。从ROC曲线获取阈值

我在假阳性率(x)的特定阈值下比较模型。我希望从性能对象中获得真正的正确率(y)的值。更重要的是,我想获得用于生成该点的类别百分比阈值。

最接近阈值的假阳性率(x-value)的索引号应该给我适当的真阳性率(y-value)的索引号。我不确定如何获得该指数值。

更重要的是,我如何获得用于表示这一点的类概率阈值?

回答

48

这就是为什么str是我最喜欢的一个R函数:

library(ROCR) 
data(ROCR.simple) 
pred <- prediction(ROCR.simple$predictions, ROCR.simple$labels) 
perf <- performance(pred,"tpr","fpr") 
plot(perf) 
> str(perf) 
Formal class 'performance' [package "ROCR"] with 6 slots 
    [email protected] x.name  : chr "False positive rate" 
    [email protected] y.name  : chr "True positive rate" 
    [email protected] alpha.name : chr "Cutoff" 
    [email protected] x.values :List of 1 
    .. ..$ : num [1:201] 0 0 0 0 0.00935 ... 
     [email protected] y.values :List of 1 
     .. ..$ : num [1:201] 0 0.0108 0.0215 0.0323 0.0323 ... 
    [email protected] alpha.values:List of 1 
    .. ..$ : num [1:201] Inf 0.991 0.985 0.985 0.983 ... 

AHAH!这是一个S4 class,所以我们可以使用@来访问插槽。这里是你如何做一个data.frame

cutoffs <- data.frame([email protected][[1]], [email protected][[1]], 
         [email protected][[1]]) 
> head(cutoffs) 
     cut   fpr  tpr 
1  Inf 0.000000000 0.00000000 
2 0.9910964 0.000000000 0.01075269 
3 0.9846673 0.000000000 0.02150538 
4 0.9845992 0.000000000 0.03225806 
5 0.9834944 0.009345794 0.03225806 
6 0.9706413 0.009345794 0.04301075 

如果你想打的FPR的阈值,你可以子集这个data.frame找到下面这FPR最大阈值TPR:

cutoffs <- cutoffs[order(cutoffs$tpr, decreasing=TRUE),] 
> head(subset(cutoffs, fpr < 0.2)) 
      cut  fpr  tpr 
96 0.5014893 0.1495327 0.8494624 
97 0.4997881 0.1588785 0.8494624 
98 0.4965132 0.1682243 0.8494624 
99 0.4925969 0.1775701 0.8494624 
100 0.4917356 0.1869159 0.8494624 
101 0.4901199 0.1962617 0.8494624 
+3

你太了不起了。并感谢提到str。如果我对未来感到难过,我会采用它。 – Faydey 2013-05-03 01:03:12

+0

@ user24926很高兴帮助! – Zach 2013-05-03 02:33:23

+3

我真的很喜欢这个答案中的交互和迭代方法。 – 2013-05-04 07:40:30

5

2解决方案的基础上在ROCRpROC包:

threshold1 <- function(predict, response) { 
    perf <- ROCR::performance(ROCR::prediction(predict, response), "sens", "spec") 
    df <- data.frame(cut = [email protected][[1]], sens = [email protected][[1]], spec = [email protected][[1]]) 
    df[which.max(df$sens + df$spec), "cut"] 
} 
threshold2 <- function(predict, response) { 
    r <- pROC::roc(response, predict) 
    r$thresholds[which.max(r$sensitivities + r$specificities)] 
} 
data(ROCR.simple, package = "ROCR") 
threshold1(ROCR.simple$predictions, ROCR.simple$labels) 
#> [1] 0.5014893 
threshold2(ROCR.simple$predictions, ROCR.simple$labels) 
#> [1] 0.5006387 

参见OptimalCutpoints包,它提供了许多算法寻找最佳的阈值。

6

套餐pROC包括功能coords计算最佳的门槛:

library(pROC) 
my_roc <- roc(my_response, my_predictor) 
coords(my_roc, "best", ret = "threshold")