R語言之邏輯回歸


 

本文主要將邏輯回歸的實現,模型的檢驗等

參考博文http://blog.csdn.net/tiaaaaa/article/details/58116346;http://blog.csdn.net/ai_vivi/article/details/43836641

1.測試集和訓練集(3:7比例)數據來源:http://archive.ics.uci.edu/ml/datasets/statlog+(australian+credit+approval)

austra=read.table("australian.dat")
head(austra) #預覽前6行

N=length(austra$V15) #690行,15列
#ind=1,ind=2分別以0.7,0.3的概率出現
ind=sample(2,N,replace=TRUE,prob=c(0.7,0.3))

aus_train=austra[ind==1,]
aus_test=austra[ind==2,]

  

2. 邏輯回歸的實現及預測

pre=glm(V15~.,data=aus_train,family=binomial(link="logit"))
summary(pre)

real=aus_test$V15
predict_=predict.glm(pre,type="response",newdata=aus_test)
predict=ifelse(predict_>0.5,1,0)
aus_test$predict=predict
head(aus_test)
#write.csv(aus_test,"aus_test.csv")

  

3.模型檢驗

res=data.frame(real,predict)
n=nrow(aus_train)
#計算Cox-Snell擬合優度 R2=1-exp((pre$deviance-pre$null.deviance)/n) cat("Cox-Snell R2=",R2,"\n") #Cox-Snell R2= 0.5502854
#計算Nagelkerke擬合優度 R2=R2/(1-exp((-pre$null.deviance)/n)) cat("Nagelkerke R2=",R2,"\n") #Nagelkerke R2= 0.7379711 #模型其他指標 #residuals(pre) #殘差 #coefficients(pre) #系數 #anova(pre) #方差

  

4.准確率和精度

true_value=aus_test[,15]
predict_value=aus_test[,16]
#計算模型精度
error=predict_value-true_value
#判斷正確的數量占總數的比例  
accuracy=(nrow(aus_test)-sum(abs(error)))/nrow(aus_test)

#混淆矩陣中的量(混淆矩陣具體解釋見下頁)
#真實值預測值全為1 / 預測值全為1 --- 提取出的正確信息條數/提取出的信息條數  
precision=sum(true_value & predict_value)/sum(predict_value)
#真實值預測值全為1 / 真實值全為1 --- 提取出的正確信息條數 /樣本中的信息條數  
recall=sum(predict_value & true_value)/sum(true_value)

#P和R指標有時候會出現的矛盾的情況,這樣就需要綜合考慮他們,最常見的方法就是F-Measure(又稱為F-Score)
F_measure=2*precision*recall/(precision+recall)    #F-Measure是Precision和Recall加權調和平均,是一個綜合評價指標  

#輸出以上各結果  
print(accuracy)  
print(precision)  
print(recall)  
print(F_measure)  
#混淆矩陣,顯示結果依次為TP、FN、FP、TN  
table(true_value,predict_value) 

  

5. ROC曲線

#ROC曲線 (ROC曲線詳細解釋見下頁) 
# 方法1  
#install.packages("ROCR")    
library(ROCR)       
pred <- prediction(predict_,true_value)   #預測值(0.5二分類之前的預測值)和真實值     
performance(pred,'auc')@y.values        #AUC值  0.9191563
perf <- performance(pred,'tpr','fpr')  #y軸為tpr(true positive rate),x軸為fpr(false positive rate)
plot(perf)  
#方法2  
#install.packages("pROC")  
library(pROC)  
modelroc <- roc(true_value,predict.)  
plot(modelroc, print.auc=TRUE, auc.polygon=TRUE,legacy.axes=TRUE, grid=c(0.1, 0.2),  
     grid.col=c("green", "red"), max.auc.polygon=TRUE,  
     auc.polygon.col="skyblue", print.thres=TRUE)        #畫出ROC曲線,標出坐標,並標出AUC的值  
#方法3,按ROC定義  
TPR=rep(0,1000)  
FPR=rep(0,1000)  
p=predict.  
for(i in 1:1000)  
  {   
  p0=i/1000;  
  ypred<-1*(p>p0)    
  TPR[i]=sum(ypred*true_value)/sum(true_value)    
  FPR[i]=sum(ypred*(1-true_value))/sum(1-true_value)  
  }  
plot(FPR,TPR,type="l",col=2)  
points(c(0,1),c(0,1),type="l",lty=2)  

  

6. 更換測試集和訓練集的選取方式,采用十折交叉驗證

australian <- read.table("australian.dat")  
#將australian數據分成隨機十等分  
#install.packages("caret")  
#固定folds函數的分組  
set.seed(7)  
library(caret)  
folds <- createFolds(y=australian$V15,k=10)  
  
#構建for循環,得10次交叉驗證的測試集精確度、訓練集精確度  
  
max=0  
num=0  
  
for(i in 1:10){  
    
  fold_test <- australian[folds[[i]],]   #取folds[[i]]作為測試集  
  fold_train <- australian[-folds[[i]],]   # 剩下的數據作為訓練集  
    
  print("***組號***")  
    
  fold_pre <- glm(V15 ~.,family=binomial(link='logit'),data=fold_train)  
  fold_predict <- predict(fold_pre,type='response',newdata=fold_test)  
  fold_predict =ifelse(fold_predict>0.5,1,0)  
  fold_test$predict = fold_predict  
  fold_error = fold_test[,16]-fold_test[,15]  
  fold_accuracy = (nrow(fold_test)-sum(abs(fold_error)))/nrow(fold_test)   
  print(i)  
  print("***測試集精確度***")  
  print(fold_accuracy)  
  print("***訓練集精確度***")  
  fold_predict2 <- predict(fold_pre,type='response',newdata=fold_train)  
  fold_predict2 =ifelse(fold_predict2>0.5,1,0)  
  fold_train$predict = fold_predict2  
  fold_error2 = fold_train[,16]-fold_train[,15]  
  fold_accuracy2 = (nrow(fold_train)-sum(abs(fold_error2)))/nrow(fold_train)   
  print(fold_accuracy2)  
    
    
  if(fold_accuracy>max)  
    {  
    max=fold_accuracy    
    num=i  
    }  
    
}  
  
print(max)  
print(num)  
  
##結果可以看到,精確度accuracy最大的一次為max,取folds[[num]]作為測試集,其余作為訓練集。 

  

7.十折交叉驗證的准確度

#十折里測試集最大精確度的結果  
testi <- australian[folds[[num]],]  
traini <- australian[-folds[[num]],]   # 剩下的folds作為訓練集  
prei <- glm(V15 ~.,family=binomial(link='logit'),data=traini)  
predicti <- predict.glm(prei,type='response',newdata=testi)  
predicti =ifelse(predicti>0.5,1,0)  
testi$predict = predicti  
#write.csv(testi,"ausfold_test.csv")  
errori = testi[,16]-testi[,15]  
accuracyi = (nrow(testi)-sum(abs(errori)))/nrow(testi)   
  
#十折里訓練集的精確度  
predicti2 <- predict.glm(prei,type='response',newdata=traini)  
predicti2 =ifelse(predicti2>0.5,1,0)  
traini$predict = predicti2  
errori2 = traini[,16]-traini[,15]  
accuracyi2 = (nrow(traini)-sum(abs(errori2)))/nrow(traini)   
  
#測試集精確度、取第i組、訓練集精確  
accuracyi;num;accuracyi2  
#write.csv(traini,"ausfold_train.csv")  

  

混淆矩陣

    預測    
    1 0  
1 True Positive(TP) True Negative(TN) Actual Positive(TP+TN)
0 False Positive(FP) False Negative(FN) Actual Negative(FP+FN)
    Predicted Positive(TP+FP) Predicted Negative(TN+FN)      (TP+TN+FP+FN)

AccuracyRate(准確率): (TP+TN)/(TP+TN+FN+FP)

ErrorRate(誤分率): (FN+FP)/(TP+TN+FN+FP)

Recall(召回率,查全率,擊中概率): TP/(TP+FN), 在所有GroundTruth為正樣本中有多少被識別為正樣本了;

Precision(查准率):TP/(TP+FP),在所有識別成正樣本中有多少是真正的正樣本;

TPR(True Positive Rate): TP/(TP+FN),實際就是Recall

FAR(False Acceptance Rate)或FPR(False Positive Rate):FP/(FP+TN), 錯誤接收率,誤報率,在所有GroundTruth為負樣本中有多少被識別為正樣本了;

FRR(False Rejection Rate): FN/(TP+FN),錯誤拒絕率,拒真率,在所有GroundTruth為正樣本中有多少被識別為負樣本了,它等於1-Recall

 

ROC曲線(receiver operating characteristic curve)

 

 

  1. 橫軸是FPR,縱軸是TPR;

  2. 每個閾值的識別結果對應一個點(FPR,TPR),當閾值最大時,所有樣本都被識別成負樣本,對應於左下角的點(0,0),當閾值最小時,所有樣本都被識別成正樣本,對應於右上角的點(1,1),隨着閾值從最大變化到最小,TP和FP都逐漸增大;

  3. 一個好的分類模型應盡可能位於圖像的左上角,而一個隨機猜測模型應位於連接點(TPR=0,FPR=0)和(TPR=1,FPR=1)的主對角線上;

  4. 可以使用ROC曲線下方的面積AUC(AreaUnder roc Curve)值來度量算法好壞:如果模型是完美的,那么它的AUG = 1,如果模型是個簡單的隨機猜測模型,那么它的AUG = 0.5,如果一個模型好於另一個,則它的曲線下方面積相對較大;

  5. ERR(Equal Error Rate,相等錯誤率):FAR和FRR是同一個算法系統的兩個參數,把它放在同一個坐標中。FAR是隨閾值增大而減小的,FRR是隨閾值增大而增大的。因此它們一定有交點。這個點是在某個閾值下的FAR與FRR等值的點。習慣上用這一點的值來衡量算法的綜合性能。對於一個更優的指紋算法,希望在相同閾值情況下,FAR和FRR都越小越好。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM