Take the 2-minute tour ×
Cross Validated is a question and answer site for people interested in statistics, machine learning, data analysis, data mining, and data visualization. It's 100% free, no registration required.

I would like to implement an algorithm for automatic model selection. I am thinking of doing stepwise regression but anything will do (it has to be based on linear regressions though).

My problem is that I am unable to find a methodology, or an open source implementation (I am woking in java). The methodology I have in mind would be something like:

  1. calculate the correlation matrix of all the factors
  2. pick the factors that have a low correlation to each other
  3. remove the factors that have a low t-stat
  4. add other factors (still based on the low correlation factor found in 2.).
  5. reiterate several times until some criterion (e.g AIC) is over a certain threshold or cannot or we can't find a larger value.

I would like to have some advice on that. I realize there is an R implementation for this (stepAIC) but I find the code quite hard to understand. Also I have not been able to find articles describing the stepwise regression.

share|improve this question
Frankly, I think this is a disastrous idea, just about guaranteed to lead to many false conclusions. –  gung Jan 9 '12 at 18:30
@gung: while I agree that blindly following the result of a model selection is a bad idea, I think it can be useful as a starting point of an analysis. In my case I have several hundreds of factors available, and I would like to pick the 5-10 most relevant. I don't see how I could do that without automatic model selection (which will later be manually amended). –  S4M Jan 10 '12 at 9:33
All model selection procedures are subject to the problems that I discuss in my answer below. In addition, the larger the number of possible factors you want to search over, the more extreme those problems become, and the increase is not linear. While there are some better approaches (discussed by @Zach), which should be used in conjunction with cross-validation (discussed by @JackTanner), selecting based on t, r and AIC are not among them. Moreover, with hundreds of factors the amount of data needed could easily be in the millions. Unfortunately, you have a very difficult task before you. –  gung Jan 10 '12 at 16:21
What is the purpose of doing model selection? Is it for a predictive/forecasting model or are you looking for the important variables? Also how big is the data set you are using - how many obsevations and how many variables? –  probabilityislogic Jan 31 '12 at 5:42
I always say beware of automatic algorithms. It always helps to include subject matter knowledge. Stepwise procedures have problems. I twould pay for you to read one of the many books available on model selection. –  Michael Chernick May 4 '12 at 17:57
add comment

4 Answers

I think this approach is mistaken, but perhaps it will be more helpful if I explain why. Wanting to know the best model given some information about a large number of variables is quite understandable. Moreover, it is a situation in which people seem to find themselves regularly. In addition, many textbooks (and courses) on regression cover stepwise selection methods, which implies that they must be legitimate. Unfortunately however, they are not, and the pairing of this situation and goal are quite difficult to successfully navigate. The following is a list of problems with automated stepwise model selection procedures (attributed to Frank Harrell, and copied from here):

  1. It yields R-squared values that are badly biased to be high.
  2. The F and chi-squared tests quoted next to each variable on the printout do not have the claimed distribution.
  3. The method yields confidence intervals for effects and predicted values that are falsely narrow; see Altman and Andersen (1989).
  4. It yields p-values that do not have the proper meaning, and the proper correction for them is a difficult problem.
  5. It gives biased regression coefficients that need shrinkage (the coefficients for remaining variables are too large; see Tibshirani [1996]).
  6. It has severe problems in the presence of collinearity.
  7. It is based on methods (e.g., F tests for nested models) that were intended to be used to test prespecified hypotheses.
  8. Increasing the sample size does not help very much; see Derksen and Keselman (1992).
  9. It allows us to not think about the problem.
  10. It uses a lot of paper.

The question is, what's so bad about these procedures / why do these problems occur? Most people who have taken a basic regression course are familiar with the concept of regression to the mean, so this is what I use to explain these issues. (Although this may seem off-topic at first, bear with me, I promise it's relevant.)

Imagine a high school track coach on the first day of tryouts. Thirty kids show up. These kids have some underlying level of intrinsic ability to which neither the coach, nor anyone else, has direct access. As a result, the coach does the only thing he can do, which is have them all run a 100m dash. The times are presumably a measure of their intrinsic ability and are taken as such. However, they are probabilistic; some proportion of how well someone does is based on their actual ability and some proportion is random. Imagine that the true situation is the following:

intrinsic_ability = runif(30, min=9, max=10)
time = 31 - 2*intrinsic_ability + rnorm(30, mean=0, sd=.5)

The results of the first race are displayed in the following figure along with the coach's comments to the kids.

first race

Note that partitioning the kids by their race times leaves overlaps on their intrinsic ability--this fact is crucial. After praising some, and yelling at some others (as coaches tend to do), he has them run again. Here are the results of the second race with the coach's reactions (simulated from the same model above):

second race

Notice that their intrinsic ability is identical, but the times bounced around relative to the first race. From the coach's point of view, those he yelled at tended to improve, and those he praised tended to do worse (I adapted this concrete example from the Kahneman quote listed on the wiki page), although actually regression to the mean is a simple mathematical consequence of the fact that the coach is selecting athletes for the team based on a measurement that is partly random.

Now, what does this have to do with automated (e.g., stepwise) model selection techniques? Developing and confirming a model based on the same dataset is sometimes called data dredging. Although there is some underlying relationship amongst the variables, and stronger relationships are expected to yield stronger scores (e.g., higher t-statistics), these are random variables and the realized values contain error. Thus, when you select variables based on having higher (or lower) realized values, they may be such because of their underlying true value, error, or both. If you proceed in this manner, you will be as surprised as the coach was after the second race. This is true whether you select variables based on having high t-statistics, or low intercorrelations. True, using the AIC is better than using p-values, because it penalizes the model for complexity, but the AIC is itself a random variable (if you run a study several times and fit the same model, the AIC will bounce around just like everything else). Unfortunately, this is just a problem intrinsic to the epistemic nature of reality itself.

I hope this is helpful.

share|improve this answer
Phenomenal explanation of data dredging. –  Frank Harrell Jan 10 '12 at 13:45
+1- I look forward to linking to this answer in the future. –  David Robinson Jan 11 '12 at 6:36
This is a very well thought out answer, although i completely disagree with the idea that aic is an improvement over p-values (or bic or similar), in the context of linear model selection. any penalty like aic which is of the form $-2L+kp$ is equivalent to setting the p-value to $Pr(\chi^2_1>k)$ (both entry and exit). aic basically tells you how to choose the p-value. –  probabilityislogic Jan 31 '12 at 6:00
My comment was in regards to using aic for stepwise or similar algorithm. My comment was also to brief. Note $p$ is number of variables, $k$ is penalty ($2$ for aic $\log N$ for bic), and $-2L$ is negative twice the maximised log likelihood. Aic and bic are different conceptually but not operationally from p-values when doing "subset" style selection with no shrinkage of the non-zero coefficients. –  probabilityislogic Jan 31 '12 at 9:29
@gung - if you take the difference between two models with one parameter different you get $(-2L_1+2p_0+2)-(-2L_0+2p_0)=-2(L_1-L_0)+2$. Now the first term is the likelihood ratio statistic upon which the p-value is based. So we are adding the extra parameter if the likelihood ratio statistic is bigger than some cutoff. This is the same as what the p-value approach is doing. There is only a conceptual difference here –  probabilityislogic Feb 1 '12 at 1:11
show 6 more comments

Check out the caret package in R. It will help you cross-validate step-wise regression models (use method='lmStepAIC' or method='glmStepAIC'), and might help you understand how these sorts of models tend to have poor predictive performance. Furthermore, you can use the findCorrelation function in caret to identify and eliminate collinear variables, and the rfe function in caret to eliminate variables with a low t-statistic (use rfeControl=rfeControl(functions=lmFuncs)).

However, as mentioned in the previous answers, these methods of variable selection are likely to get you in trouble, particularly if you do them iteratively. Make absolutely certain you evaluate your performance on a COMPLETELY held-out test set. Don't even look at the test set until you are happy with your algorithm!

Finally, it might be better (and simpler) to use predictive model with "built-in" feature selection, such as ridge regression, the lasso, or the elastic net. Specifically, try the method=glmnet argument for caret, and compare the cross-validated accuracy of that model to the method=lmStepAIC argument. My guess is that the former will give you much higher out-of-sample accuracy, and you don't have to worry about implementing and validating your custom variable selection algorithm.

share|improve this answer
Penalties like the double pareto are better than ridge and lasso from a statistical perspective, as they don't shrink the clearly non-zero coefficients. But unfortunately, they always lead to a non-convex penalty, so they are worse from a computational perspective. I would think a penalty based on the Cauchy distribution would be good $\log(\lambda^2+\beta^2)$. –  probabilityislogic Jun 30 '13 at 0:02
@probabilityislogic Do you know of any good implementations of the double pareto penalty, in a language like r or python? I'd love to try it out. –  Zach Jun 30 '13 at 1:29
add comment

I fully concur with the problems outlined by @gung. That said, realistically speaking, model selection is a real problem in need of a real solution. Here's something I would use in practice.

  1. Split your data into training, validation, and test sets.
  2. Train models on your training set.
  3. Measure model performance on the validation set using a metric such as prediction RMSE, and choose the model with the lowest prediction error.
  4. Devise new models as necessary, repeat steps 2-3.
  5. Report how well the model performs on the test set.

For an example of the use of this method in the real world, I believe that it was used in the Netflix Prize competition.

share|improve this answer
Data splitting is not reliable unless $n>20000$. –  Frank Harrell Jan 10 '12 at 13:46
@Frank: Why do you think N needs to be so high? –  rolando2 Jan 11 '12 at 2:29
Because of poor precision. If you split again you can get much different results. That's why people do 100 repeats of 10-fold cross-validation, or bootstrapping. –  Frank Harrell Jan 11 '12 at 3:07
@FrankHarrell What does that n>20000 figure depend on? Is it based on the original poster's comment about having "several hundreds of factors"? Or is it independent of any aspect of the data? –  Darren Cook Jan 13 '12 at 0:51
The kind of setting that I testing data splitting on was n=17000 with a fraction of 0.3 having an event, and having about 50 parameters examined or fitted in a binary logistic model. I used a random 1:1 split. The validated ROC area in the test sample changed substantively when I re-split the data and started over. Look under Studies of Methods Used in the Text in biostat.mc.vanderbilt.edu/rms for simulation studies and related papers giving more information. –  Frank Harrell Jan 13 '12 at 13:41
show 1 more comment
up vote -11 down vote accepted

I see my question generated lots of interest and an interesting debate about the validity of the automatic model selection approach. While I agree that taking for granted the result of an automatic selection is risky, it can be used as a starting point. So here is how I implemented it for my particular problem, which is to find the best n factors to explain a given variable

  1. do all the regressions variable vs individual factors
  2. sort the regression by a given criterion (say AIC)
  3. remove the factors that have a low t-stat: they are useless in explaining our variable
  4. with the order given in 2., try to add the factors one by one to the model, and keep them when they improve our criterion. iterate for all the factors.

Again, this is very rough, there may be ways to improve the methodology, but that is my starting point. I am posting this answer hoping it can be useful for someone else. Comments are welcome!

share|improve this answer
(1) I haven't witnessed any "debate" in this thread: all replies and comments present the same basic message. (2) Your implementation appears to be an ad hoc version of stepwise regression. I agree that it can be useful as a starting point provided it is not automatically accepted as an end in itself. –  whuber Feb 11 '12 at 16:25
you did actually accept your own answer that moves against every argument brought forward by the community. Not surprising to see the negatives here... –  jank Nov 21 '13 at 11:56
I believe it's the first time i see so many downvotes. @SAM why don't you just accept some of the other excellent answers and delete your "answer"? –  Martín Bel Mar 16 at 20:00
add comment

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.