Order confusion matrix in R

14,645

Try this then redo your code:

 cross.m$Observations <- factor( cross.m$Observations, 
                              levels=c("Underweight","Normal","Overweight") )
 cross.m$Predicted<- factor( cross.m$Predicted, 
                              levels=c("Underweight","Normal","Overweight") )
conf <- table(Predicted, Observations)

library(caret) 
f.conf <- confusionMatrix(conf)
print(f.conf)

Ordinary matrix methods would probably not work since a caret confusion matrix object is a list.

Share:
14,645

Related videos on Youtube

SamuelNLP
Author by

SamuelNLP

Updated on June 04, 2022

Comments

  • SamuelNLP
    SamuelNLP almost 2 years

    I've created a confusion matrix from the observations and its predictions in 3 classes.

    classes=c("Underweight", "Normal", "Overweight")
    

    When I compute the confusion matrix, it organizes the classes in the table alphabetical. Here is my code.

    # Confusion matrix
    Observations <- bmi_classification(cross.m$bmi)
    Predicted <- bmi_classification(cross.m$cvpred)
    
    conf <- table(Predicted, Observations)
    
    library(caret) 
    f.conf <- confusionMatrix(conf)
    print(f.conf)
    

    This produces this output:

    Confusion Matrix and Statistics
    
                 Observations
    Predicted     Normal Overweight Underweight
      Normal          17          0           1
      Overweight       1          4           0
      Underweight      1          0           1
    

    So, I would like it to first Underweight, then normal and finally Overweight. I've tried to pass the order to the matrix as an argument but no luck with that.

    EDIT:

    I tried reordering it,

    conf <- table(Predicted, Observations)
    
    reorder = matrix(c(9, 7, 8, 3, 1, 2, 6, 4, 5), nrow=3, ncol=3)
    
    conf.reorder <- conf[reorder]
    

    but I'm getting, [1] 1 1 0 1 17 1 0 0 4

    • priyanka
      priyanka about 10 years
      This might help
  • SamuelNLP
    SamuelNLP about 10 years
    The bmi_classification function turns a number of bmi into the respective class. Example, if cross.m$bmi = 15 the it returns Underweight, so I don't see how that can help.
  • IRTFM
    IRTFM about 10 years
    I editted my response to fit your new code. Although it remains untested in the absence of a reproducible example.