Roc曲线绘制我这样做对吗?
我编写了自己的代码来创建ROC曲线,然后根据定义计算AUC,但我从其他软件包中得到了不同的结果,我不明白我在这里做错了什么。这是我的密码。先谢谢你Roc曲线绘制我这样做对吗?,r,roc,R,Roc,我编写了自己的代码来创建ROC曲线,然后根据定义计算AUC,但我从其他软件包中得到了不同的结果,我不明白我在这里做错了什么。这是我的密码。先谢谢你 ROC.sort <- function(pred,true,vals,decreasing=FALSE){ sorted.index <- sort(vals,index=TRUE,decreasing=decreasing)$ix sort.pred <- pred[sorted.index] sort.
ROC.sort <- function(pred,true,vals,decreasing=FALSE){
sorted.index <- sort(vals,index=TRUE,decreasing=decreasing)$ix
sort.pred <- pred[sorted.index]
sort.true <- true[sorted.index]
return(list(sort.pred,sort.true))
}
ROC.ploter <- function(pred,true,add.to.plot=FALSE,color="black"){
index <- which(pred == 1)
vals <- true[index]
n.true <- 1/length(which(vals==1))
n.false <- 1/length(which(vals==0))
points <- data.frame(0,0)
last.point <- c(0,0)
for(i in 1:length(vals)){
if(vals[i] == 0){
next.point <- last.point + c(n.false,0)
last.point <- next.point
points <- rbind(points,next.point)
} else {
next.point <- last.point + c(0,n.true)
last.point <- next.point
points <- rbind(points,next.point)
}
}
if(add.to.plot){
points(x=points[,1],y=points[,2],col=color,type="l")
} else {
plot(x=points[,1],y=points[,2],xlab="False Positives",ylab="True Positives",
main= "ROC",type="l",col=color)
points(x=c(0,1),y=c(0,1),type='l')
}
return(points)
}
find.auc <- function(points){
x <- points[,1]
y <- points[,2]
result <- 0
n <- length(x)
x.prev <- x[1]
y.prev <- y[1]
for(i in 2:n){
x.curr <- x[i]
y.curr <- y[i]
if(x.curr == x.prev){
y.prev <- y.curr
} else {
result <- result + y.prev*(x.curr-x.prev)
x.prev <- x.curr
}
}
return(result)
}
ROC.sort您能否使用此代码和其他软件包中的函数添加一个工作示例我添加了一个工作示例。其他软件包来自python和ROCR。看起来像你的例子,曲线只是沿着对角线翻转,所以请确保在x上绘制1-spec,在y上绘制灵敏度。和1-auc
和Hmisc::somers2(truth[-training.index],pred.labs)['C']
给我大致相同的答案,所以我想你只需要调整一下。哦,糟糕,对不起,我确实调整了,我在ROC.sort中添加了一个额外的参数。但就我的数据而言,它远不如ROCR平滑,形状也不同。我将添加生成ROCR图的命令。
library(LiblineaR)
size <- 10000
truth <- rbinom(size,1,.9)
dat <- cbind(truth+rnorm(size),truth*rnorm(size))
training.index <- (1:(floor(2*size/3)))
model <- LiblineaR(data=dat[training.index,],labels=truth[training.index])
predicted <- predict(model,dat[-training.index,],decisionValues=TRUE)
pred.labs <- predicted$predictions
pred.scores <- predicted$decisionValues
sorted <- ROC.sort(pred.labs,truth[-training.index],pred.scores,decreasing=TRUE)
pts <- ROC.ploter(sorted[[1]],sorted[[2]])
auc <- find.auc(pts)
print(auc)
pred <- prediction(pred.scores, truth[testing.index])
perf <- performance(pred, measure = "tpr", x.measure = "fpr")
plot(perf, col=rainbow(10))
pts <- ROC.ploter(sorted[[1]],sorted[[2]],add.to.plot=TRUE)