Unbiased Error Variance From OLS
Role: Data Scientist
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `residual_variance(X, y)`: fit OLS of `y` on `X` with an intercept and return the unbiased error variance `RSS / (n - p - 1)` as a Python `float`. Here `RSS = sum((y - y_hat)**2)`, `n = X.shape[0]`, and `p = X.shape[1]` (intercept excluded). The result should match statsmodels `res.mse_resid` (and `res.scale`).
Return the variance itself. Its square root is the residual standard error, which is a different quantity. The divisor is `n - p - 1`; dividing by `n` gives a different, biased number.
```hint Count the parameters
Count every coefficient the fit estimates, the intercept included. Each one costs the residuals a degree of freedom.
```
```hint Solving the fit
With plain numpy the intercept column has to be added by hand. A least-squares solver such as `np.linalg.lstsq` avoids inverting `X.T @ X`, which loses precision when predictors are correlated.
```
### Constraints & Assumptions
- `X` is a numeric array of shape `(n, p)` and `y` has length `n`.
- Test on an `X` of shape `(18, 4)`. The divisor is then 13, and your result should agree with statsmodels under `numpy.testing.assert_allclose`.
- `numpy` or `statsmodels` may be used.
### Clarifying Questions to Ask
- Can `X` arrive as a 1-D array when there is a single predictor?
- Is `X` guaranteed to have full column rank, and can it already contain a constant column?
- What should happen when `n <= p + 1`, so that no residual degrees of freedom are left?
### What a Strong Answer Covers
- Adding the intercept and fitting OLS with a numerically stable solver.
- Computing RSS from the fitted residuals, using the residual degrees of freedom as the divisor, and returning a Python `float`.
- Why the intercept counts toward the degrees of freedom, and what dividing by `n` does to the estimate.
- Input handling: a 1-D `X`, a column-vector `y`, too few rows, a rank-deficient design.
- A cross-check against statsmodels.
### Follow-up Questions
- Why divide by `n - p - 1` instead of `n`?
- How would you obtain the standard errors of the coefficients from this value?
- What changes when the design matrix is rank-deficient, for example when `X` already contains a column of ones?
- How does this estimate relate to adjusted R²?
Overview: Implement a Python function that fits ordinary least squares with an intercept and returns the unbiased estimate of the error variance. It tests degrees-of-freedom reasoning, numerically stable fitting with numpy or statsmodels, and how the variance estimate feeds into coefficient standard errors.