Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

✅ Model Selection

As data scientists, you often have to work with huge amounts of data. For example, smart phones produce thousands of measurements a day. Having more information can, in theory, help us make better predictions, but it also brings risks: too many variables can make analyses infeasible, lead to false discoveries, or cause models to learn noise instead of real effects.

The large p issue

Big data refers to large data sets with many predictors which often cannot be processed or analyzed using traditional data processing techniques. For our prediction models, this brings some issues:

This is where techniques like linear model selection become into play to refine our models.

Today’s data: Hitters

For practical demonstration, we will use the Hitters dataset. This dataset provides Major League Baseball Data from the 1986 and 1987 seasons. It contains 322 observations of major league players on 20 variables (so it’s not big data, but we can pretend it is). The Research aim is to predict a baseball player’s salary on the basis of various predictors associated with the performance in the previous year. You can check its contents here: https://islp.readthedocs.io/en/latest/datasets/Hitters.html

For computational reasons, we will not include all predictors but only a smaller subset:

Loading...

Let’s also take a look at the correlation matrix to check for potential multicollinearity, which can affect the stability of linear regression models.

<Figure size 640x480 with 2 Axes>

The heatmap reveals strong correlations between several predictors:

We thus remove two of the correlated features:

Handling big data in linear models

Subset Selection

In subset selection we identify a subset of the pp predictors that are truly related to the outcome. The model is then fitted using least squares on the reduced set of variables.

How do we determine which variables are relevant?

Best Subset Selection

We will start with performing Best Subset Selection (also called exhaustive search) as implemented in the mlxtend package. It has great documentation, e.g. for the exhaustive search. In short, this approach is a brute-force evaluation of feature subsets. A specific performance metric (e.g. MSE, R², or accuracy) is optimized given an arbitrary regressor or classifier. For example, if we have 4 features, the algorithm will evaluate all 15 possible combinations of features (all 24=162^4 = 16 subsets except the empty one).

Loading...
Loading...

Before we start the subset selection, we first define the target and the features:

We first split our data into training and test dataset. Although the selection function uses cross-validation to identify the best subset of predictors, this evaluation is done during the selection process and can still overfit to the data: when we pick the best of many CV scores, we also pick the subset that got luckiest on these folds. To fairly assess how the final model performs on new data, we split off a test set and use it only after feature selection is complete.

PurposeWhat is it for?When?
Cross Validation in selection functionHelps choose the best subset of featuresDuring selection
Test Set EvaluationChecks how well the final model performsAfter selection

We then run Best Subset Selection on the training data:

Best R²: 0.41
Best subset (indices): (1, 3, 4)
Best subset (corresponding names): ('CWalks', 'Hits', 'HmRun')

If you are interested in the details, they are stored in the metric dictionary:

Loading...

Because the exhaustive search evaluated every subset, we can also draw the picture that motivates the whole chapter: how good is the best model of each size?

Source
Number of subsets evaluated: 127  (= 2^7 - 1)
<Figure size 700x450 with 1 Axes>

Two things are worth noticing. First, more features do not automatically give a better model. On the training data, adding a feature can never decrease the R², but the cross-validated R² rises, peaks at 3 features, and then declines again. Second, the curve is almost flat between 2 and 6 features. Many different subsets perform about equally well, so we should not over-interpret which exact features end up in the “best” model.

Forward Stepwise Selection

Forward Stepwise Selection is a greedy feature‐selection method that starts with no features and, at each step, adds the single feature whose inclusion most improves the model’s performance. This “add the best remaining feature” is repeated until a desired number of features is reached, at which point the algorithm stops and returns the best subset.

An important parameter is k_features, which determines the number of features to select. We can pass an integer (at most the total number of available features), a tuple (the algorithm will then evaluate all subset sizes between the min and max value), or one of two string options ("best", or "parsimonious"). Please refer to the documentation for further details.

>> Forward SFS:
   Best CV R²      : 0.413
   Optimal # feats : 3
   Feature indices : (1, 3, 4)
   Feature names   : ('CWalks', 'Hits', 'HmRun')

You can see we ended up with the same three predictors as in best subset selection: CWalks, Hits, HmRun. However, this is not necessarily always the case! Best subset and stepwise selection can, and often will, lead to different results. In our case we only had a small number of predictors, which makes it more likely to end up with the same subset.

Backward Stepwise Selection

Backward Stepwise Selection begins with the full feature set and, at each step, removes the single feature whose exclusion most improves (or least harms) model performance. We keep repeating this “remove the worst feature” step until only the desired number of features remains, and then the algorithm returns that reduced subset:

<< Backward SFS:
   Best CV R²      : 0.413
   Optimal # feats : 3
   Feature indices : (1, 3, 4)
   Feature names   : ('CWalks', 'Hits', 'HmRun')

Summary

Selection methodFinds the best subset?Computational costWorks for p > n?
Best subsetYes (best CV score among all subsets)Very high: 2p2^p modelsNo
Forward stepwiseNot guaranteedLow: about p2/2p^2/2 modelsYes, for models with fewer than n features
Backward stepwiseNot guaranteedLow: about p2/2p^2/2 modelsNo, because it starts by fitting the full model
Loading...
Loading...
Loading...
Loading...

What next?

All three procedures converged on the same three predictors here, so let’s evaluate the model performance and estimate the true test error using that subset.

Test MSE:  182321.00
Test RMSE: 426.99
Test R²:   0.2492

So in sum:

But did the selection actually help? For comparison, let’s evaluate the full model with all 7 features on the same test set:

Test R² (all 7 features):     0.2864
Test R² (3 selected features): 0.2492

The full model is not worse. Subset selection gave us a simpler model with 3 instead of 7 predictors, but not a better one. With only 79 players in the test set, a difference of this size could also be due to chance. This is typical: subset selection mainly makes models simpler and easier to interpret, but it does not guarantee better predictions.

Regularization and Dimensionality Reduction

As mentioned before, regularization and dimensionality reduction are two other ways of dealing with large numbers of predictors. Regularization is covered in the next chapter, and dimensionality reduction in the 🔎 PCA, PCR & PLS session.