[英]How to create the confusion matrix with stargazer and caret
我正在嘗試在sweave r中創建一個表,但它並沒有按我的意願出來。 這是我的代碼。
<<results='asis'>>=
## 2 class example
library(caret)
lvs <- c("normal", "abnormal")
truth <- factor(rep(lvs, times = c(86, 258)),
levels = rev(lvs))
pred <- factor(c(rep(lvs, times = c(54, 32)),
rep(lvs, times = c(27, 231))),
levels = rev(lvs))
xtab <- table(pred, truth)
Con.Mat <- confusionMatrix(xtab)
Con.Mat$table
Con.Mat$overall
Con.Mat$byClass
stargazer::stargazer(Con.Mat$table,head=FALSE,title = "Table")
stargazer::stargazer(Con.Mat$overall,head=FALSE,title = "overall")
stargazer::stargazer(Con.Mat$byClass,head=FALSE,title = "byClass")
@
帶有confusionMatrix()函數的R的輸出如下
> confusionMatrix(xtab)
Confusion Matrix and Statistics
truth
pred abnormal normal
abnormal 231 32
normal 27 54
Accuracy : 0.8285
95% CI : (0.7844, 0.8668)
No Information Rate : 0.75
P-Value [Acc > NIR] : 0.0003097
Kappa : 0.5336
Mcnemar's Test P-Value : 0.6025370
Sensitivity : 0.8953
Specificity : 0.6279
Pos Pred Value : 0.8783
Neg Pred Value : 0.6667
Prevalence : 0.7500
Detection Rate : 0.6715
Detection Prevalence : 0.7645
Balanced Accuracy : 0.7616
'Positive' Class : abnormal
使用觀星台時,請在此處輸入圖片說明
我遇到了同樣的問題,發現以下解決方法:
1)首先,您必須使用as.data.frame.matrix()將混淆矩陣從類表轉換為數據框。
ConfMat <- as.data.frame.matrix(Con.Mat$table)
2)然后,您可以使用摘要= FALSE參數,強制Stargazer將其輸出生成為數據框。
stargazer(ConfMat, head = FALSE, title = "Table", summary = FALSE)
以后,您可以通過在數據框中創建列或行總計來添加列或行。 另外,在中間的行之間添加百分比。
希望能幫助到你!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.