首页 > 解决方案 > 逻辑回归混淆矩阵问题

问题描述

我尝试为我的,但我不断得到:

错误:datareference应该是具有相同水平的因素。

下面是我的模型:

model3 <- glm(winner ~ srs.1 + srs.2, data = train_set, family = binomial)
confusionMatrix(table(predict(model3, newdata=test_set, type="response")) >= 0.5,
                      train_set$winner == 1)

winner变量包含team1team2
srs.1srs.2是数值。

我的问题是什么?

标签: rlogistic-regressionconfusion-matrix

解决方案


我想你的winner标签是0,1的二进制。所以让我们使用下面的例子:

library(caret)
set.seed(111)
data = data.frame(
srs.1 = rnorm(200),
srs.2 = rnorm(200)
)

data$winner = ifelse(data$srs.1*data$srs.2 > 0,1,0)

idx = sample(nrow(data),150)
train_set = data[idx,]
test_set = data[-idx,]

model3 <- glm(winner ~ srs.1 + srs.2, data = train_set, family = binomial)

就像您所做的那样,我们尝试预测,如果 > 0.5,它将为 1,否则为 0。您得到的 table() 是正确的。请注意,您需要同时为 test_set 或 train_set 执行此操作:

pred = as.numeric(predict(model3, newdata=test_set, type="response")>0.5)
ref = test_set$winner

confusionMatrix(table(pred,ref))

Confusion Matrix and Statistics

    ref
pred  0  1
   0 12  5
   1 19 14

               Accuracy : 0.52            
                 95% CI : (0.3742, 0.6634)
    No Information Rate : 0.62            
    P-Value [Acc > NIR] : 0.943973        

                  Kappa : 0.1085  

推荐阅读