错误:`data`和`reference`应该是具有相同级别的因子。使用confusionMatrix(插入符号)

问题描述 投票:2回答:1

使用confusionMatrix()包中的caret函数时出错。为了重现这个例子,我使用了Sonar包中的mlbench数据集。

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()时遇到的错误是

错误:datareference应该是具有相同级别的因子

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

知道发生了什么事吗?

r r-caret confusion-matrix
1个回答
2
投票

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

confusionMatrix(factor(p_class), experimental[["Class"]])
# Confusion Matrix and Statistics
# 
#           Reference
# Prediction  M  R
#          M 17 20
#          R 33 13
# ...
© www.soinside.com 2019 - 2024. All rights reserved.