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

如何使用R中的函数创建混淆矩阵,r,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) actual插入符号库提供了大量的机器学习方法 library(caret) actual <- as.factor(c(1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0)) predicted <- as.factor(c(1, 1

我创建了以下数据集:

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)

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

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")
库(插入符号)

实际的

如果您想要与您所发布的相同的输出格式,则考虑此函数

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

你好@Mbalenhle,很高兴知道这一点。如果这个或任何其他的答案已经解决了你的问题,请通过点击复选标记来考虑。这向更广泛的社区表明,你已经找到了一个解决方案,并给回答者和你自己带来了一些声誉。没有义务这样做。请尝试
表格(实际、预测)
confusion <- function(pred, real) {
  stopifnot(all(c(pred, real) %in% 0:1))
  table(matrix(c("TN", "FP", "FN", "TP"), 2L)[cbind(pred, real) + 1L])
}
> confusion(predicted, actual)

FN FP TN TP 
 1  2  5  4