Fit Lasso with coordinate descent and soft thresholding

HardRegressionPro

Lasso adds an L1 penalty that pushes useless weights to exactly zero, so it doubles as feature selection. The L1 term has no gradient at zero, so the standard solver updates one weight at a time with a closed-form soft threshold.

Write lasso_cd(X, y, alpha, n_sweeps). X has shape (n, d), y has shape (n,). Minimise (1 / (2n)) * ||y - X @ w - b||^2 + alpha * sum(|w_j|). The bias b is not penalised.

Steps:
1. Centre: Xc = X - column means, yc = y - mean(y). Start w = zeros(d).
2. Do n_sweeps full sweeps. In each sweep visit j = 0, 1, ..., d - 1 in order. Let z_j = sum(Xc[:, j]^2) / n. If z_j < 1e-12 (constant column), set w_j = 0. Otherwise compute rho_j = Xc[:, j] @ (yc - Xc @ w + Xc[:, j] * w_j) / n using the current w (updated in place during the sweep), then w_j = S(rho_j, alpha) / z_j, where S(a, t) = sign(a) * max(|a| - t, 0).
3. b = mean(y) - column_means @ w.

Return (w, b) with w a NumPy array and b a float.

Signaturedef lasso_cd(X, y, alpha, n_sweeps)

Example

if alpha is larger than every |rho_j| at the start, all weights stay 0 and b = mean(y).

Understand the idea

Lasso adds an L1 penalty, alpha x sum of |w_j|, which pushes unhelpful weights to exactly zero, so it also selects features. The L1 term has a corner at zero, so instead of gradient descent you update one weight at a time with a closed form called soft thresholding: S(a, t) shrinks a toward zero by t and snaps it to 0 if |a| <= t. Worked example: S(0.8, 0.3) = 0.5 and S(-0.2, 0.3) = 0. One centred feature: Xc = [-1, 1], yc = [-2, 2], n = 2, w = 0. z = (1 + 1) / 2 = 1. rho = Xc . (yc - Xc w + Xc w) / n = (2 + 2) / 2 = 2. With alpha = 0.5, w = S(2, 0.5) / 1 = 1.5. With alpha = 3, w = 0. Finally b = mean(y) - mean(X) . w. Rule: centre; for each sweep, for j in order, rho_j uses the current w with feature j's own contribution added back; w_j = S(rho_j, alpha) / z_j (0 if z_j < 1e-12). scikit-learn's Lasso uses coordinate descent.

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

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

  • Sample 1: small alphalasso_cd(_X, _y, 0.05, 50)
  • Sample 2: bigger alpha zeroes weightslasso_cd(_X, _y, 1.0, 50)