# 모형 평가 지표 — 같은 점수에서 임계값·혼동행렬·ROC 면적 연결
# 적용 범위: CRAN pROC의 ROC·AUC·좌표 정의를 학습용 점수 8개에 적용했습니다. 점수와 실제 범주는 가상 입력이며 학습한 모형의 성능이 아닙니다. pROC 패키지를 실행하거나 공식 aSAH 자료를 사용한 것이 아니라 base R로 임계값별 개수와 사다리꼴 면적을 직접 계산했습니다.
# 출처: https://cran.r-project.org/web/packages/pROC/refman/pROC.html#roc
# 출처: https://cran.r-project.org/web/packages/pROC/refman/pROC.html#auc
# 출처: https://cran.r-project.org/web/packages/pROC/refman/pROC.html#coords
# 실행 확인 환경: R version 4.6.2 (2026-10-29)
# 아래 코드를 실행하면 출력과 그림을 확인할 수 있습니다.

truth <- c(1, 1, 0, 1, 0, 0, 1, 0)
score <- c(0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2)
thresholds <- c(Inf, sort(unique(score), decreasing = TRUE))
coordinates <- function(threshold) {
  predicted <- score >= threshold
  tp <- sum(predicted & truth == 1)
  fp <- sum(predicted & truth == 0)
  fn <- sum(!predicted & truth == 1)
  tn <- sum(!predicted & truth == 0)
  c(TP = tp, FP = fp, FN = fn, TN = tn,
    TPR = tp / (tp + fn), FPR = fp / (fp + tn))
}
counts <- t(vapply(thresholds, coordinates, numeric(6)))
roc_table <- data.frame(임계값 = thresholds, counts, check.names = FALSE)
area <- sum(diff(roc_table$FPR) *
  (head(roc_table$TPR, -1) + tail(roc_table$TPR, -1)) / 2)
positive <- score[truth == 1]
negative <- score[truth == 0]
pairwise_area <- mean(outer(positive, negative, ">") +
  0.5 * outer(positive, negative, "=="))
at_half <- coordinates(0.5)
precision <- unname(at_half["TP"] / (at_half["TP"] + at_half["FP"]))
accuracy <- unname((at_half["TP"] + at_half["TN"]) / length(truth))
print(roc_table)
cat("임계값 0.5의 정밀도·정확도:\n")
print(c(정밀도 = precision, 정확도 = accuracy))
cat("사다리꼴 AUC와 양성·음성 쌍 비교:\n")
print(c(면적 = area, 쌍비교 = pairwise_area))
plot(roc_table$FPR, roc_table$TPR, type = "n", xlim = c(0, 1), ylim = c(0, 1),
  xaxs = "i", yaxs = "i", xlab = "거짓 양성률 FPR", ylab = "참 양성률 TPR",
  main = "가상 점수 8개의 임계값별 ROC와 면적")
polygon(c(roc_table$FPR, 1, 0), c(roc_table$TPR, 0, 0),
  col = adjustcolor("#2563EB", alpha.f = 0.14), border = NA)
abline(0, 1, lty = 2, col = "#9CA3AF")
lines(roc_table$FPR, roc_table$TPR, col = "#2563EB", lwd = 3)
points(roc_table$FPR, roc_table$TPR, pch = 16, col = "#2563EB")
points(at_half["FPR"], at_half["TPR"], pch = 19, col = "#D97706", cex = 1.5)
text(0.55, 0.64, "임계값 0.5", col = "#D97706", adj = 0, cex = 0.85)
legend("bottomright", c("AUC = 0.75", "TPR = FPR 기준선"),
  col = c("#2563EB", "#9CA3AF"), lty = c(1, 2), lwd = c(3, 1), bty = "n", cex = 0.85)
