One-Pass OLS From Sufficient Statistics
Role: Data Scientist
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `def ols_from_running_sums(n, sum_x, sum_y, sum_xy, sum_xx)`, which recovers a simple OLS line from the count and four running sums only. Return `(slope, intercept)` as a `tuple[float, float]` of plain Python floats, slope first.
Requirements:
- `slope = (n*sum_xy - sum_x*sum_y) / (n*sum_xx - sum_x**2)`
- `intercept = (sum_y - slope*sum_x) / n`
- Use only the five scalar arguments. Raw data is never provided.
Example:
```python
# x = [1, 2, 3], y = [2, 4, 6]
# n=3, sum_x=6, sum_y=12, sum_xy=28, sum_xx=14
ols_from_running_sums(3, 6.0, 12.0, 28.0, 14.0)
# -> (2.0, 0.0)
```
```hint Where the formulas come from
Start from the mean-centered slope (covariance over variance) and replace each mean with a sum divided by `n`. Doing that once shows why five numbers are enough.
```
```hint Return types
The caller may pass ints or numpy scalars. Make sure the tuple you return holds plain Python floats.
```
### Constraints & Assumptions
- Only the five scalar arguments are available. The raw x and y values are never passed in.
- The denominator `n*sum_xx - sum_x**2` is guaranteed nonzero.
- The output is checked with `numpy.testing.assert_allclose` against a two-pass, mean-centered OLS fit on the original data.
### What a Strong Answer Covers
- A correct slope and intercept from the given formulas, returned as plain floats with the slope first.
- Why the count and four sums are sufficient statistics for simple OLS, and how the raw-sum formulas relate to the mean-centered covariance over variance.
- Why the result matches a two-pass fit only up to floating-point rounding.
- When the one-pass form loses precision, for example when x has a large mean relative to its spread.
### Follow-up Questions
- Why can the one-pass formula be numerically unstable, and how would you improve it?
- How would you extend this to multiple predictors?
- Which extra running sum would you need to report $R^2$ for the fit, and how would you compute it from the sums?
Overview: Implement simple linear regression from five running sums: the count, the sums of x and y, the sum of xy and the sum of x squared. It tests whether you understand sufficient statistics for OLS, how the raw-sum formulas relate to covariance over variance, and why the one-pass form can lose precision.