Compute simple OLS regression residuals in NumPy
Role: Data Scientist
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement `simple_ols_residuals(x, y)`, which fits `y_hat = a + b*x` by least squares on the single predictor `x` and returns the residual vector.
Requirements:
- Residuals are `y - y_hat` (not `y_hat - y`), in the same order as the input.
- Return a 1-D float `np.ndarray` of shape `(n,)`.
- `np.polyfit`, `np.linalg.lstsq`, or the closed-form formulas are all allowed.
- The result is compared with `numpy.testing.assert_allclose` on fixed 1-D float inputs.
Examples:
```python
x = np.array([0.0, 1.0, 2.0, 3.0])
y = np.array([1.0, 3.0, 5.0, 7.0]) # perfectly linear: y = 1 + 2x
simple_ols_residuals(x, y) # -> array([0., 0., 0., 0.])
x = np.array([0.0, 1.0, 2.0])
y = np.array([1.0, 2.0, 4.0]) # best line: y_hat = 5/6 + 1.5x
simple_ols_residuals(x, y) # -> array([ 0.16666667, -0.33333333, 0.16666667])
```
```hint Where the line must pass
A least-squares line fitted with an intercept always passes through the point $(\bar{x}, \bar{y})$. Once you have the slope, that fact gives you the intercept.
```
### What a Strong Answer Covers
- Fits a line with an intercept, by the closed form or a least-squares solver, and gets the slope and intercept right.
- Returns `y - y_hat` in input order as a 1-D float array of shape `(n,)`.
- Says what happens when every `x` value is the same, and when `x` and `y` have different lengths.
- Checks the output against the properties every OLS residual vector with an intercept has.
- States the time and space cost.
### Follow-up Questions
- How would you extend this to multiple predictors?
- What properties must these residuals always satisfy, and how would you turn them into tests for the function?
- Why can the closed form and `np.linalg.lstsq` return slightly different residuals, and when does that difference matter?
Overview: Write a NumPy function that fits a straight line with an intercept by least squares and returns the residuals, observed minus fitted, in input order. It tests the closed-form slope and intercept, the sign convention, degenerate inputs such as constant x, and the properties OLS residuals always satisfy.