2013-05-02 73 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")