Derivation of Ridge and Lasso Regularization
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 () and Lasso () regularization add convex norm penalties to the Ordinary Least Squares (OLS) objective (typically excluding the intercept by centering and ):
1. Ridge Regression (Closed-Form Derivation): Minimizing the squared-error loss plus squared penalty for :
Taking the gradient with respect to and setting it to zero gives:
Because is positive semidefinite and , is strictly positive definite and always invertible—even when or features are collinear.
2. Lasso Regression (Subgradient & Soft-Thresholding Derivation): Lasso minimizes (using scikit-learn’s scaling convention):
Because is non-differentiable at , we use the subdifferential for and for . Minimizing over coordinate with partial residual gives the KKT optimality condition , yielding the closed-form coordinate update via the soft-thresholding operator :
Whenever , the numerator vanishes and identically, inducing feature sparsity.
Key Terms
- Ordinary Least Squares (OLS): Linear regression minimizing with closed form when is nonsingular.
- Norm: , whose diamond-shaped constraint boundary has corners along coordinate axes that promote exact zeros.
- Squared Norm: , a smooth strictly convex penalty (the norm itself is ).
- Subgradient: A generalization of the gradient to convex non-differentiable functions, allowing optimality conditions at kinks such as .
- Soft-Thresholding: Shrinking correlations toward zero by an additive margin and clamping values below threshold strictly to zero.
Example
Suppose features are orthonormal () and the unpenalized OLS coefficient for feature is , with regularization :
- Ridge shrinks proportionally: (shrunk toward zero, never exact zero).
- Lasso applies soft-thresholding: . Because , Lasso drops feature completely. Geometrically, minimizing elliptical MSE contours subject to an diamond hits vertices on the coordinate axes far more readily than a smooth circle .
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()
Related Concepts
- Lagrangian Duality (Constrained vs. Penalized Form): Minimizing is equivalent via KKT multipliers to minimizing subject to , explaining the geometric circle () vs. diamond () intersection intuition.
- Bayesian MAP Interpretation: Ridge corresponds to Maximum A Posteriori (MAP) estimation with an isotropic Gaussian prior , whereas Lasso corresponds to a zero-mean Laplace (double-exponential) prior .
- 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 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.