Fit OLS with an intercept by mean-centering, without a ones column
Role: Data Scientist
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `def centered_ols(X: np.ndarray, y: np.ndarray) -> np.ndarray` that fits OLS with an intercept via mean-centering, never appending a ones column. Given float64 `X` of shape `(n, p)` and `y` of shape `(n,)`, the result must match the with-intercept normal-equation fit (up to floating-point rounding).
Requirements:
- Center each column of `X` about its mean, and `y` about `mean(y)`.
- Solve the `p`-column centered system (no intercept) for the slopes `b`.
- Intercept: `b0 = mean(y) - mean(X, axis=0) @ b`.
- Return an `np.ndarray` of shape `(p+1,)` ordered `[b0, b1, ..., bp]`.
- Never construct a ones column in the solved matrix.
Example:
```python
X = np.array([[1.0], [2.0], [3.0]])
y = np.array([2.0, 4.0, 6.0])
centered_ols(X, y) # -> array([0.0, 2.0]) # [b0, b1]
```
```hint Where the intercept goes
Write out the normal equation for the intercept row on its own. What does it say about the sum of the residuals, and which point must the fitted hyperplane pass through?
```
```hint Choosing the solver
Before you pick between the normal equations and a least-squares routine, think about what forming `X.T @ X` does to the condition number.
```
### Constraints & Assumptions
- `X` is a float64 array of shape `(n, p)` and `y` is a float64 array of shape `(n,)`.
- The only matrix passed to the solver has the `p` centered columns of `X`.
- The output is compared with the augmented normal-equation fit using a floating-point tolerance (for example `np.allclose`).
### What a Strong Answer Covers
- Why centering both `X` and `y` takes the intercept out of the slope problem and gives the same slopes as the augmented fit.
- A correct implementation that solves only the `p` centered columns, recovers `b0` from the means, and returns shape `(p+1,)` in the stated order.
- The choice of solver and its numerical consequences.
- Edge cases such as a constant feature column, collinear features, very few rows, and the shape of `y`.
### Follow-up Questions
- Why does mean-centering reproduce the with-intercept fit exactly?
- Would you use `np.linalg.lstsq` or solve the normal equations directly?
- What happens when one column of `X` is constant, and how should the function report it?
- How would you extend the same trick to weighted least squares?
Overview: Implement ordinary least squares with an intercept in NumPy by mean-centering the features and target, without appending a column of ones. It tests the normal equations, why the intercept separates from the slopes, numerically stable solver choices, and edge cases such as constant or collinear columns.