简体   繁体   中英

How to create a confusion matrix using a function in R

I created the following data set:

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)

The following code works, but I want to use a function to create a confusion matrix instead:

#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"]))

What might be the code to do that?

The caret library offers a great collection of methods for machine learning

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")

If you want the same output format as the one you posted, then consider this 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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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