{"word_count": 2177, "character_count": 18533}
A natural technique to select variables in the context of generalized linear models is to use a stepŵise procedure. It is natural, but contreversial, as discussed by Frank Harrell  in a great post, clearly worth reading. Frank mentioned about 10 points against a stepwise procedure.It yields R-squared values that are badly biased to be high.The F and chi-squared tests quoted next to each variable on the printout do not have the claimed distribution.The method yields confidence intervals for effects and predicted values that are falsely narrow (see Altman and Andersen (1989)).It yields p-values that do not have the proper meaning, and the proper correction for them is a difficult problem.It gives biased regression coefficients that need shrinkage (the coefficients for remaining variables are too large (see Tibshirani (1996)).It has severe problems in the presence of collinearity.It is based on methods (e.g., F tests for nested models) that were intended to be used to test prespecified hypotheses.Increasing the sample size does not help very much (see Derksen and Keselman (1992)).It allows us to not think about the problem.It uses a lot of paper.In order to illustrate that issue of variable selection, consider a dataset I've been using many times on the blog,MYOCARDE=read.table("http://freakonometrics.free.fr/saporta.csv",head=TRUE,sep=";")where we have observations from people entering E.R., because of a (potential) infarctus, and we want to understand who did survive, and to build a predictive model.What if we use a forward stepwise logistic regression here? I want to use a forward construction since it usually yields to models with less explanatory variables. We can use Akaike Information Criterion&#62; reg0=glm(PRONO~1,data=MYOCARDE,family=binomial)&#62; reg1=glm(PRONO~.,data=MYOCARDE,family=binomial)&#62; step(reg0,scope=formula(reg1),+ direction="forward",k=2)                  # AICStart:  AIC=98.03PRONO ~ 1         Df Deviance    AIC+ REPUL  1   46.884 50.884+ INSYS  1   51.865 55.865+ INCAR  1   53.313 57.313+ PRDIA  1   78.503 82.503+ PAPUL  1   82.862 86.862+ PVENT  1   87.093 91.093&#60;none&#62;       96.033 98.033+ FRCAR  1   94.861 98.861 Step:  AIC=50.88PRONO ~ REPUL         Df Deviance    AIC+ INCAR  1   44.530 50.530+ PVENT  1   44.703 50.703+ INSYS  1   44.857 50.857&#60;none&#62;       46.884 50.884+ PAPUL  1   45.274 51.274+ PRDIA  1   46.322 52.322+ FRCAR  1   46.540 52.540 Step:  AIC=50.53PRONO ~ REPUL + INCAR         Df Deviance    AIC&#60;none&#62;       44.530 50.530+ PVENT  1   43.134 51.134+ PRDIA  1   43.772 51.772+ INSYS  1   44.305 52.305+ PAPUL  1   44.341 52.341+ FRCAR  1   44.521 52.521 Call:  glm(formula = PRONO ~ REPUL + INCAR, family = binomial, data = MYOCARDE) Coefficients:(Intercept)        REPUL     1.633668    -0.003564        INCAR     1.618479   Degrees of Freedom: 70 Total (i.e. Null);  68 ResidualNull Deviance:    96.03 Residual Deviance: 44.53 AIC: 50.53or Schwarz Bayesian Information Criterion,&#62; step(reg0,scope=formula(reg1),+ direction="forward",k=log(n))           # BICStart:  AIC=98.11PRONO ~ 1         Df Deviance    AIC+ REPUL  1   46.884 51.043+ INSYS  1   51.865 56.024+ INCAR  1   53.313 57.472+ PRDIA  1   78.503 82.662+ PAPUL  1   82.862 87.021+ PVENT  1   87.093 91.252&#60;none&#62;       96.033 98.113+ FRCAR  1   94.861 99.020 Step:  AIC=51.04PRONO ~ REPUL         Df Deviance    AIC+ INCAR  1   44.530 50.768+ PVENT  1   44.703 50.942&#60;none&#62;       46.884 51.043+ INSYS  1   44.857 51.095+ PAPUL  1   45.274 51.512+ PRDIA  1   46.322 52.561+ FRCAR  1   46.540 52.778 Step:  AIC=50.77PRONO ~ REPUL + INCAR         Df Deviance    AIC&#60;none&#62;       44.530 50.768+ PVENT  1   43.134 51.452+ PRDIA  1   43.772 52.089+ INSYS  1   44.305 52.623+ PAPUL  1   44.341 52.659+ FRCAR  1   44.521 52.838 Call:  glm(formula = PRONO ~ REPUL + INCAR, family = binomial, data = MYOCARDE) Coefficients:(Intercept)        REPUL     1.633668    -0.003564        INCAR     1.618479   Degrees of Freedom: 70 Total (i.e. Null);  68 ResidualNull Deviance:    96.03 Residual Deviance: 44.53 AIC: 50.53With those two approaches, we have the same story: the most important variable (or say with the highest predictive value) is REPUL. And we can improve the model by adding INCAR. And that's it. We can get a good model with those two covariates.Now, what about using cross-validation here? We should keep in ming that AIC is asymptotically equivalent to One-Leave-Out Cross Validation (see Stone (1977)),  while BIC is equivalent to -fold Cross Validation (see Shao (1997)), whereUsing Leave-One-Out Cross ValidationIn order to select the first variable, consider 7 logistic regression, each on a single different variable. Each time, we estimate the model on  observations and get a prediction on the remaining one,on. Set . The function to get those values is&#62; name_var=names(MYOCARDE)&#62; pred_i=function(i,k){+ fml = paste(name_var[8],"~",name_var[k],sep="")+ reg=glm(fml,data=MYOCARDE[-i,],family=binomial)+ predict(reg,newdata=MYOCARDE[i,],+ type="response")+ }then for each variable , we get the ROC curve using and,&#62; library(AUC)&#62; ROC=function(k){+  Y=MYOCARDE[,8]=="Survival"+  S=Vectorize(function(i) pred_i(i,k))+ (1:length(Y))+  R=roc(S,as.factor(Y))+  return(list(roc=cbind(R$fpr,R$tpr),+              auc=AUC::auc(R)))+ }Here, for each variable, we compute the area under the curve (AUC criterion)&#62; AUC=rep(NA,7)&#62; for(k in 1:7){+   AUC[k]=ROC(k)$auc+   cat("Variable ",k,"(",name_var[k],") :",+   AUC[k],"\n") }Variable  1 ( FRCAR ) : 0.4934319 Variable  2 ( INCAR ) : 0.8965517 Variable  3 ( INSYS ) : 0.909688 Variable  4 ( PRDIA ) : 0.7487685 Variable  5 ( PAPUL ) : 0.7134647 Variable  6 ( PVENT ) : 0.6584565 Variable  7 ( REPUL ) : 0.9154351But we can also visualize those curves,&#62; plot(0:1,0:1,col="white",xlab="",ylab="")&#62; for(k in 1:7) + lines(ROC(k)$roc,type="s",col=CL[k])&#62; legend(.8,.45,name_var,col=CL,lty=1,cex=.8)(there is no PRONO here, there is a typo  in the Legend)where here colors were obtained using&#62; library(RColorBrewer)&#62; CL=brewer.pal(8, "Set1")[-7]Here ROC curves were obtained using a Leave-one-Out strategy. And the best variable (if we should keep one, and one only) is&#62; k0=which.max(AUC)&#62; name_var[k0][1] "REPUL"Now, consider a stepwise procedure: we keep that 'best' variable in our model, and we try to add another one.&#62; pred_i=function(i,k){+ vk=c(k0,k)+ fml = paste(name_var[8],"~",paste(name_var[vk],+ collapse="+"),sep="")+ reg=glm(fml,data=MYOCARDE[-i,],family=binomial)+ predict(reg,newdata=MYOCARDE[i,],+ type="response")+ }&#62; library(AUC)&#62; ROC=function(k){+ Y=MYOCARDE[,8]=="Survival"+ S=Vectorize(function(i) pred_i(i,k))+ (1:length(Y))+ R=roc(S,as.factor(Y))+ return(list(roc=cbind(R$fpr,R$tpr),+ auc=AUC::auc(R)))+ }&#62; plot(0:1,0:1,col="white",xlab="",ylab="")&#62; for(k in (1:7)[-k0]) lines(ROC(k)$roc,type="s",col=CL[k])&#62; segments(0,0,1,1,lty=2,col="grey")&#62; legend(.8,.45,+   name_var[-k0],+   col=CL[-k0],lty=1,cex=.8)We were already quite good. And we might expect to find another variable that will increase the predictive power of our classifier.&#62; AUC=rep(NA,7)&#62; for(k in (1:7)[-k0]){+  AUC[k]=ROC(k)$auc+  cat("Variable ",k,"(",name_var[k],") :",+  AUC[k],"\n")+ }Variable  1 ( FRCAR ) : 0.9064039 Variable  2 ( INCAR ) : 0.9195402 Variable  3 ( INSYS ) : 0.9187192 Variable  4 ( PRDIA ) : 0.9137931 Variable  5 ( PAPUL ) : 0.9187192 Variable  6 ( PVENT ) : 0.9137931And, of course, we can move foreward, add another variable, etc,&#62; k0=c(k0,which.max(AUC))&#62; pred_i=function(i,k){+   vk=c(k0,k)+   fml = paste(name_var[8],"~",paste(+ name_var[vk],collapse="+"),sep="")+ reg=glm(fml,data=MYOCARDE[-i,],family=binomial)+ predict(reg,newdata=MYOCARDE[i,],+ type="response")+ }&#62; library(AUC)&#62; ROC=function(k){+  Y=MYOCARDE[,8]=="Survival"+  S=Vectorize(function(i) pred_i(i,k))+  (1:length(Y))+  R=roc(S,as.factor(Y))+  return(list(roc=cbind(R$fpr,R$tpr),+  auc=AUC::auc(R)))+ }&#62; &#62; plot(0:1,0:1,col="white",xlab="",ylab="")&#62; for(k in (1:7)[-k0]) lines(ROC(k)$roc,type="s",col=CL[k])&#62; segments(0,0,1,1,lty=2,col="grey")&#62; legend(.8,.45,name_var[-k0],+ col=CL[-k0],lty=1,cex=.8)But here, the gain is rather small (if any)&#62; AUC=rep(NA,7)&#62; for(k in (1:7)[-k0]){+ AUC[k]=ROC(k)$auc+ cat("Variable ",k,"(",name_var[k],") :",+ AUC[k],"\n")+ }Variable  1 ( FRCAR ) : 0.9121511 Variable  3 ( INSYS ) : 0.9170772 Variable  4 ( PRDIA ) : 0.910509 Variable  5 ( PAPUL ) : 0.907225 Variable  6 ( PVENT ) : 0.909688With that stepwise algorithm, the best strategy is to keep, first, REPUL, and then to add INCAR. Which is consistent with the stepwise procedure using Akaike Information Criterion.An alternative could be to select the best pair among all possible pairs. It will be time consuming, but it can be used to avoid the stepwise drawback.&#62; pred_i=function(i,k){+ fml = paste(name_var[8],"~",paste(name_var[+ as.integer(k)],collapse="+"),sep="")+ reg=glm(fml,data=MYOCARDE[-i,],family=binomial)+ predict(reg,newdata=MYOCARDE[i,],+ type="response")+ }&#62; library(AUC)&#62; ROC=function(k){+   Y=MYOCARDE[,8]=="Survival"+   L=list()+   n=length(Y)+   nk=trunc(n/trunc(n/10))+   for(i in 1:(nk-1)) L[[i]]=((i-1)*+     trunc(n/10)+1:(n/10)) +   L[[nk]]=((nk-1)*trunc(n/10)+1):n+   S=unlist(Vectorize(function(i) +     pred_i(L[[i]],k))(1:nk))+   R=roc(S,as.factor(Y))+   return(AUC::auc(R))+ }&#62; v=data.frame(k1=rep(1:7,each=7),k2=rep(1:7,7))&#62; v=v[v$k1&#60;v$k2,]&#62; v$auc=NA&#62; for(i in 1:nrow(v)) v$auc[i]=ROC(v[i,1:2])&#62; v   k1 k2       auc2   1  2 0.90476193   1  3 0.90476194   1  4 0.69909695   1  5 0.63957316   1  6 0.63341547   1  7 0.881773410  2  3 0.907225011  2  4 0.908867012  2  5 0.894088713  2  6 0.880131414  2  7 0.889983618  3  4 0.891625619  3  5 0.881773420  3  6 0.901477821  3  7 0.876847326  4  5 0.692528727  4  6 0.713875228  4  7 0.882594434  5  6 0.691297235  5  7 0.883415442  6  7 0.8834154Here the best pair is&#62; v[which.max(v$auc),]   k1 k2      auc11  2  4 0.908867&#62; name_var[as.integer(v[which.max(v$auc),1:2])][1] "INCAR" "PRDIA"which is different, compared with the one we got above. What is odd here is that we get a smaller AUC than the ones we got at step 2 in the stepwise procedure.Nevertheless, even with a few observations (our dataset is rather small here), it is time consuming to look at all ROC curves, for all pairs. An alternative might be to use -Fold Cross Validation.Using -Fold Cross ValidationHere we consider a partition of indices, , and we definebased on observations. For all, set . Then, we can use the stepwise method described above&#62; pred_i=function(i,k){+ fml = paste(name_var[8],"~",name_var[k],sep="")+ reg=glm(fml,data=MYOCARDE[-i,],family=binomial)+ predict(reg,newdata=MYOCARDE[i,],+ type="response")+ }&#62; library(AUC)&#62; ROC=function(k){+   Y=MYOCARDE[,8]=="Survival"+   L=list()+   n=length(Y)+   nk=trunc(n/trunc(n/10))+   for(i in 1:(nk-1)) L[[i]]=((i-1)*+     trunc(n/10)+1:(n/10)) +   L[[nk]]=((nk-1)*trunc(n/10)+1):n+   S=unlist(Vectorize(function(i) +     pred_i(L[[i]],k))(1:nk))+   R=roc(S,as.factor(Y))+   return(list(roc=cbind(R$fpr,R$tpr),+               auc=AUC::auc(R)))+ }&#62; plot(0:1,0:1,col="white",xlab="",ylab="")&#62; for(k in (1:7)) lines(ROC(k)$roc,col=CL[k])&#62; segments(0,0,1,1,lty=2,col="grey")&#62; legend(.8,.45,name_var,col=CL,lty=1,cex=.8)with&#62; AUC=rep(NA,7)&#62; for(k in 1:7){+ AUC[k]=ROC(k)$auc+ cat("Variable ",k,"(",name_var[k],") :",+ AUC[k],"\n")+ }Variable  1 ( FRCAR ) : 0.3932677 Variable  2 ( INCAR ) : 0.8940887 Variable  3 ( INSYS ) : 0.908046 Variable  4 ( PRDIA ) : 0.7278325 Variable  5 ( PAPUL ) : 0.6756979 Variable  6 ( PVENT ) : 0.63711 Variable  7 ( REPUL ) : 0.8834154So, this time, INSYS is probably the best covariate to use. Now, if we keep that variable, and move forward,&#62; k0=which.max(AUC)&#62; pred_i=function(i,k){+  vk=c(k0,k)+ fml = paste(name_var[8],"~",paste(name_var[vk],+ collapse="+"),sep="")+ reg=glm(fml,data=MYOCARDE[-i,],family=binomial)+ predict(reg,newdata=MYOCARDE[i,],+ type="response")+ }&#62; library(AUC)&#62; ROC=function(k){+   Y=MYOCARDE[,8]=="Survival"+   L=list()+   n=length(Y)+   nk=trunc(n/trunc(n/10))+   for(i in 1:(nk-1)) L[[i]]=((i-1)*+     trunc(n/10)+1:(n/10)) +   L[[nk]]=((nk-1)*trunc(n/10)+1):n+   S=unlist(Vectorize(function(i) +      pred_i(L[[i]],k))(1:nk))+   R=roc(S,as.factor(Y))+   return(list(roc=cbind(R$fpr,R$tpr),+               auc=AUC::auc(R)))+ }&#62; plot(0:1,0:1,col="white",xlab="",ylab="")&#62; for(k in (1:7)[-k0]) + lines(ROC(k)$roc,col=CL[k])&#62; segments(0,0,1,1,lty=2,col="grey")&#62; legend(.8,.45,name_var[-k0],+        col=CL[-k0],lty=1,cex=.8)and our best choice for the second variable would be INCAR&#62; AUC=rep(NA,7)&#62; for(k in (1:7)[-k0]){+   AUC[k]=ROC(k)$auc+   cat("Variable ",k,"(",name_var[k],") :",+ AUC[k],"\n")+ }Variable  1 ( FRCAR ) : 0.9047619 Variable  2 ( INCAR ) : 0.907225 Variable  4 ( PRDIA ) : 0.8916256 Variable  5 ( PAPUL ) : 0.8817734 Variable  6 ( PVENT ) : 0.9014778 Variable  7 ( REPUL ) : 0.8768473 &#62; which.max(AUC)[1] 2Here again, it is possible to look at all pairs&#62; pred_i=function(i,k){+ fml = paste(name_var[8],"~",paste(name_var[+ as.integer(k)],collapse="+"),sep="")+ reg=glm(fml,data=MYOCARDE[-i,],family=binomial)+ predict(reg,newdata=MYOCARDE[i,],+ type="response")+ }&#62; library(AUC)&#62; ROC=function(k){+   Y=MYOCARDE[,8]=="Survival"+   L=list()+   n=length(Y)+   nk=trunc(n/trunc(n/10))+   for(i in 1:(nk-1)) L[[i]]=((i-1)*+   trunc(n/10)+1:(n/10)) +   L[[nk]]=((nk-1)*trunc(n/10)+1):n+   S=unlist(Vectorize(function(i) +     pred_i(L[[i]],k))(1:nk))+   R=roc(S,as.factor(Y))+   return(AUC::auc(R))+ }&#62; v=data.frame(k1=rep(1:7,each=7),k2=rep(1:7,7))&#62; v=v[v$k1&#60;v$k2,]&#62; v$auc=NA&#62; for(i in 1:nrow(v)) v$auc[i]=ROC(v[i,1:2])&#62; v[which.max(v$auc),]   k1 k2      auc11  2  4 0.908867&#62; name_var[as.integer(v[which.max(v$auc),1:2])][1] "INCAR" "PRDIA"which is the same as what we got using an One-Leave-Out strategy: we have again the same two covariates. And again, the AUC is lower than the one we got using a stepwise procedure (I still don't understand how this is possible).   An alternative for the code would be to store all the regression models in a list,&#62; L=list()&#62; n=nrow(MYOCARDE)&#62; nk=trunc(n/trunc(n/10))&#62; for(i in 1:(nk-1)) L[[i]]=((i-1)*trunc(n/10)++  1:(n/10)) &#62; L[[nk]]=((nk-1)*trunc(n/10)+1):n&#62; REG=list()&#62; for(k in 1:7){+   REG[[k]]=list()+   fml = paste(name_var[8],"~",+ paste(name_var[as.integer(k)],collapse="+"),+ sep="")+ for(i in 1:nk) REG[[k]][[i]]=reg=glm(fml,+  data=MYOCARDE[-L[[i]],],family=binomial)+ }and then to call them, properly&#62; pred_i=function(i,k){+  I=which(sapply(1:10,function(j) i%in%L[[j]]))+  predict(REG[[k]][[I]],newdata=MYOCARDE[i,],+  type="response")+ }One has to check about the efficiency, especially with a large dataset.Using Trees and Random ForestsAnother quick, but popular (from what I've seen), technique is to use trees. Important variables should appear in the output,&#62; library(rpart)&#62; tree=rpart(PRONO~.,data=MYOCARDE)&#62; library(rpart.plot)&#62; rpart.plot(tree)Here, the first variable that appears in the tree construction is INSYS, and the second on is REPUL. Which is rather different with what we got above. But using one tree is maybe not sufficient. One can use the variable importance function (described in a previous post) obtained using random forests.&#62; library(randomForest)&#62; rf=randomForest(PRONO~.,data=MYOCARDE,+                 importance=TRUE)&#62; rf$importance[,4]   FRCAR    INCAR    INSYS 1.042006 7.363255 8.954898    PRDIA    PAPUL    PVENT 3.149235 2.571267 3.152619    REPUL 7.510110Here, we have the same story as the one we got with a simple tree: the 'most important' variable is INSYS while the second one is REPUL. But here, we consider tree based predictors. And not a logistic regression.Using Dedicated R functionsIt is possible to use some dedicated R functions for variable selection. For instance, since we consider a logistic regression, use&#62; library(bestglm)&#62; Xy=as.data.frame(MYOCARDE)&#62; Xy[,8]=(Xy[,8]=="Death")*1             &#62; names(Xy)=names(MYOCARDE)&#62; B=bestglm(Xy)&#62; B$Subsets[,2:8]   FRCAR INCAR INSYS PRDIA PAPUL PVENT REPUL0  FALSE FALSE FALSE FALSE FALSE FALSE FALSE1  FALSE FALSE FALSE FALSE FALSE FALSE  TRUE2* FALSE  TRUE FALSE FALSE FALSE FALSE  TRUE3  FALSE  TRUE FALSE FALSE FALSE  TRUE  TRUE4   TRUE  TRUE FALSE FALSE FALSE  TRUE  TRUE5   TRUE  TRUE  TRUE FALSE FALSE  TRUE  TRUE6   TRUE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE7   TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUEWith only one variable, we should consider REPUL (row 1 of the matrix), while with two variables, we should consider REPUL and INCAR (and that is the best model, based on some Bayesian Information Criterion). Here, cross validation techniques can be used also,&#62; B=bestglm(Xy, IC = "CV", CVArgs = + list(Method = "HTF", K = 10, REP = 1))&#62;  cverrs = B$Subsets[, "CV"]&#62;  sdCV = B$Subsets[, "sdCV"]&#62;  CVLo = cverrs - sdCV&#62;  CVHi = cverrs + sdCV&#62;  ymax = max(CVHi)&#62;  ymin = min(CVLo)&#62;  k = 0:(length(cverrs) - 1)&#62;  plot(k, cverrs, ylim = c(ymin,+  ymax), type = "n", yaxt = "n")&#62;  points(k,cverrs,cex = 2,col="red",pch=16)&#62;  lines(k, cverrs, col = "red", lwd = 2)&#62;  axis(2, yaxp = c(0.6, 1.8, 6))&#62;  segments(k, CVLo, k, CVHi,col="blue", lwd = 2)&#62;  eps = 0.15&#62;  segments(k-eps, CVLo, k+eps, CVLo, + col = "blue", lwd = 2)&#62;  segments(k-eps, CVHi, k+eps, CVHi, + col = "blue", lwd = 2)&#62;  indMin = which.min(cverrs)&#62;  fmin = sdCV[indMin]&#62;  cutOff = fmin + cverrs[indMin]&#62;  abline(h = cutOff, lty = 2)&#62;  indMin = which.min(cverrs)&#62;  fmin = sdCV[indMin]&#62;  cutOff = fmin + cverrs[indMin]&#62;  min(which(cverrs &#60; cutOff))[1] 2If we summarize, here,stepwise, AIC : REPUL + INCARstepwise, BIC : REPUL + INCAROne-leave-Out CV stepwise : REPUL + INCAROne-leave-Out CV pairs : INCAR + PRDIA -fold CV stepwise : INSYS + INCAR -fold CV pairs : INCAR + PRDIATree : INSYS + REPULVariable Importance (RF) : INSYS + INCARBest GLM : REPUL + INCARThat is the lovely part with statistical tools: there are usually multiple (valid) answers. And this is why machine learning is difficult: if there was a single answer, any machine could built up a model that works well. But obviously, it has to be more complicated...