Stop overfitting with ridge regression

When features are correlated, plain least squares gives huge, unstable weights. Ridge adds a penalty lam * ||w||^2 that pulls the weights toward zero.

Write fit_ridge(X, y, lam) that returns (w, b). Centre X and y first so the bias is not penalised, solve (Xc.T Xc + lam I) w = Xc.T yc, then b = mean(y) - mean(X) @ w.

Signaturedef fit_ridge(X, y, lam)

Understand the idea

Ridge regression adds a penalty lam x (sum of squared weights) to least squares. The penalty pulls weights toward zero, which tames the huge, unstable weights you get when features are correlated. Like adding a spring that keeps every weight near zero unless the data really pulls it away. Centre X and y first so the intercept is not penalised, solve for w, then recover b from the means. Worked example, one feature: x = [0, 2], y = [1, 5]. Means 1 and 3, centred xc = [-1, 1], yc = [-2, 2]. xc^T xc = 2 and xc^T yc = 4. With lam = 0, w = 4 / 2 = 2. With lam = 2, w = 4 / (2 + 2) = 1, shrunk. Then b = 3 - 1 x 1 = 2. Rule: w = solve(Xc^T Xc + lam I, Xc^T yc); b = mean(y) - mean(X) . w. Ridge is a standard baseline and the same idea as weight decay in neural networks.

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

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

  • Sample 1: lam = 0 matches least squaresfit_ridge(_X, _y, 0.0)[0]
  • Sample 2: lam = 10 weightsfit_ridge(_X, _y, 10.0)[0]
  • Test 3: lam = 10 biasfit_ridge(_X, _y, 10.0)[1]