Mean-centering predictors in an OLS model with an interaction term
Role: Data Scientist
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `centering_with_interaction(df)`, where `df` is a `pd.DataFrame` with float columns `x1`, `x2` and `y`. Fit two OLS interaction models: (A) on raw `x1` and `x2`, and (B) on centered `x1c = x1 - x1.mean()` and `x2c = x2 - x2.mean()`. Return selected coefficients from both.
```python
def centering_with_interaction(df: pd.DataFrame) -> pd.Series:
...
```
Requirements:
- Each model has an intercept, both main effects, and the product term (`x1 * x2` in A, `x1c * x2c` in B).
- Return a `float64` `pd.Series` named `'coefs'` with index exactly `['b1_raw', 'b1_centered', 'b12_raw', 'b12_centered']`.
- `b1_*` is the coefficient on the first main effect (`x1` or `x1c`), and `b12_*` is the coefficient on the product term.
- `b12_raw` and `b12_centered` must be identical up to floating-point rounding (centering does not change the interaction coefficient).
- `b1_raw` and `b1_centered` must differ (each main effect is the slope when the other predictor is zero, and centering redefines zero).
```hint Substitute and collect
Write `x1 = x1c + m1` and `x2 = x2c + m2`, where `m1` and `m2` are the means, substitute into the raw model, and collect terms by centered column.
```
```hint Order of operations
Center `x1` and `x2` first and then form their product. Subtracting the mean from the raw product column is a different change and leaves `b1` where it was.
```
### What a Strong Answer Covers
- Fits both models with an intercept, both main effects and the product, with the centered product built from the centered columns.
- Returns the four coefficients as a `float64` Series named `'coefs'` in the exact index order.
- Shows algebraically why the interaction coefficient is unchanged and by how much `b1` shifts.
- Interprets `b1` in each model as the slope of `x1` at a specific value of `x2`.
- States what centering changes and what it leaves the same.
### Follow-up Questions
- Why does centering leave the interaction coefficient unchanged?
- What practical benefit does centering give here?
- Does centering change the fitted values, R², or the standard error of the interaction coefficient?
Overview: Fit an OLS model with a two-way interaction on raw and on mean-centered predictors, and compare the main-effect and interaction coefficients across the two fits. It tests how centering reparameterizes a regression and how to read main effects when a product term is present.