Skip to content

← Regression from Scratch step 3 of 4

Easy Primitives

Ridge Regression

Ridge regression fits a linear model while penalizing large weights. The penalty favors smaller coefficients, but its usefulness depends on the data and regularization strength; it does not guarantee better predictions.

Your task

Implement ridge_regression(x, y, lam) for floating-point arrays:

  • x has shape (N, d), one example per row and one feature per column.
  • y has shape (N,).
  • lam is a nonnegative regularization strength.

N and d are positive. Return the fitted weight vector with shape (d,), without changing inputs. There is no separate intercept. Do not add a column of ones or center the data. Every supplied feature's coefficient is penalized, including a constant column if one is already present.

Minimize this objective, where the error term is a sum, not a mean:

sum((y - x @ w)**2) + lam * sum(w**2)

The weights satisfy the normal equations:

A = x.T @ x + lam * I
rhs = x.T @ y
A @ w = rhs

I is the d-by-d identity matrix. Solve the system with torch.linalg.solve or jnp.linalg.solve; do not form an explicit matrix inverse. In PyTorch, create I with x's dtype and device.

When is the solution unique?

For lam > 0, the added diagonal penalty makes A positive definite in exact arithmetic, even if x has dependent columns or fewer rows than columns. Floating-point computations can still be affected by conditioning.

For lam = 0, assume x has full column rank. Without that assumption, the unregularized normal equations may be singular. Positive regularization fixes that issue; zero regularization does not.

Example

For x = [[1], [2], [3]] and y = [2, 4, 6], x.T @ x is 14 and x.T @ y is 28. The single fitted weight is 28 / (14 + lam):

  • lam = 0 gives weight 2, fitting these targets exactly.
  • lam = 1 gives weight 28/15, approximately 1.866667.

Do not divide the data term by N when building this system. Using a mean squared error objective with the same numeric lam would require an N-scaled penalty in the normal equations and would produce different weights.