我正在尝试在ggplot中创建一条ROC曲线
我自己写的函数,但是当我将我的结果与来自社区(我相信更多)的roc_curve函数的结果进行比较时,我得到了不同的结果。
我想问一下在下面的函数中哪里有错误?
library(ggplot2)
library(dplyr)
library(yardstick)
n <- 300 # sample size
data <-
data.frame(
real = sample(c(0,1), replace=TRUE, size=n),
pred = sample(runif(n), replace=TRUE, size=n)
)
simple_roc <- function(labels, scores){
labels <- labels[order(scores, decreasing=TRUE)]
data.frame(TPR=cumsum(labels)/sum(labels), FPR=cumsum(!labels)/sum(!labels), labels)
}
simple_roc(data$real, data$pred) %>%
ggplot(aes(TPR, FPR)) +
geom_line()
yardstick::roc_curve(data, factor(real), pred) %>%
ggplot(aes(1 - specificity, sensitivity)) +
geom_line()发布于 2020-06-02 15:55:44
首先,您需要将ROC曲线锚定在点(0,0)和(1,1)中。
simple_roc <- function(labels, scores){
labels <- labels[order(scores, decreasing=TRUE)]
data.frame(
TPR = c(0, cumsum(labels)/sum(labels), 1),
FPR = c(0, cumsum(!labels)/sum(!labels), 1)
)
}那么数据在ggplot2中的呈现顺序就很重要了。反转线方向会让你离得更近一些:
yardstick::roc_curve(data, factor(real), pred) %>%
ggplot(aes(rev(1 - specificity), rev(sensitivity))) +
geom_line()https://stackoverflow.com/questions/62140022
复制相似问题