[英]confusionMatrix for logistic regression in R
我想使用訓練數據和測試數據為邏輯回歸計算兩個混淆矩陣:
logitMod <- glm(LoanStatus_B ~ ., data=train, family=binomial(link="logit"))
我將預測概率的閾值設置為0.5:
confusionMatrix(table(predict(logitMod, type="response") >= 0.5,
train$LoanStatus_B == 1))
下面的代碼非常適合我的訓練集。 但是,當我使用測試集時:
confusionMatrix(table(predict(logitMod, type="response") >= 0.5,
test$LoanStatus_B == 1))
它給了我一個錯誤
Error in table(predict(logitMod, type = "response") >= 0.5, test$LoanStatus_B == : all arguments must have the same length
為什么是這樣? 我怎樣才能解決這個問題? 謝謝!
我認為使用預測有問題,因為您忘記提供新數據了。 另外,您可以使用caret
包中的函數confusionMatrix
來計算和顯示混淆矩陣,但是您無需在調用之前列出結果。
在這里,我創建了一個包含代表性二進制目標變量的玩具數據集,然后訓練了與您的模型類似的模型。
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"))
現在,您可以預測數據(例如,您的訓練集),然后使用confusionMatrix()
兩個參數的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)
這是結果
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.