[英]Error: `data` and `reference` should be factors with the same levels. Using confusionMatrix (caret)
I am getting an error when using the confusionMatrix()
function from the caret
package.使用
caret
包中的confusionMatrix()
函数时出现错误。 To reproduce the example, I use the Sonar
dataset from the mlbench
package.为了重现该示例,我使用了
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"]])
The error I am getting when running confusionMatrix()
is我在运行
confusionMatrix()
时遇到的错误是
Error:
data
andreference
should be factors with the same levels`错误:
data
和reference
应该是具有相同水平的因素`
I checked that both p_class
and experimental[["Class"]]
have the same number of objetcs (83).我检查了
p_class
和p_class
experimental[["Class"]]
具有相同数量的 objetcs (83)。
Any idea what's going on?知道发生了什么吗?
The issue is that data
or, in this case, p_class
has to be a factor.问题是
data
或在这种情况下p_class
必须是一个因素。 So, instead we should use所以,我们应该使用
confusionMatrix(factor(p_class), experimental[["Class"]])
# Confusion Matrix and Statistics
#
# Reference
# Prediction M R
# M 17 20
# R 33 13
# ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.