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.
def 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.