繁体   English   中英

如何使用 R 中的 function 创建混淆矩阵

[英]How to create a confusion matrix using a function in R

我创建了以下数据集:

actual <- c(1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0)
predicted <- c(1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0)

以下代码有效,但我想使用 function 来创建混淆矩阵:

#create new data frame
new_data <- data.frame(actual, predicted)
new_data["class"] <- ifelse(new_data["actual"]==0 & new_data["predicted"]==0, "TN",
                            ifelse(new_data["actual"]==0 & new_data["predicted"]==1, "FP",
                                   ifelse(new_data["actual"]==1 & new_data["predicted"]==0, "FN", "TP")))
(conf.val <- table(new_data["class"]))

执行此操作的代码可能是什么?

插入符号库提供了大量机器学习方法

library(caret)
actual <- as.factor(c(1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0))
predicted <- as.factor(c(1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0))

caret::confusionMatrix(data = predicted, actual, positive="1")

如果您想要与您发布的格式相同的 output 格式,请考虑这个 function

confusion <- function(pred, real) {
  stopifnot(all(c(pred, real) %in% 0:1))
  table(matrix(c("TN", "FP", "FN", "TP"), 2L)[cbind(pred, real) + 1L])
}

Output

> confusion(predicted, actual)

FN FP TN TP 
 1  2  5  4 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM