---
title: Ridge regression (closed form)
url: https://gurkanozkan.ai/learn/coding/mle-ridge-regression-closed-form-12/
markdown: https://gurkanozkan.ai/learn/coding/mle-ridge-regression-closed-form-12.md
kind: coding
difficulty: Easy
topics:
  - Linear models
  - Regularisation
  - NumPy
json: https://gurkanozkan.ai/api/learn/coding/mle-ridge-regression-closed-form-12.json
robots: noindex
---

# Ridge regression (closed form)

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

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

## Examples

Each call and the value it should give.

```python
>>> 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
```

## Hints

1. Build X^TX + lambda*I and solve for w — do not invert it.
2. Use numpy.linalg.solve (numeric solve) rather than an explicit inverse.
3. No separate intercept: if the caller adds a bias column, it is penalised too.

## Reference solution

```python
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.*
