Joint F-Test on a Subset of OLS Coefficients with statsmodels
Role: Data Scientist
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `joint_f_test(X, y, indices)`. Fit OLS of `y` on `X` with an intercept and F-test the joint null that the slopes at 0-based `X` columns `indices` are all zero, with the other coefficients unrestricted. Return `(f_value, p_value, df_num, df_denom)`.
Requirements:
- The design matrix has the intercept at column 0, so `X` column `i` maps to design column `i+1`.
- Build `R` of shape `(len(indices), p+1)` with one row per restriction and a single `1.0` in that coefficient's column, and pass it to `res.f_test(R)` from statsmodels.
- `f_value` and `p_value` are `float`; `df_num` and `df_denom` are `int`.
Example call:
```python
# X shape (30, 4), fixed y, indices=[1, 3]
f_value, p_value, df_num, df_denom = joint_f_test(X, y, [1, 3])
# df_num == 2 (two restrictions), df_denom == 30 - (4 + 1)
```
```hint Two kinds of degrees of freedom
One degrees-of-freedom number counts restrictions and the other comes from the residuals of the unrestricted fit. Decide which is which before you read them off the result.
```
```hint Check the helper's defaults
Look at what `sm.add_constant` does when `X` already contains a column with no variation. Would your `R` still line up with the design?
```
### Constraints & Assumptions
- `X` has shape `(n, p)` and `y` has shape `(n,)`. The example uses `n = 30` and `p = 4`.
- `indices` is non-empty and holds distinct, valid 0-based column indices of `X`.
- The design with the intercept has full column rank and `n > p + 1`.
### What a Strong Answer Covers
- Mapping each tested `X` column to its design column and building `R` with one row per restriction, leaving the intercept and the other slopes unrestricted.
- The numerator degrees of freedom (number of restrictions) and the denominator degrees of freedom (residual degrees of freedom of the full model).
- Returning the four values with the required Python types.
- How the joint test differs from separate t-tests on the same coefficients.
- A way to sanity-check the statistic, such as comparing restricted and unrestricted residual sums of squares.
### Follow-up Questions
- How does the joint F-test relate to two separate t-tests on the same coefficients?
- How would you compute the same F statistic manually from restricted and unrestricted RSS?
- What changes if the errors are heteroscedastic?
Overview: Fit an OLS regression with an intercept in statsmodels and run a joint F-test that a chosen subset of slope coefficients are all zero. It tests building a restriction matrix, getting both degrees of freedom right, and explaining how a joint test differs from separate t-tests.