Fit elastic net with an intercept by coordinate descent

HardRegressionPro

Why it matters Elastic net is the default sparse linear model for genomics, ads and pricing data with many correlated features.

Elastic net mixes the lasso's sparsity with ridge's stability when features are correlated.

Write elastic_net_cd(X, y, alpha, l1_ratio, n_sweeps). Minimise (1 / (2n)) * ||y - b - X w||^2 + alpha * l1_ratio * ||w||_1 + 0.5 * alpha * (1 - l1_ratio) * ||w||^2, with an unpenalised intercept b. Handle b by centering: subtract column means from X and the mean from y, run coordinate descent on the centered data from w = 0, then set b = mean(y) - mean(X) . w. For coordinate j: rho = Xc_j . r_j / n, z = Xc_j . Xc_j / n, and w_j = S(rho, alpha * l1_ratio) / (z + alpha * (1 - l1_ratio)), where S(a, t) = sign(a) * max(|a| - t, 0) and r_j is the centered residual without feature j. If z is 0 set w_j = 0. Return (w, b) with w a float array and b a float.

Signaturedef elastic_net_cd(X, y, alpha, l1_ratio, n_sweeps)

Example

X [[1, 2], [2, 1], [3, 4], [4, 3]], y [3, 3, 7, 7], alpha 0.1, l1_ratio 0.5, n_sweeps 50 gives w [0.95122, 0.95122] and b 0.243902.

Understand the idea

Elastic net adds two penalties to least squares: an L1 penalty that pushes small weights to exactly zero, and an L2 penalty that keeps correlated weights from swinging wildly. l1_ratio picks the mix: 1 is lasso, 0 is ridge.

For one coordinate the answer is still closed form. Compute rho, the correlation of feature j with the residual that ignores j. The L1 part cuts rho toward zero by alpha * l1_ratio (soft thresholding). The L2 part divides by a slightly bigger number.

Worked example: rho = 0.9, z = 1, alpha = 0.2, l1_ratio = 0.5. Threshold t = 0.1, so S(0.9, 0.1) = 0.8. The denominator is 1 + 0.2 * 0.5 = 1.1, so w_j = 0.727. If rho were 0.05, it is inside the threshold and w_j becomes exactly 0.

Rule: w_j = S(rho_j, alpha * l1_ratio) / (z_j + alpha * (1 - l1_ratio)), with b fitted by centering.

This is exactly the coordinate update used by well known linear model solvers.

Shapes and data flow

X (n, d) -> Xc (n, d), r (n,), w (d,), b scalar
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: exampleelastic_net_cd([[1, 2], [2, 1], [3, 4], [4, 3]], [3, 3, 7, 7], 0.1, 0.5, 50)
  • Sample 2: strong l1 zeroes a weightelastic_net_cd(_X, _y, 0.8, 0.9, 100)