Implement a streaming L2-regularised SGD regressor with Welford running standardisation
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `OnlineSGDRegressor(n_features, lr=0.01, l2=0.0, eps=1e-8)`, a linear regressor trained one sample at a time. It maintains running per-feature mean and variance with Welford's algorithm and standardises each input before taking an L2-regularised SGD step on squared loss. The state starts at zero: `n_seen = 0`, `intercept_ = 0.0`, and `mean_`, `m2_` and `coef_` are zero vectors of length `n_features`.
Requirements:
- `var_` is the population variance `m2_ / n_seen` (zeros when `n_seen == 0`).
- `partial_fit(x, y)` updates the Welford statistics first, then computes `z = (x - mean_) / sqrt(var_ + eps)` and `r = z @ coef_ + intercept_ - y`, and returns the pre-step loss `0.5 * r**2` as a `float`.
- The step is `coef_ -= lr * (r * z + l2 * coef_)` and `intercept_ -= lr * r`. The intercept is not regularised.
- If any value in `x` or `y` is not finite, return `nan` and leave all state (including `n_seen`) unchanged.
- `fit_stream(X, y)` returns the per-sample losses with shape `(n,)`. `predict(X)` standardises a 2-D `X` with the current statistics and returns a 1-D array.
Example:
```python
m = OnlineSGDRegressor(1, lr=0.1, l2=0.5)
m.partial_fit([2.0], 1.0) # 0.5 (z=0) -> coef_=[0.0], intercept_=0.1
m.partial_fit([4.0], 3.0) # 4.205 (z≈1, r=-2.9) -> coef_≈[0.29], intercept_=0.39
```
```hint Guard the state
Decide where the finiteness check has to sit. Any counter increment or assignment that runs before it makes the "state unchanged" rule impossible to keep.
```
```hint The first sample
Work out `var_` right after the first sample and what `z` is for that sample. That tells you why `eps` is in the denominator and what the first step can and cannot change.
```
### Constraints & Assumptions
- `x` is a length-`n_features` vector and `y` is a scalar.
- `fit_stream` receives `X` with shape `(n, n_features)` and `y` with shape `(n,)`.
- Only NumPy is available, and the stream is too long to store, so statistics must be updated in one pass.
### What a Strong Answer Covers
- A correct Welford update (mean and `m2_` in the right order) and the population variance, with zeros before any sample.
- Standardising with the updated statistics and computing the residual and pre-step loss before the weights change.
- The L2 SGD step with the gradient taken at the old coefficients and no penalty on the intercept.
- Leaving every piece of state untouched on a non-finite input, and returning the specified shapes and types.
- The per-sample cost, and why Welford's method beats the sum-of-squares formula numerically.
### Follow-up Questions
- How would you handle concept drift in the feature statistics?
- Standardisation stats change after the weights are learned. Why is that a problem, and how would you mitigate it?
- How would you make the L2 step efficient for very sparse, high-dimensional inputs?
Overview: Implement an online linear regressor that standardises each feature with Welford running statistics and takes one L2-regularised SGD step per sample. It tests numerically stable streaming statistics, the order of updates within a step, and keeping all state unchanged when an input is not finite.