井出草平の研究ノート

ROC曲線と正診率[R]

ROC(Receiver Operating Characteristic)曲線は、X軸に偽陽性率、Y軸に真陽性率をとって描かれる。 ROCは、すべての陽性を識別するために、どれだけの間違いを犯しているかがわかる。

今回は正診率について。

ROC曲線下の面積およびブートストラップによる95%信頼区間についてはこちら。 https://ides.hatenablog.com/entry/2019/10/08/152927

ROC曲線のサンプルサイズの推定についてはこちら。 https://ides.hatenablog.com/entry/2019/10/09/102040

データ作成

cls = c('P', 'P', 'N', 'P', 'P', 'P', 'N', 'N', 'P', 'N', 'P',
        'N', 'P', 'N', 'N', 'N', 'P', 'N', 'P', 'N')
score = c(0.9, 0.8, 0.7, 0.6, 0.55, 0.51, 0.49, 0.43, 0.42, 0.39, 0.33, 
          0.31, 0.23, 0.22, 0.19, 0.15, 0.12, 0.11, 0.04, 0.01)
dat <- cbind(cls, score)
colnames(dat)<- c("cls","score")

データこちら。

  cls score
1   P  0.90
2   P  0.80
3   N  0.70
4   P  0.60
5   P  0.55
6   P  0.51

パッケージの読み込み

library(ROCR)

predictionの設定

pred <- prediction(df1$score, df1$cls)

performanceの設定

tpr: 真陽性率 (TP/(TP+FN) fpr: 偽陽性率(FP/(FP+TN)

perf <- performance(pred, measure ="tpr", x.measure = "fpr") ## rocのデータ,Y軸、X軸の名前

プロット

plot(perf)

f:id:iDES:20210903152836p:plain

AUCの計算

res01 <- performance(pred, measure = "auc")
res01@y.values

正診率の計算

  • 正診率=(TP+TN)/総数
  • 感度=TP/(TP+FN)
  • 特異度=TN/(FP+TN)
Cutoff <- unlist(pred@cutoffs) # カットオフポイント
TP <- unlist(pred@tp) # TP
FP <- unlist(pred@fp) # FP
FN <- unlist(pred@fn) # FN
TN <- unlist(pred@tn) # TN
Sensitivity <- unlist(pred@tp)/(unlist(pred@tp)+unlist(pred@fn)) # Sensitivity
Specificity <- unlist(pred@tn)/(unlist(pred@fp)+unlist(pred@tn)) # Specificity
Accuracy <- ((unlist(pred@tp)+unlist(pred@tn))/nrow(dat)) # Accuracy

テーブルにまとめる。

table <- data.frame(Cutoff, TP, FP, FN, TN,Sensitivity, Specificity, Accuracy)
table

結果。

   Cutoff TP FP FN TN Sensitivity Specificity Accuracy
1     Inf  0  0 10 10         0.0         1.0     0.50
2    0.90  1  0  9 10         0.1         1.0     0.55
3    0.80  2  0  8 10         0.2         1.0     0.60
4    0.70  2  1  8  9         0.2         0.9     0.55
5    0.60  3  1  7  9         0.3         0.9     0.60
6    0.55  4  1  6  9         0.4         0.9     0.65
7    0.51  5  1  5  9         0.5         0.9     0.70
8    0.49  5  2  5  8         0.5         0.8     0.65
9    0.43  5  3  5  7         0.5         0.7     0.60
10   0.42  6  3  4  7         0.6         0.7     0.65
11   0.39  6  4  4  6         0.6         0.6     0.60
12   0.33  7  4  3  6         0.7         0.6     0.65
13   0.31  7  5  3  5         0.7         0.5     0.60
14   0.23  8  5  2  5         0.8         0.5     0.65
15   0.22  8  6  2  4         0.8         0.4     0.60
16   0.19  8  7  2  3         0.8         0.3     0.55
17   0.15  8  8  2  2         0.8         0.2     0.50
18   0.12  9  8  1  2         0.9         0.2     0.55
19   0.11  9  9  1  1         0.9         0.1     0.50
20   0.04 10  9  0  1         1.0         0.1     0.55
21   0.01 10 10  0  0         1.0         0.0     0.50

正確性が最も高いのは?

max(table$Accuracy)

Answer: 0.7