如何在同一张图中为两个模型制作漂亮的ROC曲线?

问题描述 投票:0回答:1

我已经训练了两个 xgboost 模型,比如 model1 和 model2。我有每个模型的 AUC 分数,我希望它们出现在图中。我想在同一个图中为两个模型制作漂亮的 ROC 曲线。像这样的东西:

我该怎么做?

我通常使用图书馆 pROC,我知道我需要从每个模型中提取分数和真相,对吗?

所以可能是这样的:

roc1 = roc(model1$truth, model1$scores)
roc2 = roc(model2$truth, model2$scores)

我还需要每个模型的 fpr 和 tpr:

D1 = data.frame = (fpr = 1 - roc1$specificities, tpr = roc1$sensitivities)
D2 = data.frame = (fpr = 1 - roc2$specificities, tpr = roc2$sensitivities)

然后我可以添加箭头来指出哪条曲线是:

arrows = tibble(x1 = c(0.5, 0.13) , x2 = c(0.32, 0.2), y1 = c(0.52, 0.83), y2 = c(0.7,0.7) )

最后ggplot:(这部分不见了)

ggplot(data = D1, aes(x = fpr, y = tpr)) + 
geom_smooth(se = FALSE) + 
geom_smooth(data = D2, color = 'red', se = FALSE) + 
annotate("text", x = 0.5, 0.475, label = 'score of model 1') + 
annotate("text", x = 0.13, y = 0.9, label = scores of model 2') +

所以我需要两件事的帮助:

  1. 如何从模型中获取正确的信息来制作 ROC 曲线?我如何获得 truthprediction scorestruth可能只是训练集中目标特征的标签?

  2. 如何继续代码?到目前为止我的代码正确吗?

r machine-learning ggplot2 roc
1个回答
1
投票

您可以使用 pROC 中的 coords 获得数据框中的灵敏度和特异性。在第一次附加一个列标记每个集合为模型 1 或模型 2 后,只需 rbind 两个模型的结果。要获得带有自动标签的平滑 ROC,您可以使用 geomtextpath 包中的 geom_textsmooth

library(pROC)
library(geomtextpath)

roc1 <- roc(model1$truth, model1$scores)
roc2 <- roc(model2$truth, model2$scores)

df <- rbind(cbind(model = "Model 1", coords(roc1)), 
            cbind(model = "Model 2", coords(roc2)))

ggplot(df, aes(1 - specificity, sensitivity, color = model)) +
  geom_textsmooth(aes(label = model), size = 7, se = FALSE, span = 0.2,
                  textcolour = "black", vjust = 1.5, linewidth = 1,
                  text_smoothing = 50) +
  geom_abline() +
  scale_color_brewer(palette = "Set1", guide = "none", direction = -1) +
  scale_x_continuous("False Positive Rate", labels = scales::percent) +
  scale_y_continuous("True Positive Rate", labels = scales::percent) +
  coord_equal(expand = FALSE) +
  theme_classic(base_size = 20) +
  theme(plot.margin = margin(10, 30, 10, 10)) 


使用的数据

set.seed(2023)

model1 <- model2 <- data.frame(scores = rep(1:100, 50))
p1 <- model2$scores + rnorm(5000, 0, 20)
p2 <- model1$scores/100

model1$truth <- rbinom(5000, 1, (p1 - min(p1))/diff(range(p1)))
model2$truth <- rbinom(5000, 1, p2)
© www.soinside.com 2019 - 2024. All rights reserved.