2015-10-05 57 views
0

我已經構建了邏輯迴歸,現在我想計算從0到1範圍內的各種截斷值的預測精度。這是我一直使用的for循環。但我正在逐漸下標越界誤差,同時計算不同截斷點的準確性

標出界

這裏predtrain包含300個預測的輸出概率的每個範圍從0到1。每個值與截止eff的。最後,必須生成表格/混淆矩陣,將原始值(訓練$ CAN)與f1進行比較。有些事情是這樣的:

tab 
# pred2 
#  0 1 
# 0 1 93 
# 1 0 206 

代碼我寫的是:

predtrain <- predict(logreg1, newdata = train, type = 'response') 
eff<-seq(0,1,by = 0.05) 
for (i in 1:length(eff) {   
    f1 <- ifelse(predtrain > eff[i], 1, 0) 
    t1 <- table(train$CAN, f1) 
    effy <- (t1[1,1]+t1[2,2])/(t1[1,1]+t1[1,2]+t1[2,2]+t1[2,1]) 
    eff[[i]] <-effy 
} 
+0

請不要在不需要時發佈截圖。 – 2015-10-05 02:52:27

回答

2

你要標出來界失誤的原因是,你想創建一個像截止混淆矩陣0和1 - 這將創建一個單列的混淆矩陣(所有預測都是正數或負數),導致像t1[2,2]這樣的代碼導致您的錯誤。

在現實中,你正在試圖做的一切是計算在不同的臨界值的預測精度,從而可以在不創建表在所有喜歡的東西來完成:

cutoffs <- seq(0, 1, by=0.05) 
eff <- sapply(cutoffs, function(cutoff) { 
    sum((predtrain > cutoff) == train$CAN)/length(predtrain) 
}) 

要看到這個動作,讓我們考慮一個小例子模型:

eff <- sapply(cutoffs, function(cutoff) { 
    sum((predtrain > cutoff) == train$CAN)/length(predtrain) 
}) 
plot(cutoffs, eff) 

set.seed(144) 
x <- runif(100) 
train <- data.frame(x, CAN=as.numeric(runif(100)+x >= 1)) 
logreg1 <- glm(CAN~x, data=train, family="binomial") 
predtrain <- predict(logreg1, newdata = train, type = 'response') 

現在,我們可以在每個截止得到預測準確性10

enter image description here

您可以交替使用像ROCR軟件包這樣的軟件包來獲取指標。舉例來說,這裏是你如何可以在每個截止搶靈敏度:

library(ROCR) 
pred <- prediction(predtrain, train$CAN) 
perf <- performance(pred, "sens") 
eff <- sapply(cutoffs, function(cutoff) max([email protected][[1]][[email protected][[1]] >= cutoff])) 
plot(cutoffs, eff) 

enter image description here

+0

非常感謝。我試圖生成新的數據幀f1,然後比較它知道循環效率不高。 –

+0

但是要計算特異性和敏感性這樣的東西不會變得更加困難?我已經寫了兩個for循環,我知道這不是很有效,但我得到了可以計算性能變量的表格。這個代碼可以改進嗎? –

+0

@SairamReddy我已經更新了代碼,演示瞭如何使用ROCR,它可以在一系列截止點上獲取任意數量的不同結果。通過將'「sens」'切換到其他度量(您可以將其讀作「performance」),您將能夠獲取其他結果度量標準。 – josliber

0

但計算類似特異性和敏感性不就變得更加困難?我已經寫了兩個for循環,我知道這不是很有效,但我得到了可以計算性能變量的表格。這個方法可以改進嗎?

enter code here 
    z <- seq(0,1,by = 0.05) 
    t1 <- vector(mode = "list", length = length(z)) 
for(i in 1:length(z)) { 
      predtrain <- predict(logreg1, newdata = train, type = 'response') 

       for(j in 1:length(predtrain)){ 
        predtrain[j] <- ifelse(predtrain[j]>z[i], 1, 0) 
       } 
     t1[[i]] <- table(train$CAN, predtrain) 
     } t1