Solve OLS with an intercept using a truncated SVD in NumPy
Role: Data Scientist
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `svd_ols(X, y, rcond)` to solve OLS with an intercept from a truncated SVD. `X` is float64 of shape `(n, p)` without a column of ones, `y` is float64 of shape `(n,)`, and `rcond` is a float.
```python
import numpy as np
def svd_ols(X: np.ndarray, y: np.ndarray, rcond: float) -> np.ndarray:
...
```
Requirements:
- Prepend a column of ones to form `Xd` of shape `(n, p + 1)`.
- Take `U, s, Vt = np.linalg.svd(Xd, full_matrices=False)`.
- Set `s_inv[i] = 1 / s[i]` only where `s[i] > rcond * s.max()`, and `0` otherwise. Truncate the small values; do not divide by them.
- Compute `beta = V @ diag(s_inv) @ U.T @ y` with `V = Vt.T`, using only NumPy (no `np.linalg.pinv` or `np.linalg.lstsq`).
- Return an `np.ndarray` of shape `(p + 1,)` ordered `[intercept, b1, ..., bp]`.
```hint One direction at a time
Write `beta` as a sum over singular directions, one term per singular value, and look at what a tiny `s[i]` does to its term.
```
```hint Shapes
Work out the shapes of `U`, `s` and `Vt` for the reduced SVD, including when `n < p + 1`, and choose a multiplication order that never builds a large intermediate matrix.
```
### Constraints & Assumptions
- `X` is float64 with shape `(n, p)` and no column of ones; `y` is float64 with shape `(n,)`.
- `rcond` is a relative cutoff applied to the largest singular value.
- Only NumPy is allowed, and the pseudo-inverse and least-squares helpers are off limits.
### What a Strong Answer Covers
- Building the design matrix and the reduced SVD with correct shapes, including a wide `Xd`.
- Applying the relative cutoff without ever dividing by a dropped singular value.
- What the returned vector equals when nothing is truncated and when directions are dropped.
- How `rcond` trades bias against variance, and how the ones column interacts with truncation.
- Time and space complexity.
### Follow-up Questions
- Why truncate the small singular values instead of dividing by them?
- How does `rcond` trade off bias and variance, and how does this compare with ridge regression?
- Why might you center `X` and `y` before the SVD and recover the intercept afterward?
Overview: Implement linear regression with an intercept in NumPy from a reduced singular value decomposition, zeroing the inverse of singular values below a relative cutoff. It tests pseudo-inverse reasoning, matrix shapes, numerical stability under collinearity, and how the cutoff trades bias against variance.