通过阅读类似的问题,我知道问题在于yhat.logisticReg不是2级因子,而training.prepped$TARGET_FLAG是2级因子。我认为可以通过更改模型或在预测中解决此问题,从而将yhat.logisticReg设为2级。我怎样才能做到这一点?

logisticReg = glm(TARGET_FLAG ~ .,
                  data = training.prepped,
                  family = binomial())
yhat.logisticReg = predict(logisticReg, training.prepped, type = "response")
confusionMatrix(yhat.logisticReg, training.prepped$TARGET_FLAG)

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


str(training.prepped$TARGET_FLAG)
Factor w/ 2 levels "0","1": 1 1 1 1 1 2 1 2 2 1 ...

str(yhat.logisticReg)
 Named num [1:8161] 0.1656 0.2792 0.3717 0.0894 0.272 ...
 - attr(*, "names")= chr [1:8161] "1" "2" "3" "4" ...

最佳答案

您可能需要先选择一个阈值,然后将实值数据转换为二进制值,例如

a <- c(0.2, 0.7, 0.4)
threshold <- 0.5
binary_a <- factor(as.numeric(a>threshold))

str(binary_a)
Factor w/ 2 levels "0","1": 1 2 1

08-24 14:10