LearnCoding

Ridge regression (closed form)

EasyLinear models, Regularisation, NumPy

Problem

Return w = (XᵀX + λI)⁻¹ Xᵀy, with no separate intercept (if the caller adds a bias column, it is penalised too). Use a linear solve, not an explicit inverse.

Signature

def ridge_fit(X, y, lam: float) -> np.ndarray: ...

Examples

The visible tests, as an interactive Python session would show them: each call and the value it should give.

>>> close(ridge_fit([[1.0],[2.0],[3.0]], [2.0,4.0,6.0], 0.0), [2.0])
True

>>> close(ridge_fit([[1.0],[2.0],[3.0]], [2.0,4.0,6.0], 14.0), [1.0])
True

Solve it in your own editor; nothing on this page runs code.

Hints

Build X^TX + lambda*I and solve for w — do not invert it.

Use numpy.linalg.solve (numeric solve) rather than an explicit inverse.

No separate intercept: if the caller adds a bias column, it is penalised too.

Reference solution

import numpy as np

def ridge_fit(X, y, lam):
    X = np.asarray(X, float); y = np.asarray(y, float)
    d = X.shape[1]
    return np.linalg.solve(X.T @ X + lam * np.eye(d), X.T @ y)

What a strong solution covers

  • Uses np.linalg.solve.
  • Explains why λ > 0 makes the system well-posed with collinear features.
  • Discusses not penalising the intercept (centring), choosing λ by CV, and gradient-descent alternatives at large d.

Common mistakes

  • np.linalg.inv (numerically worse)
  • penalising the intercept unknowingly.

Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.