Home > Software engineering >  How can I get confusion matrix values with a loop?
How can I get confusion matrix values with a loop?

Time:04-07

I tried to set a loop that could get specific values from a confusion matrix, but it was impossible for me.

This is the simple idea that I have in mind:

knn_MaC <-  function(train,test,label,test_label,k,positive){
  z <- matrix()
  for (i in k){
  Yp <- knn(train = train, test = test, cl= label,k = i)
  MaC <-  confusionMatrix(Yp,test_label,positive)
  z <- c(MaC$table[2],MaC$table[3])
  }}

As I said, I tried a lot of ways getting all kinds of errors instead. My idea is get this values to make a resume table.

CodePudding user response:

In the code below I've made some example data, and written a function that works correctly for me:

library(class)
library(caret)
library(data.table)

train <- rbind(iris3[1:25,,2], iris3[1:25,,3])
test <- rbind(iris3[26:50,,2], iris3[26:50,,3])
cl <- factor(c(rep("c",25), rep("s",25)))
test_label <- factor(c(rep("c",25), rep("s",25)))
k <- c(3,5,7,11)
positive <- NULL

knn_MaC <-  function(train,test,label,test_label,k,positive){
  z <- list()
  for (i in k){
    Yp <- knn(train = train, test = test, cl= label,k = i)
    MaC <-  confusionMatrix(Yp,test_label,positive)
    z[[i]] <- data.frame(k=i,
                       False_negative=MaC$table[2],
                       False_positive=MaC$table[3])
  }
  return(rbindlist(z))
}

final_results <- knn_MaC(train,test,label,test_label,k,positive)

If this doesn't work for you, you may need to provide an example of your data. Also, make sure you've cleared your environment completely before testing it.

  • Related