我有一个分类模型predict(model, test.x)
来评估一个有11个类的数据的模型,预测的结果:
table(predicted_class)
0 1 2 3 5 6 8 10
7 6 232 11 74 58 1 1
我的测试标签(真相)是:
table(test.y)
0 1 2 3 4 5 6 7 8 9 10
105 16 78 25 14 74 12 9 23 15 19
当我想用caret包获得混淆矩阵时,我有这个错误消息,因为我的模型没有预测类7和9:
caret::confusionMatrix(test.y, predicted_class, mode = "everything")
Error in confusionMatrix.default(test.y, predicted_class, :
the data cannot have more levels than the reference
当预测中缺少某个因子级别时,如何获得混淆矩阵:如何为缺少的类(在本例中为4,7和9)自动为predict_class添加0
通过使用union
连接因子来使水平相同
all_class <- union(predicted_class, test.y)
newtable <- table(factor(predicted_class, all_class), factor(test.y, all_class))
caret::confusionMatrix(newtable)