1 Introduction

Model selection is the process of choosing the most relevant features from a set of candidate variables. This procedure is crucial because it ensures that the final model is both accurate and interpretable while being computationally efficient and avoiding overfitting. Stepwise regression algorithms iteratively add or remove features from the model based on certain criteria (e.g., significance level or P-value, information criteria like AIC or BIC, etc.). The process continues until no further improvements can be made according to the chosen criterion. At the end of the stepwise procedure, you’ll have a final model that includes the selected features and their coefficients.

StepReg simplifies model selection tasks by providing a unified programming interface. It currently supports model buildings for five distinct response variable types (section 3.1), four model selection strategies (section 3.2) including the best subsets algorithm, and a variety of selection metrics (section 3.3). Moreover, StepReg detects and addresses the multicollinearity issues if they exist (section 3.4). The output of StepReg includes multiple tables summarizing the final model and the variable selection procedures. Additionally, StepReg offers a plot function to visualize the selection steps (section 4). For demonstration, the vignettes include four use cases covering distinct regression scenarios (section 5). Non-programmers can access the tool through the iterative Shiny app detailed in section 6.

2 Quick demo

The following example selects an optimal linear regression model with the mtcars dataset.

library(StepReg)
#devtools::load_all("~/GitHub/StepReg/")

data(mtcars)
formula <- mpg ~ .
res <- stepwise(formula = formula,
                data = mtcars,
                type = "linear",
                include = c("qsec"),
                strategy = "bidirection",
                metric = c("AIC"))

Breakdown of the parameters:

  • formula: specifies the dependent and independent variables
  • type: specifies the regression category, depending on your data, choose from “linear”, “logit”, “cox”, etc.
  • include: specifies the variables that must be in the final model
  • strategy: specifies the model selection strategy, choose from “forward”, “backward”, “bidirection”, “subset”
  • metric: specifies the model fit evaluation metric, choose one or more from “AIC”, “AICc”, “BIC”, “SL”, etc.

The output consists of multiple tables, which can be viewed with:

res
Table 1. Summary of arguments for model selection
‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗
                       Parameter        Value
—————————————————————————————————————————————
               included variable         qsec 
                        strategy  bidirection 
                          metric          AIC 
  tolerance of multicollinearity        1e-07 
      multicollinearity variable         NULL 
                       intercept            1 
‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗

Table 2. Summary of variables in dataset      
‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗
  Variable_type  Variable_name  Variable_class
——————————————————————————————————————————————
      Dependent            mpg         numeric 
    Independent            cyl         numeric 
    Independent           disp         numeric 
    Independent             hp         numeric 
    Independent           drat         numeric 
    Independent             wt         numeric 
    Independent           qsec         numeric 
    Independent             vs         numeric 
    Independent             am         numeric 
    Independent           gear         numeric 
    Independent           carb         numeric 
‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗

Table 3. Summary of selection process under bidirection with AIC
‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗
  Step  Enter_effect  Remove_effect  Number_parms         AIC
—————————————————————————————————————————————————————————————
     1             1                            1   149.94345 
     2          qsec                            2  145.776054 
     3            wt                            3    97.90843 
     4            am                            4   95.307305 
‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗

Table 4. Summary of coefficients for the selected model with mpg under bidirection and AIC 
‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗
     Variable   Estimate  Std. Error    t value  Pr(>|t|)
—————————————————————————————————————————————————————————
  (Intercept)   9.617781    6.959593   1.381946  0.177915 
         qsec   1.225886     0.28867   4.246676  0.000216 
           wt  -3.916504    0.711202  -5.506882     7e-06 
           am   2.935837    1.410905   2.080819  0.046716 
‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗

You can also visualize the variable selection procedures with:

plot(res)

The (+)1 refers to original model with intercept being added, (+) indicates variables being added to the model while (-) means variables being removed from the model.

Additionally, you can generate reports of various formats with:

report(res, report_name = "path_to/demo_res", format = "html")

Replace "path_to/demo_res" with desired output file name, the suffix ".html" will be added automatically. For detailed examples and more usage, refer to section 4 and 5.

3 Key features

3.1 Regression categories

StepReg supports multiple types of regressions, including linear, logit, cox, poisson, and gamma regressions. These methods primarily vary by the type of response variable, which are summarized in the table below. Additional regression techniques can be incorporated upon user requests.

Table 1: Common regression categories
Regression Reponse
linear continuous
logit binary
cox time-to-event
poisson count
gamma continuous and positively skewed

3.2 Model selection strategies

Model selection aims to identify the subset of independent variables that provide the best predictive performance for the response variable. Both stepwise regression and best subsets approaches are implemented in StepReg. For stepwise regression, there are mainly three methods: Forward Selection, Backward Elimination, Bidirectional Elimination.

Table 2: Model selection strategy
Strategy Description
Forward Selection In forward selection, the algorithm starts with an empty model (no predictors) and adds in variables one by one. Each step tests the addition of every possible predictor by calculating a pre-selected metric. Add the variable (if any) whose inclusion leads to the most statistically significant fit improvement. Repeat this process until more predictors no longer lead to a statistically better fit.
Backward Elimination In backward elimination, the algorithm starts with a full model (all predictors) and deletes variables one by one. Each step test the deletion of every possible predictor by calculating a pre-selected metric. Delete the variable (if any) whose loss leads to the most statistically significant fit improvement. Repeat this process until less predictors no longer lead to a statistically better fit.
Bidirectional Elimination Bidirectional elimination is essentially a forward selection procedure combined with backward elimination at each iteration. Each iteration starts with a forward selection step that adds in predictors, followed by a round of backward elimination that removes predictors. Repeat this process until no more predictors are added or excluded.
Best Subsets Stepwise algorithms add or delete one predictor at a time and output a single model without evaluating all candidates. Therefore, it is a relatively simple procedure that only produces one model. In contrast, the Best Subsets algorithm calculates all possible models and output the best-fitting models with one predictor, two predictors, etc., for users to choose from.

Given the computational constraints, when dealing with datasets featuring a substantial number of predictor variables greater than the sample size, the Bidirectional Elimination typically emerges as the most advisable approach. Forward Selection and Backward Elimination can be considered in sequence. On the contrary, the Best Subsets approach requires the most substantial processing time, yet it calculates a comprehensive set of models with varying numbers of variables. In practice, users can experiment with various methods and select a final model based on the specific dataset and research objectives at hand.

3.3 Selection metrics

Various selection metrics can be used to guide the process of adding or removing predictors from the model. These metrics help to determine the importance or significance of predictors in improving the model fit. In StepReg, selection metrics include two categories: Information Criteria and Significance Level of the coefficient associated with each predictor. Information Criteria is a means of evaluating a model’s performance, which balances model fit with complexity by penalizing models with a higher number of parameters. Lower Information Criteria values indicate a better trade-off between model fit and complexity. Note that when evaluating different models, it is important to compare them within the same Information Criteria framework rather than across multiple Information Criteria. For example, if you decide to use AIC, you should compare all models using AIC. This ensures consistency and fairness in model comparison, as each Information Criterion has its own scale and penalization factors. In practice, multiple metrics have been proposed, the ones supported by StepReg are summarized below.

Importantly, given the discrepancies in terms of the precise definitions of each metric, StepReg mirrors the formulas adopted by SAS for univariate multiple regression (UMR) except for HQ, IC(1), and IC(3/2). A subset of the UMR can be easily extended to multivariate multiple regression (MMR), which are indicated in the following table.

Table 3: Statistics in selection metric
Statistic Meanings
\({n}\) Sample Size
\({p}\) Number of parameters including the intercept
\({q}\) Number of dependent variables
\(\sigma^2\) Estimate of pure error variance from fitting the full model
\({SST}\) Total sum of squares corrected for the mean for the dependent variable, which is a numeric value for UMR and a matrix for multivariate regression
\({SSE}\) Error sum of squares, which is a numeric value for UMR and a matrix for multivariate regression
\(\text{LL}\) The natural logarithm of likelihood
\({| |}\) The determinant function
\(\ln()\) The natural logarithm
Table 4: Abbreviation, Definition, and Formula of the Selection Metric for Linear, Logit, Cox, Possion, and Gamma regression
Abbreviation Definition Formula
linear logit, cox, poisson and gamma
AIC Akaike’s Information Criterion \(n\ln\left(\frac{|\text{SSE}|}{n}\right) + 2pq + n + q(q+1)\)
(Clifford M. Hurvich 1989; Al-Subaihi 2002)\(^1\)
\(-2\text{LL} + 2p\)
(Darlington 1968; George G. Judge 1985)
AICc Corrected Akaike’s Information Criterion \(n\ln\left(\frac{|\text{SSE}|}{n}\right) + \frac{nq(n+p)}{n-p-q-1}\)
(Clifford M. Hurvich 1989; Edward J. Bedrick 1994)\(^2\)
\(-2\text{LL} + \frac{n(n+p)}{n-p-2}\)
(Clifford M. Hurvich 1989)
BIC Sawa Bayesian Information Criterion \(n\ln\left(\frac{SSE}{n}\right) + 2(p+2)o - 2o^2, o = \frac{n\sigma^2}{SSE}\)
(Sawa 1978; George G. Judge 1985)
not available for MMR
not available
Cp Mallows’ Cp statistic \(\frac{SSE}{\sigma^2} + 2p - n\)
(Mallows 1973; Hocking 1976)
not available for MMR
not available
HQ Hannan and Quinn Information Criterion \(n\ln\left(\frac{|\text{SSE}|}{n}\right) + 2pq\ln(\ln(n))\)
(E. J. Hannan 1979; Allan D R McQuarrie 1998; Clifford M. Hurvich 1989)
\(-2\text{LL} + 2p\ln(\ln(n))\)
(E. J. Hannan 1979)
IC(1) Information Criterion with Penalty Coefficient Set to 1 \(n\ln\left(\frac{|\text{SSE}|}{n}\right) + p\)
(J. A. Nelder 1972; A. F. M. Smith 1980) not available for MMR
\(-2\text{LL} + p\)
(J. A. Nelder 1972; A. F. M. Smith 1980)
IC(3/2) Information Criterion with Penalty Coefficient Set to 3/2 \(n\ln\left(\frac{|\text{SSE}|}{n}\right) + \frac{3}{2}p\)
(A. F. M. Smith 1980)
not available for MMR
\(-2\text{LL} + \frac{3}{2}p\)
(A. F. M. Smith 1980)
SBC Schwarz Bayesian Information Criterion \(n\ln\left(\frac{|\text{SSE}|}{n}\right) + p \ln(n)\)
(Clifford M. Hurvich 1989; Schwarz 1978; George G. Judge 1985; Al-Subaihi 2002)
not available for MMR
\(-2\text{LL} + p\ln(n)\)
(Schwarz 1978; George G. Judge 1985)
SL Significance Level (pvalue) \(\textit{F test}\) for UMR and \(\textit{Approximate F test}\) for MMR Forward: LRT and Rao Chi-square test (logit, poisson, gamma); LRT (cox);

Backward: Wald test
Rsq R-square statistic \(1 - \frac{SSE}{SST}\)
not available for MMR
not available
adjRsq Adjusted R-square statistic \(1 - \frac{(n-1)(1-R^2)}{n-p}\)
(Darlington 1968; George G. Judge 1985)
not available for MMR
not available
1 Unsupported AIC formula (which does not affect the selection process as it only differs by constant additive and multiplicative factors):

\(AIC=n\ln\left(\frac{SSE}{n}\right) + 2p\) (Darlington 1968; George G. Judge 1985)
2 Unsupported AICc formula (which does not affect the selection process as it only differs by constant additive and multiplicative factors):

\(AICc=\ln\left(\frac{SSE}{n}\right) + 1 + \frac{2(p+1)}{n-p-2}\) (Allan D R McQuarrie 1998)

No metric is necessarily optimal for all datasets. The choice of them depends on your data and research goals. We recommend using multiple metrics simultaneously, which allows the selection of the best model based on your specific needs. Below summarizes general guidance.

  • AIC: AIC works by penalizing the inclusion of additional variables in a model. The lower the AIC, the better performance of the model. AIC does not include sample size in penalty calculation, and it is optimal in minimizing the mean square error of predictions (Mark J. Brewer 2016).

  • AICc: AICc is a variant of AIC, which works better for small sample size, especially when numObs / numParam < 40 (Kenneth P. Burnham 2002).

  • Cp: Cp is used for linear models. It is equivalent to AIC when dealing with Gaussian linear model selection.

  • IC(1) and IC(3/2): IC(1) and IC(3/2) have 1 and 3/2 as penalty factors respectively, compared to 2 used by AIC. As such, IC(1) turns to return a complex model with more variables that may suffer from overfitting issues.

  • BIC and SBC: Both BIC and SBC are variants of Bayesian Information Criterion. The main distinction between BIC/SBC and AIC lies in the magnitude of the penalty imposed: BIC/SBC are more parsimonious when penalizing model complexity, which typically results to a simpler model (SAS Institute Inc 2018; Sawa 1978; Clifford M. Hurvich 1989; Schwarz 1978; George G. Judge 1985; Al-Subaihi 2002).

The precise definitions of these criteria can vary across literature and in the SAS environment. Here, BIC aligns with the definition of the Sawa Bayesion Information Criterion as outlined in SAS documentation, while SBC corresponds to the Schwarz Bayesian Information Criterion. According to Richard’s post, whereas AIC often favors selecting overly complex models, BIC/SBC prioritize a small models. Consequently, when dealing with a limited sample size, AIC may seem preferable, whereas BIC/SBC tend to perform better with larger sample sizes.

  • HQ: HQ is an alternative to AIC, differing primarily in the method of penalty calculation. However, HQ has remained relatively underutilized in practice (Kenneth P. Burnham 2002).

  • Rsq: The R-squared (R²) statistic measures the proportion of variations that is explained by the model. It ranges from 0 to 1, with 1 indicating that all of the variability in the response variables is accounted for by the independent variables. As such, R-squared is valuable for communicating the explanatory power of a model. However, R-squared alone is not sufficient for selection because it does not take into account the complexity of the model. Therefore, while R-squared is useful for understanding how well the model fits the data, it should not be the sole criterion for model selection.

  • adjRsq: The adjusted R-squared (adj-R²) seeks to overcome the limitation of R-squared in model selection by considering the number of predictors. It serves a similar purpose to information criteria, as both methods compare models by weighing their goodness of fit against the number of parameters. However, information criteria are typically regarded as superior in this context (Stevens 2016).

  • SL: SL stands for Significance Level (P-value), embodying a distinct approach to model selection in contrast to information criteria. The SL method operates by calculating a P-value through specific hypothesis testing. Should this P-value fall below a predefined threshold, such as 0.05, one should favor the alternative hypothesis, indicating that the full model significantly outperforms the reduced model. The effectiveness of this method hinges upon the selection of the P-value threshold, wherein smaller thresholds tend to yield simpler models.

3.4 Multicollinearity

This blog by Jim Frost gives an excellent overview of multicollinearity and when it is necessary to remove it.

Simply put, a dataset contains multicollinearity when input predictors are correlated. When multicollinearity occurs, the interpretability of predictors will be badly affected because changes in one input variable lead to changes in other input variables. Therefore, it is hard to individually estimate the relationship between each input variable and the dependent variable.

Multicollinearity can dramatically reduce the precision of the estimated regression coefficients of correlated input variables, making it hard to find the correct model. However, as Jim pointed out, “Multicollinearity affects the coefficients and p-values, but it does not influence the predictions, precision of the predictions, and the goodness-of-fit statistics. If your primary goal is to make predictions, and you don’t need to understand the role of each independent variable, you don’t need to reduce severe multicollinearity.”

In StepReg, QC Matrix Decomposition is performed ahead of time to detect and remove input variables causing multicollinearity.

4 StepReg output

StepReg provides multiple functions for summarizing the model building results. The function stepwise() generates a list of tables that describe the feature selection steps and the final model. To facilitate collaborations, you can redirect the tables into various formats such as “xlsx”, “html”, “docx”, etc. with the function report(). Furthermore, you can easily compare the variable selection procedures for multiple selection metrics by visualizing the steps with the function plot(). Details see below.

Depending on the number of selected regression strategies and metrics, you can expect to receive at least four tables from stepwise(). Below describes the content of each of 4 tables from Quick Demo 2.

Table 5: Tables generated by StepReg
Table_Name Table_Description
Summary of arguments for model selection Arguments used in the stepwise function, either default or user-supplied values.
Summary of variables in dataset Variable names, types, and classes in dataset.
Summary of selection process under xxx(strategy) with xxx(metric) Overview of the variable selection process under specified strategy and metric.
Summary of coefficients for the selected model with xxx(dependent variable) under xxx(strategy) and xxx(metric) Coefficients for the selected models under specified strategy with metric

You can save the output in different format like “xlsx”, “docx”, “html”, “pptx”, and others, facilitating easy sharing. Of note, the suffix will be automatically added to the report_name. For instance, the following example generates both “results.xlsx” and “results.docx” reports.

report(res, report_name = "results", format = c("xlsx", "docx"))

5 Use cases

Please choose the regression model that best suits the type of response variable. For detailed guidance, see section 3.1. Below, we present various examples utilizing different models tailored to specific datasets.

5.1 Linear regression with the mtcars dataset

In this section, we’ll demonstrate how to perform linear regression analysis using the mtcars dataset, showcasing different scenarios with varying numbers of predictors and dependent variables. We set type = "linear" to direct the function to perform linear regression.

Description of the mtcars dataset

The mtcars