r - 如何为不同的插入符号训练模型绘制 AUC ROC?

标签 r roc

这是一个代表

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 曲线以直观地比较两个模型?

最佳答案

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

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

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

这给了我们一个 data.frame,它有属于 0 类或 1 类的概率。让我们只使用 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))

ROC curves

关于r - 如何为不同的插入符号训练模型绘制 AUC ROC?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61814910/

相关文章:

python - 多标签分类中的 roc_curve 有斜率

r - 如何使用 ROCR 包计算 AUC

python - 使用具有不同 k 的 KNeighborsClassifier 在一张图中绘制所有 ROC 曲线

machine-learning - Keras ROC 与 Scikit ROC 不同吗?

tensorflow - Keras,训练期间验证集上的 auc 与 sklearn auc 不匹配

r - 如何使用 ggplot2 和 stat_bin 制作包含数字级别但没有观察值的条形图

r - 有没有办法简化 R 中利用循环的函数?

r - 如何控制目录在 R Markdown(PDF 输出)中的位置?

r - 将变化的 for 循环变量插入模型公式

r - 如何判断我的 R 脚本中没有使用哪些包?