Overall F-Test for OLS From Scratch
Role: Data Scientist
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `def f_statistic_from_scratch(X: np.ndarray, y: np.ndarray) -> tuple[float, float]`: fit OLS of `y` on `X` with an intercept and return the overall F-statistic and p-value for the null that all `p` slopes are zero. Compute by hand: do not read `res.fvalue` or `res.f_pvalue`.
Requirements:
- `TSS = sum((y - y.mean())**2)`, `RSS = sum((y - y_hat)**2)`.
- `F = ((TSS - RSS) / p) / (RSS / (n - p - 1))` with `p = X.shape[1]` (intercept excluded), `n = X.shape[0]`.
- p-value: `scipy.stats.f.sf(F, dfn=p, dfd=n - p - 1)`.
- Return `(f_statistic, f_pvalue)` as plain floats.
Example:
```python
import numpy as np
X = np.array([[1.0], [2.0], [3.0], [4.0], [5.0]])
y = np.array([2.0, 4.0, 5.0, 4.0, 5.0])
f_statistic_from_scratch(X, y)
# -> approximately (4.5, 0.1240)
```
The least squares line is y = 2.2 + 0.6x, so TSS = 6 and RSS = 2.4. With p = 1 and n = 5, F = (3.6 / 1) / (2.4 / 3) = 4.5 on 1 and 3 degrees of freedom.
```hint Getting the fitted values
Add the intercept as a column of ones and use a least squares solver. You do not need to invert anything.
```
```hint Matching statsmodels
Think about which baseline model the overall F-test compares against, and what that means for the total sum of squares.
```
### Constraints & Assumptions
- `X` is a 2-D array of shape (n, p) with no constant column, and `y` has length n.
- The grader uses inputs with `X.shape == (32, 4)` and `y.shape == (32,)`, and checks both returned values with `assert_allclose` against `res.fvalue` and `res.f_pvalue` from a statsmodels fit with an intercept.
### What a Strong Answer Covers
- A least squares fit with an intercept column, and both sums of squares computed correctly, with TSS centered on the mean of `y`.
- The numerator and denominator degrees of freedom and the upper-tail p-value.
- Why the hand computation reproduces statsmodels, tied to the intercept-only baseline.
- Numerical and edge-case handling: solving without an explicit inverse, collinear columns, and a zero residual sum of squares.
### Follow-up Questions
- How does this F-statistic relate to `R²`?
- Why use the mean-centered TSS instead of `sum(y**2)`?
- How would you change the computation to test only a subset of the slopes?
Overview: Compute the overall F-statistic and p-value for an OLS regression by hand with NumPy and SciPy, without reading them from statsmodels. It tests the total and residual sums of squares, the degrees of freedom, the upper-tail p-value, and why the baseline is the intercept-only model.