Show that changing the reference level of a categorical leaves OLS fitted values and R-squared unchanged
Role: Data Scientist
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `def reference_invariance(df: pd.DataFrame) -> tuple`. `df` has columns `x` (float), `g` (object, levels `'a'`, `'b'`, `'c'`), and `y` (float). Fit `y ~ x + C(g)` with the default reference and again with `'c'` as reference, and show the fit is unchanged.
Requirements:
- Fit `y ~ x + C(g)` (default reference `'a'`) and `y ~ x + C(g, Treatment(reference='c'))` using `statsmodels.formula.api.ols`.
- Return `(max_abs_fitted_diff, rsquared_default, rsquared_refc)` as plain Python `float`s (not NumPy scalars).
- `max_abs_fitted_diff` is the maximum absolute elementwise difference between the two models' fitted values (close to 0).
- The other two entries are each model's `rsquared`, which should be equal.
```hint Column spaces
Write the indicator for level `'a'` in terms of the intercept column and the other two indicators. Then compare the sets of linear combinations each design can produce.
```
```hint What "unchanged" means
The two fits run different floating-point operations. Decide what equality should mean numerically before you compare the outputs.
```
### Constraints & Assumptions
- `g` takes the levels `'a'`, `'b'` and `'c'`, so the default treatment reference is `'a'`.
- Both fits use `statsmodels.formula.api.ols`.
### What a Strong Answer Covers
- Both models fitted with the required formulas, and the three values returned in order as Python floats.
- Why a different reference level spans the same column space, so the fitted values and R-squared match.
- Which outputs change with the reference level and which stay the same.
- Why the fitted-value difference is tiny but usually not exactly zero, and how to compare with a tolerance.
### Follow-up Questions
- Which quantities do change when you switch the reference level, and how do you recover the same group means?
- How does the same column-space argument explain why dropping one dummy avoids the dummy-variable trap?
- Does the coefficient on `x`, or its standard error, change when the reference level changes? Why?
Overview: Fit the same OLS model with two different reference levels for a categorical variable and report the largest fitted-value difference and both R-squared values. It tests treatment coding, column-space reasoning, and which regression outputs depend on the choice of reference level.