Show that a pooled y ~ x * g fit gives the same treatment slope as a separate per-group regression
Role: Data Scientist
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `def pooled_vs_separate_slopes(df: pd.DataFrame) -> np.ndarray`. The DataFrame `df` has columns `x` (float), `g` (object, with exactly the levels `'ctrl'` and `'trt'`) and `y` (float). Compute the `'trt'` slope of `y` on `x` in two ways and return both.
- Pooled: fit `y ~ x * g` on all rows with `'ctrl'` as the reference level. The slope is the `x` main effect plus the interaction coefficient.
- Separate: fit a simple OLS of `y` on `x` (with an intercept) using only the rows where `g == 'trt'`.
- Return a 1-D float ndarray of shape `(2,)`: `[slope_from_pooled, slope_from_separate]`.
- The two values must agree to floating-point tolerance.
For example:
```python
df = pd.DataFrame({
"x": [0.0, 1.0, 2.0, 3.0, 0.0, 1.0, 2.0, 3.0],
"g": ["ctrl"] * 4 + ["trt"] * 4,
"y": [2.0, 1.0, 3.0, 2.0, 1.0, 2.0, 4.0, 5.0],
})
pooled_vs_separate_slopes(df)
# array([1.4, 1.4])
```
On the `'trt'` rows, $\bar x = 1.5$ and $\bar y = 3$, the sum of cross-deviations is 7 and the sum of squared `x` deviations is 5, so the separate slope is ${7 / 5 = 1.4}$. The pooled route must give the same number.
```hint Fix the reference level
Make `'ctrl'` the reference level explicitly, and check how your formula library names the interaction column before you read it from the fitted parameters.
```
```hint Count the free parameters
Count how many intercepts and slopes the pooled model gives each group, and ask whether any parameter is shared between the groups.
```
### Constraints & Assumptions
- `g` has exactly two levels, `'ctrl'` and `'trt'`.
- Each group has enough distinct `x` values for its fit to be identified.
- statsmodels (for example `smf.ols("y ~ x * g", df)`) or manual design matrices are both allowed.
### What a Strong Answer Covers
- A pooled fit with `'ctrl'` as the reference and the treatment slope taken as main effect plus interaction.
- A separate fit on the `'trt'` rows that keeps its intercept.
- An argument for why the two slopes are identical, beyond the observation that they match numerically.
- A comparison that uses a floating-point tolerance, plus the right output shape and dtype.
### Follow-up Questions
- Why does the saturated interaction model reproduce the separate fit exactly?
- What changes to either model would break this equivalence?
- Do the standard errors of the `'trt'` slope also match between the two routes? If not, why not?
Overview: Write a pandas function that computes a treatment group's regression slope twice, once from a pooled model with a group interaction and once from a fit on that group alone. It tests treatment coding, reading interaction coefficients, and why a saturated interaction model matches separate per-group fits.