Mean-Centered OLS Fit: Return the Slope and Intercept of a Centered Simple Regression
Quick Overview
Implement a simple OLS fit in NumPy on a mean-centered predictor and return the slope and intercept as plain floats. It tests whether you can explain why centering leaves the slope unchanged and moves the intercept to the mean of the response.
Mean-Centered OLS Fit: Return the Slope and Intercept of a Centered Simple Regression
Role: Data Scientist
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement `centered_fit(x, y)` that centers the predictor (`x_c = x - x.mean()`), fits OLS of `y` on `x_c` with an intercept, and returns `(slope, intercept)`.
Requirements:
- Return `(slope, intercept)` as plain Python `float` values, slope first.
- The slope must equal the uncentered OLS slope of `y` on `x`.
- The intercept must equal `y.mean()`.
Example:
```python
x = np.array([10., 12., 14., 16.]) # non-zero mean
y = np.array([1., 2., 2., 4.])
slope, intercept = centered_fit(x, y)
# slope == uncentered OLS slope of y on x == 0.45
# intercept == y.mean() == 2.25
```
```hint Look at the deviations
Write the OLS slope as a ratio of sums of deviations from the mean, then ask what subtracting a constant from every `x` does to each deviation.
```
### Constraints & Assumptions
- Inputs are 1-D float arrays of shape `(n,)`.
- `x` has a clearly non-zero mean, so centering actually moves it.
- Results are checked with `numpy.testing.assert_allclose`.
### What a Strong Answer Covers
- A working fit with an explicit intercept that returns plain floats in the order slope, intercept.
- An argument for why the centered slope matches the uncentered slope.
- An argument for why the centered intercept equals `y.mean()`.
- Time and space cost, and what happens when `x` is constant.
### Follow-up Questions
- Why does centering leave the slope unchanged but fix the intercept at `y.mean()`?
- What happens if you also center `y`?
- How do you recover the intercept of the uncentered model from the centered fit?
- Why can centering make the least-squares solve better conditioned when `x` has a large mean?
Overview: Implement a simple OLS fit in NumPy on a mean-centered predictor and return the slope and intercept as plain floats. It tests whether you can explain why centering leaves the slope unchanged and moves the intercept to the mean of the response.