完美标签的 ROC 曲线由包 ROCR 颠倒产生

ROC curve for perfect labeling is produced upside down by package ROCR

代码

library(magrittr)
library(ROCR)
library(caret)
library(dplyr)
library(ggplot2)
data(GermanCredit)

GermanCredit %<>% arrange(Class)
GermanCredit$perfect_prob = sort(runif(nrow(GermanCredit)), decreasing = TRUE)

perf = performance(prediction(GermanCredit$perfect_prob, GermanCredit$Class), "tpr", "fpr")

data.frame(FalsePositive = unlist(perf@x.values),
           TruePositive = unlist(perf@y.values),
           method = rep(names(select(GermanCredit, perfect_prob)),
                        times=c(length(perf@x.values[[1]])))) %>%
ggplot(aes(x=FalsePositive, y=TruePositive, color=method)) +
  geom_line()

显示曲线

这显然是错误的。我究竟做错了什么?我一辈子都弄不明白。目标是 "Bad"。所以我确定

> levels(GermanCredit$Class)
[1] "Bad"  "Good"

虽然插入符号将第一个级别视为正 class,如使用

时所见
confusionMatrix(..., reference=GermanCredit$Class)

ROCR 认为后面的水平是积极的 class。逻辑是 1 是积极的 class 而 0 是消极的,并且由于 0 < 1"Bad" < "Good",ROCR 认为 "Good" 是积极的class这里。

解决方案是使用显式排序:

pred = prediction(GermanCredit$perfect_prob, GermanCredit$Class, label.ordering = c("Good", "Bad")
perf = performance(pred, "tpr", "fpr")

现在 "Good" < "Bad""Bad"prediction 认为是积极的 class。