r – Error in Confusion Matrix : the data and reference factors must have the same number of levels
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.
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
r – Error in Confusion Matrix : the data and reference factors must have the same number of levels
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.
Related posts on Matrix :
- numpy – Python – Matrix outer product
- mathjax – how to write inline matrix in Latex
- numpy – Matrix exponentiation in Python
- Rank of a matrix in R
- algorithm – Difference between symmetric and asymmetric matrix
- powerbi – Power BI. Matrix two columns under one column
- Remove zeros column and rows from a matrix matlab
- Matrix power in R