Error in Confusion Matrix : the data and reference factors must have the same number of levels Error in Confusion Matrix : the data and reference factors must have the same number of levels r r

Error in Confusion Matrix : the data and reference factors must have the same number of levels


Do table(pred) and table(testing$Final). You will see that there is at least one number in the testing set that is never predicted (i.e. never present in pred). This is what is meant why "different number of levels". There is an example of a custom made function to get around this problem here.

However, I found that this trick works fine:

table(factor(pred, levels=min(test):max(test)),       factor(test, levels=min(test):max(test)))

It should give you exactly the same confusion matrix as with the function.


confusionMatrix(pred,testing$Final)

Whenever you try to build a confusion matrix, make sure that both the true values and prediction values are of factor datatype.

Here both pred and testing$Final must be of type factor. Instead of check for levels, check the type of both the variables and convert them to factor if they are not.

Here testing$final is of type int. conver it to factor and then build the confusion matrix.


I had the same issue. I guess it happened because data argument was not casted as factor as I expected.Try:

confusionMatrix(pred,as.factor(testing$Final))

hope it helps