# Algorithms for automatic model selection

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 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.

• Frankly, I think this is a disastrous idea, just about guaranteed to lead to many false conclusions. – gung - Reinstate Monica 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 - Reinstate Monica 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
• Interesting views here, but I think the negative view towards algorithmic model selection procedures is a bit dated. Take, for instance, the recent work by David Hendry in the field of econometrics, particularly his work on the PcGive software and saturation methods. A lecture providing an overview of his approach can be found here. As @MichaelChernick has pointed out (and Hendry would do, too!), subject matter knowledge is (vastly) important. This is why there's value in subject specialists - to let the algorithms act alone is the mistake. – Graeme Walsh Nov 29 '16 at 4:01

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:

set.seed(59)
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.

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):

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.

• Phenomenal explanation of data dredging. – Frank Harrell Jan 10 '12 at 13:45
• 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 too 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
• for an illustration why AIC does not solve the problem see: Mundry, R. (2011). Issues in information theory-based statistical inference—a commentary from a frequentist’s perspective. Behavioral Ecology and Sociobiology, 65(1), 57-68. – jank Nov 21 '13 at 11:52

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.

• 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
• From what I understand, model selection by AIC and leave-one-out-cross-validation is essentially the same thing (asymptotic equivalence, see Stone, 1977), so AIC and some types of cross-validation are likely to lead to very similar results. However, I haven't used the caret package, and from the method calls it seems like AIC is indeed used in some cases. – fileunderwater Jan 26 '15 at 9:08

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.

• 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

To answer the question, there are several options:

1. all-subset by AIC/BIC

2. stepwise by p-value

3. stepwise by AIC/BIC

4. regularisation such as LASSO (can be based on either AIC/BIC or CV)

5. genetic algorithm (GA)

6. others?

7. use of non-automatic, theory ("subject matter knowledge") oriented selection

Next question would be which method is better. This paper (doi:10.1016/j.amc.2013.05.016) indicates “all possible regression” gave the same results to their proposed new method and stepwise is worse. A simple GA is between them. This paper (DOI:10.1080/10618600.1998.10474784) compares penalized regression (Bridge, Lasso etc) with “leaps-and-bounds” (seems an exhaustive search algorithm but quicker) and also found “the bridge model agrees with the best model from the subset selection by the leaps and bounds method”. This paper (doi:10.1186/1471-2105-15-88) shows GA is better than LASSO. This paper (DOI:10.1198/jcgs.2009.06164) proposed a method - essentially an all-subset (based on BIC) approach but cleverly reduce the computation time. They demonstrate this method is better than LASSO. Interestingly, this paper (DOI: 10.1111/j.1461-0248.2009.01361.x) shows methods (1)-(3) produce similar performance.

So overall the results are mixed but I got an impression that GA seems very good although stepwise may not be too bad and it is quick.

As for 7), the use of non-automatic, theory ("subject matter knowledge") oriented selection. It is time consuming and it is not necessarily better than automatic method. In fact in time-series literature, it is well established that automated method (especially commercial software) outperforms human experts "by a substantial margin" (doi:10.1016/S0169-2070(01)00119-4, page561 e.g. selecting various exponential smoothing and ARIMA models).

• Be aware that you can get differing performance in simulation studies of different selection algorithms by changing the data generating process to favor (even if not intentionally) a particular routine. The issue of what approach will be faster or slower is distinct, but potentially still important. – gung - Reinstate Monica Mar 17 '15 at 16:30
• In fact the examples in Tibshirani's original paper on LASSO illustrate @gung's point well. The same goes for comparative studies of different methods on real data. BTW, is your last reference right? The paper by Clements & Hendry with the DOI you give doesn't make the claim that automated methods out-perform human experts, or use the words "by a substantial margin" at all. (It'd be nice if you gave full references.) – Scortchi - Reinstate Monica Mar 17 '15 at 17:47
• Found it: Goodrich (2001), "Commercial software in the M3-Competition", Int. J. Forecast., 17, pp 560–565. It's under the same "Commentaries on the M3-Competition" collection as the Clements & Hendry paper, which is why Googling the DOI sent me there. – Scortchi - Reinstate Monica Mar 17 '15 at 18:21
• Anyway, it's not at all clear that Goodrich's comment has anything to do with subject-matter expertise. – Scortchi - Reinstate Monica Mar 17 '15 at 20:45
• @Scortchi it may be more clear on the article starting from page 581 on that issue of journal. It is more related to "M2-Competition" in which, automatic forecasting methods were compared with invited human experts (including some big names in time-series literature) who knew economic/industry context and could even ask for additional information from companies that provided the data. – heran_xp Mar 18 '15 at 17:45

Here's an answer out of left field- instead of using linear regression, use a regression tree (rpart package). This is suitable for automatic model selection because with a little work you can automate the selection of cp, the parameter used to avoid over-fitting.

linear model can be optimised by implementing genetic algorithm in the way of choosing most valuable independant variables. The variables are represented as genes in the algorithm, and the best chromosome (set of genes) are then being selected after crossover, mutation etc. operators. It is based on natural selection - then best 'generation' may survive, in other words, the algorithm optimises estimation function that depends on the particular model.

• That would select the "best" variables in the data, not necessarily the best variables in the data generating process / population, as it only has access to the data. It isn't really that dissimilar from the stepwise method the OP wanted. – gung - Reinstate Monica Mar 14 '15 at 16:59

We do have a function in the R base stats package, called step(), which does, forward, backward or stepwise selection of models based on lowest AIC. This also works for factor variables. Does this not server the purpose here?.

Answers here advises against variable selection, but the problem is real ... and still done. One idea that should be tried out more in practice is blind analyses, as discussed in this nature paper Blind analysis: Hide results to seek the truth.

This idea has been mentioned in another post at this site, Multiple comparison and secondary research. The idea of blinding data or introducing extra, simulated noise variables have certainly been used in simulation studies to show problems with stepwise, but the idea here is to use it, blinded, in actual data analysis.

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!

• (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"? – marbel Mar 16 '14 at 20:00
• Is this SE's most downvoted answer ever? – mkt - Reinstate Monica Dec 4 '17 at 15:44
• You seem to have answered @probabilityislogic 's important question by saying your goal "to find the best n factors to explain a given variable." Model-building to explain (to understand causality) needs to be done more intentionally and usually much more intensively than model-building to predict. – rolando2 Apr 14 '18 at 15:55