Error: `data` and `reference` should be factors with the same levels. Using confusionMatrix (caret)

Error: `data` and `reference` should be factors with the same levels. Using confusionMatrix (caret)

我在使用 caret 包中的 confusionMatrix() 函数时遇到错误。为了重现该示例,我使用了 mlbench 包中的 Sonar 数据集。

library(mlbench)
data(Sonar)

rows <- sample(nrow(Sonar))
Sonar <- Sonar[rows, ]


split <- round(nrow(Sonar) * 0.6)
adiestramiento <- Sonar[1:split, ]
experimental <- Sonar[(split + 1):nrow(Sonar), ]

model <- glm(Class ~ ., family = binomial(link = "logit"), adiestramiento)
p <- predict(model, experimental, type = "response")
p_class <- ifelse(p > 0.5, "M", "R")

library(caret)
confusionMatrix(p_class, experimental[["Class"]])

我在 运行 confusionMatrix() 时遇到的错误是

Error: data and reference should be factors with the same levels`

我检查了 p_classexperimental[["Class"]] 都有相同数量的对象 (83)。

知道发生了什么事吗?

问题是 data 或者,在这种情况下,p_class 必须是一个因素。所以,我们应该使用

confusionMatrix(factor(p_class), experimental[["Class"]])
# Confusion Matrix and Statistics
# 
#           Reference
# Prediction  M  R
#          M 17 20
#          R 33 13
# ...