Skip to content

Instantly share code, notes, and snippets.

@tetlabo
Created September 2, 2021 07:29
Show Gist options
  • Save tetlabo/21646efb62b2eb5c26f50492ecfefa5d to your computer and use it in GitHub Desktop.
Save tetlabo/21646efb62b2eb5c26f50492ecfefa5d to your computer and use it in GitHub Desktop.
RでROC曲線 (precrecパッケージ)
library(tidyverse)
# 適当なロジスティック回帰モデルを作る
b <- 10
a <- 3
x <- rnorm(100, mean = 10, sd = 5)
e <- rnorm(100, sd = 12)
y <- (a * x) + b + e
y <- if_else(y >= mean(y), 1, 0)
logi_res <- glm(y ~ x, family = binomial(link = "logit"))
# precrecパッケージの読み込み
library(precrec)
# 実測値と予測値をmmdata形式?でまとめる
# 実際には、検証用データでやったほうが良いに決まっている
logi_mmdata <- mmdata(fitted(logi_res), y)
# ROC曲線などの指標を算出する
# mode = "basic" オプションを指定すると正解率、適合率などが得られる
logi_curve <- evalmod(logi_mmdata)
# ggplot2でROC曲線を描画する
# library(ggplot2)
autoplot(logi_curve, "ROC") + theme_classic(base_family = "Source Han Code JP", base_size = 18) + theme(legend.position = "none")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment