OLS via Moore-Penrose Pseudo-Inverse
Role: Data Scientist
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `def pinv_coefficients(X: np.ndarray, y: np.ndarray) -> np.ndarray` that fits OLS with an intercept via the Moore-Penrose pseudo-inverse. `X` is float64 of shape `(n, p)` (no ones column), `y` is float64 of shape `(n,)`.
The function should:
- Prepend a ones column to form `Xd` of shape `(n, p+1)`.
- Return `np.linalg.pinv(Xd) @ y` without forming `Xd.T @ Xd`.
- Return an `np.ndarray` of shape `(p+1,)` ordered `[intercept, b1, ..., bp]`.
Example:
```python
X = np.array([[1.0], [2.0], [3.0]])
y = np.array([2.0, 4.0, 6.0])
pinv_coefficients(X, y) # -> array([0., 2.]) # intercept 0, slope 2
```
```hint Where the intercept lands
The position of the ones column in `Xd` decides where the intercept appears in the output. Check that your stacking call gives shape `(n, p+1)` for every `p`, including `p = 1`.
```
```hint A design with repeated columns
Picture `X` with two identical columns. Ask what `inv(Xd.T @ Xd)` does there and what the pseudo-inverse returns instead.
```
### Constraints & Assumptions
- `X` is float64 with shape `(n, p)` and contains no intercept column.
- `y` is float64 with shape `(n,)`.
- `Xd` may be rank-deficient. The pseudo-inverse handles that case.
### What a Strong Answer Covers
- Builds `Xd` with the ones column first so the output is ordered `[intercept, b1, ..., bp]`.
- Applies the pseudo-inverse to `Xd` directly and never forms the Gram matrix `Xd.T @ Xd`.
- Explains how the SVD gives the pseudo-inverse and why the result is the minimum-norm least-squares solution.
- Says what happens on a collinear design, where `inv` fails and `pinv` still returns an answer.
- States the cost and when `np.linalg.lstsq` is the better call.
### Follow-up Questions
- Why prefer `pinv` over `inv(Xd.T @ Xd) @ Xd.T @ y`?
- How would `np.linalg.lstsq` compare here?
- How does the singular value cutoff in `pinv` change the coefficients when two columns are nearly, but not exactly, collinear?
Overview: Implement ordinary least squares with an intercept in NumPy using the Moore-Penrose pseudo-inverse, without forming the Gram matrix. It tests building the design matrix, how the SVD yields a minimum-norm solution on collinear data, and when lstsq is the better choice.