Error in ConfusionMatrix the data and reference factors must have the same number of levels

青春壹個敷衍的年華 提交于 2019-11-28 21:18:28
Mayk Tulio

Try use:

confusionMatrix(table(Argument 1, Argument 2)) 

Thats worked for me.

Red

Maybe your model is not predicting a certain factor. Use the table() function instead of confusionMatrix() to see if that is the problem.

aristotll

Try specifying na.pass for the na.action option:

predictionsTree <- predict(treeFit, testdata,na.action = na.pass)

Change them into a data frame and then use them in confusionMatrix function:

pridicted <- factor(predict(treeFit, testdata))
real <- factor(testdata$catgeory)

my_data1 <- data.frame(data = pridicted, type = "prediction")
my_data2 <- data.frame(data = real, type = "real")
my_data3 <- rbind(my_data1,my_data2)

# Check if the levels are identical
identical(levels(my_data3[my_data3$type == "prediction",1]) , levels(my_data3[my_data3$type == "real",1]))

confusionMatrix(my_data3[my_data3$type == "prediction",1], my_data3[my_data3$type == "real",1],  dnn = c("Prediction", "Reference"))
EaswerC

Might be there are missing values in the testdata, Add the following line before "predictionsTree <- predict(treeFit, testdata)" to remove NAs. I had the same error and now it works for me.

testdata <- testdata[complete.cases(testdata),]

The length problem you're running into is probably due to the presence of NAs in the training set -- either drop the cases that are not complete, or impute so that you do not have missing values.

I had same issue but went ahead and changed it after reading data file like so..

data = na.omit(data)

Thanks all for pointer!

make sure you installed the package with all its dependencies:

install.packages('caret', dependencies = TRUE)

confusionMatrix( table(prediction, true_value) )

If your data contains NAs then sometimes it will be considered as a factor level,So omit these NAs initially

DF = na.omit(DF)

Then,if your model fit is predicting some incorrect level,then it is better to use tables

confusionMatrix(table(Arg1, Arg2))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!