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