使用 ROCR 循环在一个独特的图中绘制多条 ROC 曲线

Loop to plot multiple ROC curves in one unique plot using ROCR

我正在使用 ROCR 包生成 ROC 曲线。我已经有一个循环可以从多个文件生成多个 ROC 图。我有30个文件。但我想将所有 30 条 ROC 曲线组合在一个图中(如果可能,使用不同的颜色)。我知道关于它的帖子很少,但我想使用我自己的循环并修改它。有什么建议吗?

我的脚本:

library(ROCR)
labels <- read.table(file="c:/data1/input")
files <- list.files(path="c:/data2/", pattern="*.txt")
for(i in files){
  predictions <- read.table(paste("c:/data2/",i,sep=""))
  pred <- prediction(predictions, labels)
  perf <- performance(pred,"tpr","fpr")
  pdf(paste0("c:/data2/", i,"ROC.pdf"))
  plot(perf)
  dev.off()
  }

当您对预测对象调用 plot() 时,它会生成一个新图。一种方法是使用 lines() 并直接调用值。首先我生成30个模型,因为你没有提供你的数据:

library(gbm)
library(mlbench)
library(colorspace)
data(DNA)
Pal = qualitative_hcl(30)
dat = DNA[,-c(1:2)]
dat$Class = as.numeric(dat$Class == "ei")
idx = split(sample(nrow(dat)),1:nrow(dat) %% 30)

mdl = lapply(1:30,function(i){
  mod = gbm(Class~.,data=dat[idx[[i]],])
  predictions = predict(mod,dat[-idx[[i]],],n.trees=10,type="response")
  labels = dat[-idx[[i]],"Class"]
  list(labels=labels,predictions=predictions)
})

names(mdl) = paste("model",1:30)

现在我们开始一个空白图,遍历 30 个模型,基本上你需要的部分是 lines(...) :

plot(NULL,xlim=c(0,1),ylim=c(0,1),
xlab="False positive rate",ylab="True positive rate")

for(i in 1:30){
  
  predictions = mdl[[i]]$predictions
  labels = mdl[[i]]$labels
  pred = prediction(predictions, labels)
  perf <- performance(pred,"tpr","fpr")
  
  lines(perf@x.values[[1]],perf@y.values[[1]],col=Pal[i])
  
  }

legend("bottomright",fill=Pal,names(mdl),ncol=5,cex=0.7)

对于您的示例,请尝试这样的操作:

files <- list.files(path="c:/data2/", pattern="*.txt")
mdl = lapply(files,read.table)
names(mdl) = gubs(".txt","",files)

plot(NULL,xlim=c(0,1),ylim=c(0,1),
xlab="False positive rate",ylab="True positive rate")

for(i in 1:30){
  
  pred = prediction(mdl[[i]], labels)
  perf <- performance(pred,"tpr","fpr")
  lines(perf@x.values[[1]],perf@y.values[[1]],col=Pal[i])
  
  }

legend("bottomright",fill=Pal,names(mdl),ncol=5,cex=0.7)