Skip to content
E
Educatum

Derivation of Ridge and Lasso Regularization

Curated by Educatum AI teamLast updated:
Regularization TechniquesRegularization
Direct Answer

Ridge and Lasso augment ordinary least squares (OLS) with squared L2 and L1 coefficient penalties, respectively. Setting the Ridge gradient to zero yields a closed-form solution that adds lambda I to X-transpose X, ensuring invertibility; Lasso's non-differentiable L1 penalty is solved via subdifferential KKT conditions and coordinate descent, producing soft-thresholding that zeroes small coefficients.

Study Card: Derivation of Ridge and Lasso Regularization

Direct Answer

Ridge (L2L_2) and Lasso (L1L_1) regularization add convex norm penalties to the Ordinary Least Squares (OLS) objective (typically excluding the intercept β0\beta_0 by centering XX and yy):

1. Ridge Regression (Closed-Form Derivation): Minimizing the squared-error loss plus squared L2L_2 penalty for λ>0\lambda > 0:

JRidge(β)=∥y−Xβ∥22+λ∥β∥22=(y−Xβ)⊤(y−Xβ)+λβ⊤βJ_{\text{Ridge}}(\beta) = \|y - X\beta\|_2^2 + \lambda \|\beta\|_2^2 = (y - X\beta)^\top (y - X\beta) + \lambda \beta^\top \beta

Taking the gradient with respect to β\beta and setting it to zero gives:

∇βJRidge(β)=−2X⊤(y−Xβ)+2λβ=0  ⟹  (X⊤X+λI)β=X⊤y\nabla_\beta J_{\text{Ridge}}(\beta) = -2X^\top (y - X\beta) + 2\lambda \beta = 0 \implies (X^\top X + \lambda I)\beta = X^\top y β^Ridge=(X⊤X+λI)−1X⊤y\hat{\beta}_{\text{Ridge}} = (X^\top X + \lambda I)^{-1} X^\top y

Because X⊤XX^\top X is positive semidefinite and λ>0\lambda > 0, X⊤X+λIX^\top X + \lambda I is strictly positive definite and always invertible—even when p>np > n or features are collinear.

2. Lasso Regression (Subgradient & Soft-Thresholding Derivation): Lasso minimizes (using scikit-learn’s 1/(2n)1/(2n) scaling convention):

JLasso(β)=12n∥y−Xβ∥22+λ∥β∥1J_{\text{Lasso}}(\beta) = \frac{1}{2n}\|y - X\beta\|_2^2 + \lambda \|\beta\|_1

Because ∣βj∣|\beta_j| is non-differentiable at βj=0\beta_j = 0, we use the subdifferential ∂∣βj∣={sign(βj)}\partial |\beta_j| = \{\text{sign}(\beta_j)\} for βj≠0\beta_j \ne 0 and [−1,1][-1, 1] for βj=0\beta_j = 0. Minimizing over coordinate βj\beta_j with partial residual r−j=y−∑k≠jX⋅kβkr_{-j} = y - \sum_{k \ne j} X_{\cdot k}\beta_k gives the KKT optimality condition 0∈−1nX⋅j⊤r−j+1n∥X⋅j∥22βj+λ ∂∣βj∣0 \in -\frac{1}{n}X_{\cdot j}^\top r_{-j} + \frac{1}{n}\|X_{\cdot j}\|_2^2 \beta_j + \lambda\,\partial|\beta_j|, yielding the closed-form coordinate update via the soft-thresholding operator S(z,γ)=sign(z)max⁡(∣z∣−γ,0)S(z, \gamma) = \text{sign}(z)\max(|z| - \gamma, 0):

β^j=S(X⋅j⊤r−j,  nλ)∥X⋅j∥22\hat{\beta}_j = \frac{S\big(X_{\cdot j}^\top r_{-j},\; n\lambda\big)}{\|X_{\cdot j}\|_2^2}

Whenever ∣X⋅j⊤r−j∣≤nλ|X_{\cdot j}^\top r_{-j}| \le n\lambda, the numerator vanishes and β^j=0\hat{\beta}_j = 0 identically, inducing feature sparsity.

Key Terms

  • Ordinary Least Squares (OLS): Linear regression minimizing ∥y−Xβ∥22\|y - X\beta\|_2^2 with closed form (X⊤X)−1X⊤y(X^\top X)^{-1} X^\top y when X⊤XX^\top X is nonsingular.
  • L1L_1 Norm: ∥β∥1=∑j∣βj∣\|\beta\|_1 = \sum_j |\beta_j|, whose diamond-shaped constraint boundary has corners along coordinate axes that promote exact zeros.
  • Squared L2L_2 Norm: ∥β∥22=∑jβj2\|\beta\|_2^2 = \sum_j \beta_j^2, a smooth strictly convex penalty (the L2L_2 norm itself is ∑jβj2\sqrt{\sum_j \beta_j^2}).
  • Subgradient: A generalization of the gradient to convex non-differentiable functions, allowing optimality conditions at kinks such as ∣βj∣=0|\beta_j| = 0.
  • Soft-Thresholding: Shrinking correlations toward zero by an additive margin and clamping values below threshold nλn\lambda strictly to zero.

Example

Suppose features are orthonormal (1nX⊤X=I\frac{1}{n} X^\top X = I) and the unpenalized OLS coefficient for feature jj is β^jOLS=1nX⋅j⊤y=0.08\hat{\beta}_j^{\text{OLS}} = \frac{1}{n} X_{\cdot j}^\top y = 0.08, with regularization λ=0.1\lambda = 0.1:

  • Ridge shrinks proportionally: β^jRidge=0.081+0.1≈0.0727\hat{\beta}_j^{\text{Ridge}} = \frac{0.08}{1 + 0.1} \approx 0.0727 (shrunk toward zero, never exact zero).
  • Lasso applies soft-thresholding: S(0.08,0.1)=sign(0.08)max⁡(0.08−0.1,0)=0S(0.08, 0.1) = \text{sign}(0.08)\max(0.08 - 0.1, 0) = 0. Because ∣0.08∣≤0.1|0.08| \le 0.1, Lasso drops feature jj completely. Geometrically, minimizing elliptical MSE contours subject to an L1L_1 diamond ∥β∥1≤t\|\beta\|_1 \le t hits vertices on the coordinate axes far more readily than a smooth L2L_2 circle ∥β∥22≤t\|\beta\|_2^2 \le t.

Code Implementation

import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import Lasso, Ridge
from sklearn.metrics import mean_squared_error

# Generate sparse synthetic data (zero-intercept formulation to match matrix derivation)
np.random.seed(42)
n_samples, n_features = 120, 40
X = np.random.randn(n_samples, n_features)
true_coef = np.zeros(n_features)
true_coef[:5] = [2.5, -1.8, 1.2, -0.9, 1.5]
y = X @ true_coef + 0.2 * np.random.randn(n_samples)

X_train, X_test = X[:80], X[80:]
y_train, y_test = y[:80], y[80:]

# Ridge Closed-Form Solution: (X^T X + alpha I)^-1 X^T y
def ridge_closed_form(X_mat, y_vec, alpha):
    identity = np.eye(X_mat.shape[1])
    return np.linalg.solve(X_mat.T @ X_mat + alpha * identity, X_mat.T @ y_vec)

# Lasso Coordinate Descent matching sklearn's 1/(2n)||y - Xb||_2^2 + alpha||b||_1 objective
def soft_threshold(z, gamma):
    return np.sign(z) * np.maximum(np.abs(z) - gamma, 0.0)

def lasso_coordinate_descent(X_mat, y_vec, alpha, n_iters=500):
    n, p = X_mat.shape
    beta = np.zeros(p)
    col_norms_sq = np.sum(X_mat ** 2, axis=0)
    residual = y_vec.copy()
    for _ in range(n_iters):
        for j in range(p):
            r_j = residual + X_mat[:, j] * beta[j]
            rho_j = X_mat[:, j] @ r_j
            new_beta_j = soft_threshold(rho_j, n * alpha) / col_norms_sq[j]
            residual = r_j - X_mat[:, j] * new_beta_j
            beta[j] = new_beta_j
    return beta

alpha_ridge = 1.0
alpha_lasso = 0.1

ridge_sklearn = Ridge(alpha=alpha_ridge, fit_intercept=False).fit(X_train, y_train)
lasso_sklearn = Lasso(alpha=alpha_lasso, fit_intercept=False, max_iter=10000).fit(X_train, y_train)

ridge_coef = ridge_closed_form(X_train, y_train, alpha_ridge)
lasso_coef = lasso_coordinate_descent(X_train, y_train, alpha_lasso)

print("Max |Ridge derived - sklearn|:", np.max(np.abs(ridge_coef - ridge_sklearn.coef_)))
print("Max |Lasso derived - sklearn|:", np.max(np.abs(lasso_coef - lasso_sklearn.coef_)))
print(f"Ridge Test MSE: {mean_squared_error(y_test, X_test @ ridge_coef):.4f}")
print(f"Lasso Test MSE: {mean_squared_error(y_test, X_test @ lasso_coef):.4f}")
print(f"Lasso non-zero coefficients: {np.sum(lasso_coef != 0)} / {n_features}")

plt.figure(figsize=(12, 5))
plt.subplot(1, 2, 1)
plt.plot(ridge_sklearn.coef_, 'o', label='Ridge (sklearn)')
plt.plot(ridge_coef, 'x', label='Ridge (Derived)')
plt.plot(true_coef, '*', label='True Coefficients')
plt.title("Ridge Coefficients")
plt.legend()

plt.subplot(1, 2, 2)
plt.plot(lasso_sklearn.coef_, 'o', label='Lasso (sklearn)')
plt.plot(lasso_coef, 'x', label='Lasso (Derived CD)')
plt.plot(true_coef, '*', label='True Coefficients')
plt.title("Lasso Coefficients")
plt.legend()
plt.tight_layout()
plt.show()
  • Lagrangian Duality (Constrained vs. Penalized Form): Minimizing ∥y−Xβ∥22+λ∥β∥qq\|y - X\beta\|_2^2 + \lambda \|\beta\|_q^q is equivalent via KKT multipliers to minimizing ∥y−Xβ∥22\|y - X\beta\|_2^2 subject to ∥β∥qq≤t\|\beta\|_q^q \le t, explaining the geometric circle (L2L_2) vs. diamond (L1L_1) intersection intuition.
  • Bayesian MAP Interpretation: Ridge corresponds to Maximum A Posteriori (MAP) estimation with an isotropic Gaussian prior βj∼N(0,τ2)\beta_j \sim \mathcal{N}(0, \tau^2), whereas Lasso corresponds to a zero-mean Laplace (double-exponential) prior βj∼Laplace(0,b)\beta_j \sim \text{Laplace}(0, b).
  • Multicollinearity & Elastic Net: When features are strongly correlated, Ridge splits weights evenly across correlated features while Lasso tends to pick one arbitrarily; Elastic Net combines λ1∥β∥1+λ2∥β∥22\lambda_1 \|\beta\|_1 + \lambda_2 \|\beta\|_2^2 to preserve sparsity and grouping stability.
  • Feature Standardization: Because regularization penalizes coefficient magnitudes directly, input features must be standardized to comparable scales before fitting Ridge or Lasso.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.