R中逻辑回归的混淆矩阵

Pum*_*n C 1 validation r confusion-matrix logistic-regression

我想使用我的训练数据和测试数据为我的逻辑回归计算两个混淆矩阵:

logitMod <- glm(LoanStatus_B ~ ., data=train, family=binomial(link="logit"))
Run Code Online (Sandbox Code Playgroud)

我将预测概率的阈值设置为 0.5:

confusionMatrix(table(predict(logitMod, type="response") >= 0.5,
                      train$LoanStatus_B == 1))
Run Code Online (Sandbox Code Playgroud)

下面的代码适用于我的训练集。但是,当我使用测试集时:

confusionMatrix(table(predict(logitMod, type="response") >= 0.5,
                      test$LoanStatus_B == 1))
Run Code Online (Sandbox Code Playgroud)

它给了我一个错误

Error in table(predict(logitMod, type = "response") >= 0.5, test$LoanStatus_B == : all arguments must have the same length
Run Code Online (Sandbox Code Playgroud)

为什么是这样?我怎样才能解决这个问题?谢谢!

Dam*_*ini 7

我认为使用 predict 存在问题,因为您忘记提供新数据。此外,您还可以使用该功能confusionMatrixcaret包计算和显示混淆矩阵,但你不认为呼叫之前需要表格上。

在这里,我创建了一个包含代表性二进制目标变量的玩具数据集,然后我训练了一个与您所做的类似的模型。

train <- data.frame(LoanStatus_B = as.numeric(rnorm(100)>0.5), b= rnorm(100), c = rnorm(100), d = rnorm(100))
logitMod <- glm(LoanStatus_B ~ ., data=train, family=binomial(link="logit"))
Run Code Online (Sandbox Code Playgroud)

现在,您可以预测数据(例如,您的训练集),然后使用confusionMatrix()它接受两个参数:

  • 你的预测
  • 观察到的类

library(caret)
# Use your model to make predictions, in this example newdata = training set, but replace with your test set    
pdata <- predict(logitMod, newdata = train, type = "response")

# use caret and compute a confusion matrix
confusionMatrix(data = as.numeric(pdata>0.5), reference = train$LoanStatus_B)
Run Code Online (Sandbox Code Playgroud)

这是结果

Confusion Matrix and Statistics

          Reference
Prediction  0  1
         0 66 33
         1  0  1

               Accuracy : 0.67            
                 95% CI : (0.5688, 0.7608)
    No Information Rate : 0.66            
    P-Value [Acc > NIR] : 0.4625          
Run Code Online (Sandbox Code Playgroud)

  • 这条线在做什么 data = as.numeric(pdata&gt;0.5) (2认同)
  • 在这种情况下,“1”对应于您的数字 1。但是,正参数是作为字符提供的!如果您关心准确性,那没关系。但它对于计算灵敏度/特异性很重要,因为您需要知道哪些是真/假阳性。例如,尝试: `confusionMatrix(data = as.factor(c("A","B", "B", "B", "A", "A", "A", "A", "B ", "B")), reference = as.factor(c("A","A", "A", "B", "A", "A", "A", "A", "B ", "A")), positive = "A")` 与 `positive = "B"` 相同。我希望这是有用的。如果是这样,请验证我的答案。谢谢 (2认同)