Re: [問題] 快速產生混淆矩陣

作者: rebe212296 (綠豆冰)   2020-10-02 22:24:10
※ 引述《totolink (吐吐林克)》之銘言:
: 大家好,
: 今天已經有整理好的資料表
: 一欄是真實類別,一欄是預測類別
: 是否有辦法直接透過整理好的資料表快速建立混淆矩陣呢?
因為沒有給例子,我在網路上找到下面這個資料參考
install.packages("caret", dependencies = c("Depends", "Suggests"))
library(caret)
Conf_mat<-structure(list(Predicted = c(100, 200, 200, 100, 100, 200, 200,
200, 100, 200, 500, 100, 100, 100, 100, 100,
100, 100, 500, 200
), Reference = c(600, 200, 200, 200, 200, 200, 200, 200, 500,
500, 500, 200, 200, 200, 200, 200, 200, 200, 200, 200)),
.Names = c("Predicted",
"Reference"), row.names = c(NA, 20L), class = "data.frame")
第一個解法是沒有用迴圈
conf_mat_tab<-as.vector(mode="list")
conf_mat_tab[[1]] <- caret::confusionMatrix(table(lapply(Conf_mat, factor,
levels = seq(100, 200, 100))))
conf_mat_tab[[2]] <- caret::confusionMatrix(table(lapply(Conf_mat, factor,
levels = seq(200, 300, 100))))
conf_mat_tab[[3]] <- caret::confusionMatrix(table(lapply(Conf_mat, factor,
levels = seq(300, 400, 100))))
conf_mat_tab[[4]] <- caret::confusionMatrix(table(lapply(Conf_mat, factor,
levels = seq(400, 500, 100))))
conf_mat_tab[[5]] <- caret::confusionMatrix(table(lapply(Conf_mat, factor,
levels = seq(500, 600, 100))))
下面是迴圈的做法
conf_mat_tab<-as.vector(mode="list")
L<-seq(100,600,100)
for (i in 1:c(length(L)-1)) {
conf_mat_tab[[i]] <- caret::confusionMatrix(table(lapply(Conf_mat, factor,
levels = seq(L[i],L[i+1],100))))
}
下面是印conf_mat_tab[[1]]的結果
> conf_mat_tab[[1]]
Confusion Matrix and Statistics
Reference
Predicted 100 200
100 0 9
200 0 6
Accuracy : 0.4
95% CI : (0.1634, 0.6771)
No Information Rate : 1
P-Value [Acc > NIR] : 1.000000
Kappa : 0
Mcnemar's Test P-Value : 0.007661
Sensitivity : NA
Specificity : 0.4
Pos Pred Value : NA
Neg Pred Value : NA
Prevalence : 0.0
Detection Rate : 0.0
Detection Prevalence : 0.6
Balanced Accuracy : NA
'Positive' Class : 100
不知道是不是原PO要的結果
作者: totolink (吐吐林克)   2020-10-02 22:46:00
感謝,後來發現把data frame的每欄都進行factor處理再table就可以了 XD
作者: EE1 (不鹵肋骨)   2020-10-30 16:14:00
table()最快XD

Links booklink

Contact Us: admin [ a t ] ucptt.com