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.

🧩 Regularisation

Building on subset selection, an alternative approach is to include all p predictors in the model but apply regularization, which shrinks all coefficient estimates toward zero. Predictors that contribute little to the fit end up with coefficients close to (or even exactly) zero. As a result, we introduce some bias, but lower the variance of the estimates, which can improve test performance (remember the bias-variance tradeoff).

3 approaches are commonly used to regularize the predictors:

For the practical demonstration, we will again use the Hitters dataset:

Loading...

Once again, let’s take a look at the correlation between predictors to check for potential multicollinearity, which can affect the stability of linear regression models:

<Figure size 640x480 with 2 Axes>

We now continue to prepare our data by defining target and features and split it into training and test set:

Great! We are now ready for using the data in our regression models.

Ridge Regression

The loss function for ridge regression is defined as:

L(β)=∑i=1n(yi−Xi β)2  +  λ∑j=1pβj2L(\boldsymbol\beta)=\sum_{i=1}^{n}\bigl(y_i - \mathbf X_i\,\boldsymbol\beta\bigr)^2\;+\;\lambda\sum_{j=1}^{p} \beta_j^2

Where:

Combined:

We can implement Ridge regression as follows:

Step 1: We first standardize the predictors as ridge regression is sensitive to scaling. This can be done by using e.g. StandardScaler from scikit-learn:

Step 2: Next, we set up a range of values for λ. Good values can lie anywhere between very small and very large, so we test 100 values between 0.01 and 10,000 that are evenly spaced on a log scale:

Step 3: For each lambda, we will perform ridge regression on the training data. Cross-validation is then used to identify the optimal lambda that minimizes prediction error:

Optimal alpha: 100.0
Training R²: 0.4602782368374775

We can then inspect the coefficients of the regression model:

   Predictor       Beta
3      CHits  75.496776
6       Hits  56.284067
4     CWalks  48.245080
8      Years  41.904244
1       Runs  32.287559
7      HmRun  30.376020
2        RBI  29.545059
10     Walks  29.261608
0      AtBat  22.857245
9     Errors  -7.097005
5    Assists  -6.945251

Step 4: Finally, we can evaluate the model on the testing data to assess its ability for generalization:

Test R²: 0.2917715098347792

Additional visualization: To get a better intuition about how different lambda values affect the beta estimates, we can plot them for each model. The dashed line marks the λ chosen by cross-validation:

<Figure size 640x480 with 1 Axes>

Lasso Regression

In contrast to ridge regression, lasso regression can set some coefficients exactly to zero, which removes these predictors from the model. The loss function for lasso is given as:

L(β)=∑i=1n(yi−Xi β)2  +  λ∑j=1p∣βj∣L(\boldsymbol\beta)=\sum_{i=1}^{n}\bigl(y_i - \mathbf X_i\,\boldsymbol\beta\bigr)^2\;+\;\lambda\sum_{j=1}^{p}\bigl\lvert \beta_j \bigr\rvert

Where:

You can see, that the concept is nearly identical, with the only difference being the form of the penalty term. Lasso uses the L1 norm (∣βj∣\bigl\lvert \beta_j \bigr\rvert) while Ridge uses the L2 norm (βj2\beta_j^2). Because of this geometric difference in the penalty, Lasso can produce sparse models by zeroing out irrelevant features, whereas Ridge keeps all predictors in the model but with smaller weights. Both balance the trade‐off between model fit (the RSS term) and complexity via the tuning parameter λ, typically chosen by cross‐validation.

<Figure size 640x480 with 1 Axes>

Interactive: watch the coefficients shrink

The two path plots show all coefficients at once, which is informative but hard to read. Below, drag the slider to pick a single value of λ and compare the Ridge and Lasso models side by side: both their coefficients and what the shrinkage costs (or gains) you on the test set.

Source
Loading...

Two behaviours become obvious as you move the slider to the right:

Why Ridge and Lasso Behave Differently: The Budget

There is a second way to look at the penalty. Instead of adding it to the RSS, we can give the model a fixed budget tt for the size of its coefficients. We then look for the coefficients with the smallest RSS that stay within this budget:

Both views are equivalent: a large λ corresponds to a small budget tt, and λ = 0 to an unlimited budget.

With only two coefficients, we can draw the budget as an area. Let’s take a budget of t=1t = 1 and look at the points that use it up completely:

Everything inside the diamond or the circle stays within the budget:

Budget

Figure 1:The budget for Lasso (left) and Ridge (right) regression. Figure from James et al., An Introduction to Statistical Learning, Figure 6.7.

The solution is the point within the budget that has the smallest RSS. We find it by growing the ellipses around β^\hat\beta until they first touch the blue area. For Lasso, this often happens at a corner of the diamond. The corners lie on the axes, where one of the coefficients is exactly zero (here β1=0\beta_1 = 0). The circle has no corners, so Ridge usually ends up at a point where both coefficients are non-zero, just smaller. With many predictors, the diamond has many corners and edges, so Lasso solutions with several zeros are common.

Elastic Net Regression

Neither Ridge nor Lasso will universally be better than the other. The main difference between them is the coefficient selection:

Another point to note is their response to multicollinearity:

This is where elastic net regression comes into play. Elastic net is a combination of Ridge and Lasso:

L(β)  =  ∑i=1n(yi−Xi β)2  +  λ[α∑j=1p∣βj∣  +  1−α2∑j=1pβj2]L(\boldsymbol\beta) \;=\; \sum_{i=1}^{n}\bigl(y_i - \mathbf X_i\,\boldsymbol\beta\bigr)^2 \;+\; \lambda \Biggl[ \alpha \sum_{j=1}^{p}\bigl\lvert\beta_j\bigr\rvert \;+\; \frac{1 - \alpha}{2}\sum_{j=1}^{p}\beta_j^2 \Biggr]

Here, the mixing parameter α∈[0,1]\alpha\in[0,1] determines how much weight to give each penalty: when α=1\alpha=1 you recover pure Lasso (only an L1 penalty), and when α=0\alpha=0 you recover pure Ridge (only an L2 penalty); values in between blend the two. By combining these penalties, Elastic Net can both shrink coefficients (like Ridge) and select variables (like Lasso), while also tending to select or drop groups of correlated features together. In practice, you tune both λ (overall regularization strength) and α\alpha via cross-validation to find the best compromise between bias, variance, and sparsity for your particular dataset.

As a summary, we can look at the coefficients estimated by all introduced methods, each with its λ chosen by cross-validation:

<Figure size 640x480 with 1 Axes>

Look at AtBat and Hits: linear regression gives one a large negative and the other a large positive coefficient. The two predictors are correlated at 0.96, so OLS can trade one off against the other, and the estimates become unstable. All three regularized models keep both coefficients small. Elastic Net chose the smallest mixing ratio we offered (l1_ratio=0.1), so it behaves almost exactly like Ridge here, and its coefficients are nearly identical to the Ridge coefficients.

But which model predicts best? Let’s compare them on the test set:

Loading...

On this test set, plain linear regression actually performs best. With 184 training observations and only 11 predictors, OLS does not overfit much, so there is little variance that regularization could remove. Regularization pays off when there are many predictors relative to the number of observations, or when we want stable coefficients despite strongly correlated predictors. Lasso still offers something here: it reaches a test R² of 0.32 with only 4 of the 11 predictors.

Loading...
Loading...
Loading...
Loading...

Now it’s your turn: head to the exercise section for Exercise 2, in which you will implement a Lasso model.