Fit ridge regression with cyclic coordinate descent

Why it matters Coordinate descent is how popular solvers fit ridge, lasso and elastic net on large tabular data, and interviewers like it because each step is a one-line closed form.

Ridge has a closed form, but coordinate descent updates one weight at a time and scales to wide, sparse data. It is also the warm-up for lasso and elastic net.

Write ridge_cd(X, y, lam, n_sweeps). Minimise 0.5 * ||y - X w||^2 + 0.5 * lam * ||w||^2 with no intercept. Start from w = 0. One sweep visits j = 0 .. d - 1 in order and sets w_j to its exact minimiser with the other weights fixed: w_j = X_j . r_j / (X_j . X_j + lam), where r_j = y - X w + X_j w_j is the residual without feature j. Keep the residual up to date after every coordinate. Return w after n_sweeps sweeps as a float array.

Signaturedef ridge_cd(X, y, lam, n_sweeps)

Example

X [[1, 0], [0, 1], [1, 1]], y [1, 2, 3], lam 1, n_sweeps 1 gives [1.333333, 1.222222].

Understand the idea

Coordinate descent solves a big problem by fixing all weights except one, solving for that one exactly, and moving on, like tuning a guitar one string at a time and going round again.

For ridge, the best value of a single weight w_j has a simple formula. Take the residual without feature j, r_j = y - (prediction from all other features). Then w_j = X_j . r_j / (X_j . X_j + lam). The lam in the denominator is the shrinkage.

Worked example: X = [[1, 0], [0, 1], [1, 1]], y = [1, 2, 3], lam = 1, w starts at 0. For j = 0: X_0 = [1, 0, 1], r_0 = y, so w_0 = (1 + 3) / (2 + 1) = 1.333. The residual becomes [-0.333, 2, 1.667]. For j = 1: X_1 = [0, 1, 1], so w_1 = (2 + 1.667) / (2 + 1) = 1.222.

Rule: w_j = X_j . (r + X_j w_j) / (||X_j||^2 + lam), keeping r = y - X w updated.

The same loop with a soft threshold gives lasso, which is how many linear model libraries train.

Shapes and data flow

X (n, d), y (n,), r (n,), w (d,)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

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

  • Sample 1: exampleridge_cd([[1, 0], [0, 1], [1, 1]], [1, 2, 3], 1.0, 1)
  • Sample 2: converged vs closed formridge_cd(_X, _y, 0.5, 200)
  • Test 3: three sweepsridge_cd([[1, 2], [2, 1], [3, 3], [0, 1]], [3, 3, 7, 1], 2.0, 3)
  • Test 4: orthogonal lam 0ridge_cd([[1, 0], [0, 2]], [4, 6], 0.0, 1)