2017-09-03 249 views
0

我想用我的訓練數據來計算兩個混淆矩陣用於我的邏輯迴歸邏輯迴歸和我的測試數據:混淆矩陣爲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 

爲什麼這是一個錯誤?我怎樣才能解決這個問題?謝謝!

+0

您需要將測試數據集傳遞給預測功能,否則將對列車數據集進行預測。即預測(logitMod,newdata = test,type =「response」) – user20650

+0

Thx它的工作原理! –

回答

1

我認爲使用預測存在問題,因爲您忘記提供新的數據。另外,您可以使用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()有兩個參數:

  • 你的預測
  • 所觀察到的類

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   
+1

這條線是做data = as.numeric(pdata> 0.5) –

+1

你的目標變量是0或1,但預測返回範圍從0到1的值。因此,您需要將其轉換爲二進制(離散化)。例如,您測試一個值是大於還是小於0.5。然後使用as.numer –

+0

將TRUE轉換爲1(並將FALSE轉換爲0)所以它是閾值,對嗎?我可以將其更改爲任何0-1的數字我想要 –