【问题标题】:Logistic Regression confusion matrix Error: `data` and `reference` should be factors with the same levels逻辑回归混淆矩阵错误:`data`和`reference`应该是具有相同水平的因素
【发布时间】:2018-10-06 10:53:56
【问题描述】:

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

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 应该是具有相同水平的因素。”

我的数据集有三列 - 口粮、时间和标签(标签是男性和女性)

【问题讨论】:

  • 如果您使用的是 Roman 猜测的 library(caret),请添加 r-caret 标签。

标签: r logistic-regression confusion-matrix


【解决方案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

【讨论】:

  • @Shree 你能描述得更详细些吗?什么不起作用?请修改您的原始问题。
【解决方案2】:
confusionMatrix(data = as.factor(as.numeric(pdata>0.5)), reference = train$label)

这应该可行。

【讨论】:

    猜你喜欢
    • 2020-08-17
    • 2023-03-21
    • 2021-03-18
    • 2020-09-17
    • 2019-11-21
    • 2021-05-28
    • 2023-04-05
    • 2020-04-29
    • 2019-05-26
    相关资源
    最近更新 更多