OLS Standard Errors via Design-Matrix Pseudo-Inverse
Role: Data Scientist
Category: Machine Learning
Difficulty: hard
Interview Round: Other
Implement `def standard_errors_via_pinv(X: np.ndarray, y: np.ndarray) -> np.ndarray` without statsmodels. Build `A` by prepending a ones column to `X` and return the OLS coefficient standard errors as a 1-D array of shape `(p+1,)` ordered `[intercept, b1, ..., bp]`.
The function must meet these requirements:
- Compute `P = np.linalg.pinv(A)` and `beta_hat = P @ y`.
- From the residuals, estimate `sigma_hat_sq = RSS / (n - p - 1)`.
- Compute `cov = sigma_hat_sq * (P @ P.T)` and return `np.sqrt(np.diag(cov))`.
- Never form or invert `A.T @ A`.
- The output must match `sm.OLS(y, sm.add_constant(X)).fit().bse` under `assert_allclose(rtol=1e-8)`.
Example:
```python
se = standard_errors_via_pinv(X, y) # X shape (30, 3), y shape (30,)
se.shape # (4,) -> [intercept, b1, b2, b3]
# matches sm.OLS(y, sm.add_constant(X)).fit().bse
```
```hint Condition numbers
Work out what happens to the condition number when you multiply a matrix by its own transpose, and compare the result with the precision of a float64.
```
```hint Covariance without the Gram matrix
For a tall matrix with full column rank, write its pseudo-inverse in terms of `A.T @ A`, multiply it by its own transpose, and simplify.
```
### Constraints & Assumptions
- The grader's `X` is fixed, full rank, of shape `(30, 3)`, with columns whose scales differ by about 9 orders of magnitude, so `cond(A.T @ A)` is about `1e18`.
- Assume `n - p - 1 > 0`. No rank-deficiency handling is needed beyond what `pinv` does.
- `statsmodels` is not allowed in the implementation.
### What a Strong Answer Covers
- Why the Gram matrix fails on this design, in terms of condition numbers and double precision.
- How the coefficients and the covariance come out of the pseudo-inverse, and the identity that makes them equal to the textbook formulas.
- The residual variance and its degrees of freedom.
- Why the result can match statsmodels at `rtol=1e-8` on such a badly conditioned matrix.
- The limits of `pinv`: the singular value cutoff and what happens if the design loses rank.
### Follow-up Questions
- Why is `P @ P.T` numerically preferable to `inv(A.T @ A)`?
- How would column scaling (standardizing `X`) change the approach?
- How would you obtain heteroskedasticity-robust (HC) standard errors instead?
Overview: Compute OLS coefficient standard errors for a badly scaled design by pseudo-inverting the design matrix in NumPy, without ever forming the Gram matrix. It tests condition-number reasoning, the identity linking the pseudo-inverse to the coefficient covariance, and matching statsmodels at a tight tolerance.