这里有一个reprex
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曲线),它使用的是训练数据。
首先要做的是在测试数据上提取预测 (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))