Logistic回归混淆矩阵错误:`data`和`reference`应该是具有相同级别的因子

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

我已经尝试了堆栈溢出中所有可能的解决方案,建议数据和参考应该是具有相同级别的因素。

set.seed(10)
indices = sample.split(consumers$label, SplitRatio = 0.75)

train = consumers[indices,]
test = consumers[!(indices),]

##Build a logistic regression model

is.factor(train$label)
contrasts(train$label)

lr_model <- data.frame(label = as.numeric(rnorm(100)>0.5), b= rnorm(100), c = rnorm(100), d = rnorm(100))
logitMod <- glm(label ~ ., data=train, family=binomial(link="logit"))
pdata <- predict(logitMod, newdata = train, type = "response")
confusionMatrix(data = as.numeric(pdata>0.5), reference = train$label)

我仍然得到“错误:datareference应该是具有相同级别的因素。”

我的数据集有三列 - 定量,时间和标签(标签是男性和女性)

r logistic-regression confusion-matrix
2个回答
1
投票

在这里采取预感,你正在使用caret::confusionMatrix,所以这里。你正在做的是你传递一个整数作为数据和因子作为参考。请注意,文档需要预测类或表的因子。

> library(caret)
> 
> ref <- factor(sample(0:1, size = 100, replace = TRUE))
> data1 <- sample(0:1, size = 100, replace = TRUE)
> data2 <- factor(sample(0:1, size = 100, replace = TRUE))

# this is your case
> confusionMatrix(data = data1, reference = ref)
Error: `data` and `reference` should be factors with the same levels.

# pass in a factor (try a table for giggles)
> confusionMatrix(data = data2, reference = ref)
Confusion Matrix and Statistics

          Reference
Prediction  0  1
         0 24 19
         1 33 24

               Accuracy : 0.48           
                 95% CI : (0.379, 0.5822)
    No Information Rate : 0.57           
    P-Value [Acc > NIR] : 0.97198        

                  Kappa : -0.02          
 Mcnemar's Test P-Value : 0.07142        

            Sensitivity : 0.4211         
            Specificity : 0.5581         
         Pos Pred Value : 0.5581         
         Neg Pred Value : 0.4211         
             Prevalence : 0.5700         
         Detection Rate : 0.2400         
   Detection Prevalence : 0.4300         
      Balanced Accuracy : 0.4896         

       'Positive' Class : 0

0
投票
confusionMatrix(data = as.factor(as.numeric(pdata>0.5)), reference = train$label)

这应该工作。

© www.soinside.com 2019 - 2024. All rights reserved.