Elastic Net Regularization › Formula

Michael BrenndoerferJune 12, 202518 min read
Machine Learning from ScratchAll chapters
Part 4 of 9Regression Models
Chapter 36Elastic Net Regularization › Formula
Reading section 2 of 8 · Formula · 18 minSection 2 of 8 · 18 min

Book contents

Section 2 of 8 · 18 min read

Elastic Net Regularization › FormulaOne section · Sections in this chapter2 / 8 ↓
Reading tools Definitions & inline links

Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.

Article links

Make inline references clickable

Let's build up the Elastic Net objective function step by step, starting from the most intuitive form and explaining each mathematical transformation along the way.

Starting with the Basic Regression Problem

We begin with the standard multiple linear regression problem. Our goal is to find coefficients β0,β1,β2,…,βp\beta_0, \beta_1, \beta_2, \ldots, \beta_p that minimize the sum of squared errors between our predictions and the actual values:

SSE=∑i=1n(yi−y^i)2\text{SSE} = \sum_{i=1}^n (y_i - \hat{y}_i)^2

where:

  • yiy_i is the actual target value for observation ii (where i=1,2,…,ni = 1, 2, \ldots, n)
  • y^i\hat{y}_i is the predicted value for observation ii
  • nn is the number of observations in the dataset

Here, y^i\hat{y}_i represents our predicted value for observation ii, which we calculate as:

y^i=β0+β1xi1+β2xi2+⋯+βpxip\hat{y}_i = \beta_0 + \beta_1 x_{i1} + \beta_2 x_{i2} + \cdots + \beta_p x_{ip}

where:

  • β0\beta_0 is the intercept term (constant offset)
  • βj\beta_j is the coefficient (weight) for feature jj (where j=1,2,…,pj = 1, 2, \ldots, p)
  • xijx_{ij} is the value of feature jj for observation ii
  • pp is the number of features (predictors) in the model

Adding Regularization Penalties

Now, instead of just minimizing the sum of squared errors, we want to add penalty terms that will help us control the complexity of our model. Elastic Net adds two types of penalties:

  1. L1 Penalty (LASSO component): λ1∑j=1p∣βj∣\lambda_1 \sum_{j=1}^p |\beta_j|
  2. L2 Penalty (Ridge component): λ2∑j=1pβj2\lambda_2 \sum_{j=1}^p \beta_j^2

where:

  • λ1>0\lambda_1 > 0 is the L1 regularization parameter (controls the strength of the L1 penalty)
  • λ2>0\lambda_2 > 0 is the L2 regularization parameter (controls the strength of the L2 penalty)
  • ∣βj∣|\beta_j| is the absolute value of coefficient βj\beta_j
  • βj2\beta_j^2 is the squared value of coefficient βj\beta_j

Let's understand why we use these specific penalty forms:

Why the L1 penalty uses absolute values?

The absolute value function ∣βj∣|\beta_j| has a special property: its derivative is not continuous at zero. This creates a "corner" in the objective function that can drive coefficients exactly to zero, effectively performing automatic feature selection. When we take the derivative of ∣βj∣|\beta_j|, we get:

  • ddβj∣βj∣=1\frac{d}{d\beta_j}|\beta_j| = 1 when βj>0\beta_j > 0
  • ddβj∣βj∣=−1\frac{d}{d\beta_j}|\beta_j| = -1 when βj<0\beta_j < 0
  • ddβj∣βj∣\frac{d}{d\beta_j}|\beta_j| is undefined at βj=0\beta_j = 0

This discontinuity is what allows LASSO to set coefficients exactly to zero.

Why the L2 penalty uses squared terms?

The squared penalty βj2\beta_j^2 has a smooth, continuous derivative everywhere: ddβjβj2=2βj\frac{d}{d\beta_j}\beta_j^2 = 2\beta_j. This smoothness helps with correlated features by encouraging similar coefficients for similar features, creating a "grouping effect." The penalty grows quadratically, so larger coefficients are penalized more heavily than smaller ones.

The Complete Elastic Net Objective Function

Combining all three components, our Elastic Net objective function becomes:

min⁡β{∑i=1n(yi−y^i)2+λ1∑j=1p∣βj∣+λ2∑j=1pβj2}\min_{\boldsymbol{\beta}} \left\{ \sum_{i=1}^n (y_i - \hat{y}_i)^2 + \lambda_1 \sum_{j=1}^p |\beta_j| + \lambda_2 \sum_{j=1}^p \beta_j^2 \right\}

where:

  • β=[β0,β1,…,βp]T\boldsymbol{\beta} = [\beta_0, \beta_1, \ldots, \beta_p]^T is the vector of coefficients we are optimizing
  • ∑i=1n(yi−y^i)2\sum_{i=1}^n (y_i - \hat{y}_i)^2 is the sum of squared errors (data fit term)
  • λ1∑j=1p∣βj∣\lambda_1 \sum_{j=1}^p |\beta_j| is the L1 penalty term (encourages sparsity)
  • λ2∑j=1pβj2\lambda_2 \sum_{j=1}^p \beta_j^2 is the L2 penalty term (encourages small coefficients)

Let's break down what each part does:

  • Data Fit Term ∑i=1n(yi−y^i)2\sum_{i=1}^n (y_i - \hat{y}_i)^2: Ensures our predictions are close to the actual values
  • L1 Penalty λ1∑j=1p∣βj∣\lambda_1 \sum_{j=1}^p |\beta_j|: Encourages sparsity by driving some coefficients to exactly zero
  • L2 Penalty λ2∑j=1pβj2\lambda_2 \sum_{j=1}^p \beta_j^2: Encourages small coefficients and handles correlated features well

The parameters λ1\lambda_1 and λ2\lambda_2 control the strength of each penalty:

  • When λ1=0\lambda_1 = 0 and λ2>0\lambda_2 > 0: We get pure Ridge regression
  • When λ1>0\lambda_1 > 0 and λ2=0\lambda_2 = 0: We get pure LASSO regression
  • When λ1>0\lambda_1 > 0 and λ2>0\lambda_2 > 0: We get Elastic Net

Understanding the Norm Notation

We can write the penalty terms more compactly using norm notation:

λ1∑j=1p∣βj∣+λ2∑j=1pβj2=λ1∥β∥1+λ2∥β∥22\lambda_1 \sum_{j=1}^p |\beta_j| + \lambda_2 \sum_{j=1}^p \beta_j^2 = \lambda_1 \|\boldsymbol{\beta}\|_1 + \lambda_2 \|\boldsymbol{\beta}\|_2^2

where:

  • ∥β∥1=∑j=1p∣βj∣\|\boldsymbol{\beta}\|_1 = \sum_{j=1}^p |\beta_j| is the L1 norm (Manhattan distance)
  • ∥β∥2=∑j=1pβj2\|\boldsymbol{\beta}\|_2 = \sqrt{\sum_{j=1}^p \beta_j^2} is the L2 norm (Euclidean distance)
  • ∥β∥22=∑j=1pβj2\|\boldsymbol{\beta}\|_2^2 = \sum_{j=1}^p \beta_j^2 is the squared L2 norm

The L1 norm measures the sum of absolute values, while the L2 norm measures the square root of the sum of squares. In our formulation, we use the squared L2 norm (∥β∥22\|\boldsymbol{\beta}\|_2^2) for mathematical convenience.

Why This Combination Works

Elastic Net's effectiveness comes from how these two penalties complement each other:

  1. The L1 penalty provides sparsity (feature selection) but can be unstable with correlated features
  2. The L2 penalty provides stability with correlated features but doesn't perform feature selection
  3. Together, they provide both sparsity and stability

This is particularly valuable when we have many features, some of which are correlated, and we want both interpretability through feature selection and stable coefficient estimates.

Geometric Interpretation of Regularization

To understand why Elastic Net combines the best of both worlds, let's visualize the constraint regions geometrically. In regularized regression, we can think of the problem as minimizing the sum of squared errors subject to a constraint on the coefficients.

Out[3]:
Visualization
Geometric diagram showing L1, L2, and Elastic Net constraint regions in coefficient space with loss function contours.
Geometric interpretation of regularization constraints in 2D coefficient space. The red contours represent the loss function (sum of squared errors), with the optimal OLS solution at the center. The blue regions show the constraint boundaries: L1 (diamond), L2 (circle), and Elastic Net (rounded diamond). The optimal regularized solution occurs where the loss contours first touch the constraint region. Notice how the L1 constraint has sharp corners that encourage sparsity (coefficients exactly zero on the axes), while the L2 constraint is smooth. Elastic Net combines both, creating a rounded diamond that can achieve sparsity at the corners while providing stability along the edges.

This geometric view reveals several key insights:

  1. L1 Constraint (Diamond): The sharp corners at the axes mean that the loss contours are likely to first touch the constraint region at a corner, resulting in sparse solutions where some coefficients are exactly zero.

  2. L2 Constraint (Circle): The smooth, round shape means the loss contours will touch the constraint region at a point where all coefficients are typically non-zero but small. This provides stability but no sparsity.

  3. Elastic Net Constraint (Rounded Diamond): By combining both penalties, we get a shape that has both corners (for sparsity) and smooth edges (for stability). This allows the model to achieve sparsity when needed while maintaining the grouping effect for correlated features.

The red contours represent levels of the loss function (sum of squared errors). The optimal solution for each method occurs where these contours first touch the respective constraint region. This geometric interpretation makes it clear why Elastic Net can achieve both feature selection and stability.it literally combines the geometric properties of both L1 and L2 constraints.

Matrix Notation

Now let's translate our objective function into matrix notation, which is more compact and reveals the mathematical structure more clearly.

First, let's define our matrices:

  • y\mathbf{y} is an n×1n \times 1 vector containing all target values: y=[y1,y2,…,yn]T\mathbf{y} = [y_1, y_2, \ldots, y_n]^T
  • X\mathbf{X} is an n×(p+1)n \times (p+1) design matrix where each row represents one observation and each column represents one feature (including the intercept column of ones)
  • β\boldsymbol{\beta} is a (p+1)×1(p+1) \times 1 vector of coefficients: β=[β0,β1,β2,…,βp]T\boldsymbol{\beta} = [\beta_0, \beta_1, \beta_2, \ldots, \beta_p]^T

where:

  • nn is the number of observations
  • pp is the number of features (excluding the intercept)
  • The superscript TT denotes the transpose operation

The predicted values can now be written as:

y^=Xβ\hat{\mathbf{y}} = \mathbf{X}\boldsymbol{\beta}

where y^=[y^1,y^2,…,y^n]T\hat{\mathbf{y}} = [\hat{y}_1, \hat{y}_2, \ldots, \hat{y}_n]^T is the n×1n \times 1 vector of predicted values.

This is much more compact than writing out each prediction individually. The sum of squared errors becomes:

∑i=1n(yi−y^i)2=∣∣y−Xβ∣∣22\sum_{i=1}^n (y_i - \hat{y}_i)^2 = ||\mathbf{y} - \mathbf{X}\boldsymbol{\beta}||_2^2

where ∣∣⋅∣∣2||\cdot||_2 represents the L2 norm (Euclidean norm), which for a vector v=[v1,v2,…,vn]T\mathbf{v} = [v_1, v_2, \ldots, v_n]^T is defined as:

∣∣v∣∣2=∑i=1nvi2||\mathbf{v}||_2 = \sqrt{\sum_{i=1}^n v_i^2}

Therefore, ∣∣y−Xβ∣∣22=∑i=1n(yi−y^i)2||\mathbf{y} - \mathbf{X}\boldsymbol{\beta}||_2^2 = \sum_{i=1}^n (y_i - \hat{y}_i)^2 is the squared Euclidean distance between the actual values and our predictions.

Similarly, the penalty terms become:

  • L1 penalty: λ1∣∣β∣∣1=λ1∑j=0p∣βj∣\lambda_1 ||\boldsymbol{\beta}||_1 = \lambda_1 \sum_{j=0}^p |\beta_j|
  • L2 penalty: λ2∣∣β∣∣22=λ2∑j=0pβj2\lambda_2 ||\boldsymbol{\beta}||_2^2 = \lambda_2 \sum_{j=0}^p \beta_j^2

where the summation includes all coefficients from j=0j=0 (intercept) to j=pj=p (last feature).

Putting it all together, our Elastic Net objective function in matrix notation is:

min⁡β{∣∣y−Xβ∣∣22+λ1∣∣β∣∣1+λ2∣∣β∣∣22}\min_{\boldsymbol{\beta}} \left\{ ||\mathbf{y} - \mathbf{X}\boldsymbol{\beta}||_2^2 + \lambda_1 ||\boldsymbol{\beta}||_1 + \lambda_2 ||\boldsymbol{\beta}||_2^2 \right\}

where:

  • min⁡β\min_{\boldsymbol{\beta}} indicates we are finding the coefficient vector β\boldsymbol{\beta} that minimizes the objective function
  • The objective function is the sum of three terms: data fit (SSE), L1 penalty, and L2 penalty

This notation makes it clear that we're minimizing a function of the coefficient vector β\boldsymbol{\beta}, and it's much more convenient for mathematical analysis and computational implementation.

Mathematical Properties

Understanding the mathematical properties of Elastic Net helps us predict how it will behave in different situations:

Sparsity and Grouping Effect: The L1 term encourages sparsity by driving some coefficients exactly to zero, while the L2 term encourages grouping of correlated features. This means that when features are highly correlated, Elastic Net tends to include the entire group rather than arbitrarily selecting one feature from the group (as LASSO might do).

Bias-Variance Tradeoff: As the regularization parameters λ1\lambda_1 and λ2\lambda_2 increase, the model becomes more biased (systematically wrong) but has lower variance (less sensitive to small changes in the data). This is the fundamental tradeoff in regularization.

Stability: The L2 component helps stabilize the solution when features are correlated, making the coefficient estimates more reliable and less sensitive to small changes in the data.

No Closed-Form Solution: Unlike Ridge regression, which has a closed-form solution, Elastic Net requires iterative optimization due to the non-differentiable L1 penalty. This makes it computationally more expensive but still more tractable than pure LASSO in many cases.

Convexity: The Elastic Net objective function is convex, which means it has a unique global minimum. This guarantees that our optimization algorithm will find the best solution.

Regularization Paths: Visualizing Coefficient Evolution

One of the most insightful ways to understand how Elastic Net behaves is to examine the regularization path.how coefficients change as we vary the regularization strength. This visualization reveals the key difference between LASSO and Elastic Net when dealing with correlated features.

Out[4]:
Visualization
Regularization path plot showing LASSO coefficient evolution with correlated features behaving independently.
LASSO regularization path showing coefficients evolve as regularization strength (α) increases. Notice how correlated features 0 and 1 (red and blue lines) behave independently.LASSO arbitrarily selects feature 0 and drives feature 1 to zero. As α increases, coefficients are driven to exactly zero at different points, with only the most important features surviving at high regularization.
Regularization path plot showing Elastic Net coefficient evolution with correlated features grouped together.
Elastic Net regularization path (α=0.5) showing coefficients evolve as regularization strength increases. Notice how correlated features 0 and 1 (red and blue lines) tend to stay together.both enter and exit the model simultaneously. This stability makes Elastic Net more reliable for interpretation when features are correlated, while still achieving sparsity at high regularization levels.

These regularization paths reveal the fundamental difference between LASSO and Elastic Net:

LASSO Path (Left): The red and blue lines (features 0 and 1, which are highly correlated) follow different trajectories. LASSO arbitrarily selects feature 0 and drives feature 1 to zero early in the path. This instability makes it difficult to interpret which feature is more important when features are correlated.

Elastic Net Path (Right): The red and blue lines stay close together throughout the regularization path. Both correlated features enter and exit the model together. This behavior is particularly useful when you have domain knowledge that certain features should be considered together.

The regularization path also shows how to select the optimal regularization strength: you would typically use cross-validation to find the α value that minimizes prediction error on held-out data, then read off the corresponding coefficients from these paths.

Alternative Parameterization

In practice, Elastic Net is often parameterized using a mixing parameter α\alpha and a total regularization strength λ\lambda. This alternative form makes it easier to understand the relationship between different regularization methods:

min⁡β{∣∣y−Xβ∣∣22+λ(α∣∣β∣∣1+1−α2∣∣β∣∣22)}\min_{\boldsymbol{\beta}} \left\{ ||\mathbf{y} - \mathbf{X}\boldsymbol{\beta}||_2^2 + \lambda \left( \alpha ||\boldsymbol{\beta}||_1 + \frac{1-\alpha}{2} ||\boldsymbol{\beta}||_2^2 \right) \right\}

where:

  • α∈[0,1]\alpha \in [0,1] is the mixing parameter (controls the balance between L1 and L2 penalties)
  • λ>0\lambda > 0 is the total regularization strength (controls how much regularization we apply overall)

The relationship between the two parameterizations is:

λ1=λαλ2=λ1−α2\begin{aligned} \lambda_1 &= \lambda \alpha \\ \lambda_2 &= \lambda \frac{1-\alpha}{2} \end{aligned}

where:

  • λ1\lambda_1 is the L1 penalty strength from the original formulation
  • λ2\lambda_2 is the L2 penalty strength from the original formulation

This parameterization makes it much easier to understand the behavior:

  • When α=1\alpha = 1: We get pure LASSO (L1 only) because the L2 term becomes zero
  • When α=0\alpha = 0: We get pure Ridge (L2 only) because the L1 term becomes zero
  • When 0<α<10 < \alpha < 1: We get Elastic Net with a balance between L1 and L2 penalties

The factor of 12\frac{1}{2} in the L2 term is included for mathematical convenience - it makes the derivatives cleaner and is a common convention in machine learning literature.

Scikit-learn Implementation

Scikit-learn uses a slightly different parameterization for computational efficiency:

min⁡β{12n∣∣y−Xβ∣∣22+α(ρ∣∣β∣∣1+1−ρ2∣∣β∣∣22)}\min_{\boldsymbol{\beta}} \left\{ \frac{1}{2n} ||\mathbf{y} - \mathbf{X}\boldsymbol{\beta}||_2^2 + \alpha \left( \rho ||\boldsymbol{\beta}||_1 + \frac{1-\rho}{2} ||\boldsymbol{\beta}||_2^2 \right) \right\}

where:

  • nn is the number of samples (observations)
  • α>0\alpha > 0 is the total regularization strength (equivalent to λ\lambda in the alternative parameterization)
  • ρ∈[0,1]\rho \in [0,1] is the l1_ratio parameter (equivalent to α\alpha in the alternative parameterization)
  • The factor 12n\frac{1}{2n} normalizes the data fit term by the sample size

In scikit-learn:

  • alpha parameter controls the overall regularization strength (α\alpha in the formula above)
  • l1_ratio parameter controls the mixing between L1 and L2 penalties (ρ\rho in the formula above)
  • When l1_ratio = 1 (ρ=1\rho = 1): Pure LASSO
  • When l1_ratio = 0 (ρ=0\rho = 0): Pure Ridge
  • When 0 < l1_ratio < 1 (0<ρ<10 < \rho < 1): Elastic Net
Note on Parameterization

Be careful with notation: scikit-learn's alpha parameter corresponds to λ\lambda in the mathematical literature, and scikit-learn's l1_ratio corresponds to the mixing parameter often denoted α\alpha in textbooks. Check the documentation for the specific implementation you're using to avoid confusion.

Mathematical Properties

  • Sparsity and Grouping: The L1 term encourages sparsity (some coefficients exactly zero), while the L2 term encourages grouping of correlated features
  • Bias-Variance Tradeoff: As λ\lambda increases, bias increases but variance decreases
  • Stability: The L2 term helps stabilize the solution when features are correlated
  • No Closed-Form Solution: Like LASSO, Elastic Net requires iterative optimization due to the L1 penalty