Compute the elastic net penalty and its gradient

Why it matters scikit-learn's ElasticNet and many sparse feature models regularise with exactly this mix.

Elastic net mixes the L1 penalty (which zeroes weights) with the L2 penalty (which shrinks them).

Write elastic_net(w, lam, alpha). Return a tuple (penalty, grad) where penalty = lam * (alpha * sum|w| + (1 - alpha) / 2 * sum w^2) and grad = lam * (alpha * sign(w) + (1 - alpha) * w). Use sign(0) = 0.

Signaturedef elastic_net(w, lam, alpha)

Example

elastic_net([1, -2], 1.0, 0.5) gives penalty 2.75 and grad [1.0, -1.5].

Understand the idea

Elastic net mixes two penalties on the weights. The L1 part, the sum of absolute values, pushes small weights to exactly zero. The L2 part, the sum of squares, shrinks all weights smoothly. alpha sets the mix and lam sets the overall strength. The 1/2 in front of the L2 sum makes its gradient simply w. Worked example: w = [2, 0, -1], lam = 0.5, alpha = 0.4. sum |w| = 3, sum w^2 = 5. Penalty = 0.5 * (0.4 * 3 + 0.6 / 2 * 5) = 0.5 * (1.2 + 1.5) = 1.35. Gradient = 0.5 * (0.4 * sign(w) + 0.6 * w) = 0.5 * ([0.4, 0, -0.4] + [1.2, 0, -0.6]) = 0.5 * [1.6, 0, -1.0] = [0.8, 0, -0.5]. Rule: penalty = lam * (alpha * sum |w| + (1 - alpha) / 2 * sum w^2); grad = lam * (alpha * sign(w) + (1 - alpha) * w), with sign(0) = 0. Dropping the 1/2 doubles the L2 strength. Elastic net is a standard regulariser for linear models with many correlated features, such as text and genomics.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: exampleelastic_net([1, -2], 1.0, 0.5)
  • Sample 2: pure lassoelastic_net([3, 0, -1], 0.1, 1.0)
  • Test 3: pure ridgeelastic_net([3, 0, -1], 0.1, 0.0)
  • Test 4: mixedelastic_net([0.5, -0.25, 2], 2.0, 0.3)