Ridge regression (closed form)
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])
TrueHints
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.