【问题标题】:How to plot AUC ROC for different caret training models?如何为不同的插入符号训练模型绘制 AUC ROC?
【发布时间】:2020-09-01 00:34:09
【问题描述】:

这是一个代表

library(caret)
library(dplyr)

set.seed(88, sample.kind = "Rounding")

mtcars <- mtcars %>%
  mutate(am = as.factor(am))

test_index <- createDataPartition(mtcars$am, times = 1, p= 0.2, list = F)

train_cars <- mtcars[-test_index,]

test_cars <- mtcars[test_index,]

set.seed(88, sample.kind = "Rounding")
cars_nb <- train(am ~ mpg + cyl,
                data = train_cars, method = "nb", 
                trControl = trainControl(method = "cv", number = 10, savePredictions = "final"))

cars_glm <- train(am ~ mpg + cyl,
                 data = train_cars, method = "glm", 
                 trControl = trainControl(method = "cv", number = 10, savePredictions = "final"))

我的问题是,我将如何在单个图上创建 AUC ROC 曲线以直观地比较两个模型?

【问题讨论】:

标签: r roc


【解决方案1】:

我假设您想在测试集上显示 ROC 曲线,这与使用训练数据的评论 (ROC curve from training data in caret) 中指出的问题不同。

首先要做的是以概率 (type="prob") 的形式提取测试数据 (newdata=test_cars) 的预测:

predictions_nb <- predict(cars_nb, newdata=test_cars, type="prob")
predictions_glm <- predict(cars_glm, newdata=test_cars, type="prob")

这为我们提供了一个属于 0 类或 1 类概率的 data.frame。让我们仅使用 1 类的概率:

predictions_nb <- predict(cars_nb, newdata=test_cars, type="prob")[,"1"]
predictions_glm <- predict(cars_glm, newdata=test_cars, type="prob")[,"1"]

接下来我将使用 pROC 包为训练数据创建 ROC 曲线(免责声明:我是这个包的作者。还有其他方法可以实现结果,但这是我最熟悉的一种与):

library(pROC)
roc_nb <- roc(test_cars$am, predictions_nb)
roc_glm <- roc(test_cars$am, predictions_glm)

最后,您可以绘制曲线。要使用 pROC 包获得两条曲线,请使用 lines 函数将第二条 ROC 曲线的线添加到绘图中

plot(roc_nb, col="green")
lines(roc_glm, col="blue")

为了使其更具可读性,您可以添加一个图例:

legend("bottomright", col=c("green", "blue"), legend=c("NB", "GLM"), lty=1)

还有 AUC:

legend_nb <- sprintf("NB (AUC: %.2f)", auc(roc_nb))
legend_glm <- sprintf("GLM (AUC: %.2f)", auc(roc_glm))
legend("bottomright",
       col=c("green", "blue"), lty=1,
       legend=c(legend_nb, legend_glm))

【讨论】:

  • 非常感谢@Calimo 的富有洞察力的回答,我将使用您的方法而不是 MLeval evalm 函数确实要求将插入符号训练结果放入其中。有什么办法可以将 AUC 值添加到曲线中?
  • 非常感谢!我会使用你的 plot.roc 函数!
  • 如果它解决了你的问题,请记得接受这个答案。
猜你喜欢
  • 2015-08-02
  • 2020-10-01
  • 2018-07-06
  • 2015-09-17
  • 2019-05-02
  • 1970-01-01
  • 2019-03-08
  • 2019-04-11
  • 1970-01-01
相关资源
最近更新 更多