如何计算ROCR包装中指定截止值的平均灵敏度和特异性?

时间:2013-08-25 02:51:21

标签: r roc

我使用ROCR包来绘制ROC曲线。代码如下:

pred <- prediction(my.pred, my.label)
perf <- performance(my.pred, 'tpr', 'fpr')
plot(perf,avg="threshold")

我的predperf对象不是矢量而是列表,因此我可以获得平均ROC曲线。 谁能告诉我如何计算ROCR包装中指定截止值的平均灵敏度和特异性?

1 个答案:

答案 0 :(得分:3)

实际上,ROCR对此任务来说太过分了。 performance ROCR函数返回其输入中存在的每个分数的效果指标。所以,理论上你可以做到以下几点:

library(ROCR)
set.seed(123)
N <- 1000
POSITIVE_CASE <- 'case A'
NEGATIVE_CASE <- 'case B'
CUTOFF <- 0.456

scores <- rnorm(n=N)
labels <- ifelse(runif(N) > 0.5, POSITIVE_CASE, NEGATIVE_CASE)



pred <- prediction(scores, labels)
perf <- performance(pred, 'sens', 'spec')

此时perf包含许多有用的信息:

  > str(perf)
  Formal class 'performance' [package "ROCR"] with 6 slots
  ..@ x.name      : chr "Specificity"
  ..@ y.name      : chr "Sensitivity"
  ..@ alpha.name  : chr "Cutoff"
  ..@ x.values    :List of 1
  .. ..$ : num [1:1001] 1 1 0.998 0.996 0.996 ...
  ..@ y.values    :List of 1
  .. ..$ : num [1:1001] 0 0.00202 0.00202 0.00202 0.00405 ...
  ..@ alpha.values:List of 1
  .. ..$ : num [1:1001] Inf 3.24 2.69 2.68 2.58 ...

现在,您可以在perf@alpha.values中搜索您的分数截止值,并找到相应的灵敏度和特异性值。如果您在perf@alpha.values中找不到确切的截止值,则必须进行插值:

ix <- which.min(abs(perf@alpha.values[[1]] - CUTOFF)) #good enough in our case
sensitivity <- perf@y.values[[1]][ix] #note the order of arguments to `perfomance` and of x and y in `perf`
specificity <- perf@x.values[[1]][ix]

这给了你:

> sensitivity
[1] 0.3319838
> specificity
[1] 0.6956522

但是有一种更简单,更快捷的方法:只需将标签字符串转换为二进制矢量并直接计算指标:

binary.labels <- labels == POSITIVE_CASE
tp <- sum( (scores > threshold) & binary.labels )
sensitivity <- tp / sum(binary.labels)
tn <- sum( (scores <= threshold) & (! binary.labels))
specificity <- tn / sum(!binary.labels)

这给了你:

> sensitivity
[1] 0.3319838
> specificity
[1] 0.6956522
相关问题