当所有 类 都没有用 R 中的插入符包预测时的混淆矩阵

Confusion matrix when all classes are not predicted with caret package in R

我有一个分类模型 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

How can I obtain a confusion matrix when some factor levels in prediction: How can I add 0 automatically for predicted_class for missing 类 (在本例中为 4、7 和 9)

通过 union

加入因数使水平相同
all_class <- union(predicted_class, test.y)
newtable <- table(factor(predicted_class, all_class), factor(test.y, all_class))
caret::confusionMatrix(newtable)