Implement a scikit-learn compatible StandardScaler from scratch
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement `ScratchStandardScaler`, a scikit-learn compatible transformer (`BaseEstimator`, `TransformerMixin`). `fit(X, y=None)` learns per-column statistics, `transform(X)` returns `(X - mean_) / scale_`, and `inverse_transform(X)` reverses it.
The class must meet these requirements:
- `fit` sets `mean_`, `var_` (population variance, divide by n), `scale_ = sqrt(var_)`, `n_features_in_`, and returns `self`.
- Constant columns: `var_` is exactly `0.0` and `scale_` is `1.0` (no NaN or inf).
- Accept arrays or DataFrames without mutating the input. Output is a `float64` `np.ndarray`.
- A feature count mismatch at `transform` or `inverse_transform` raises `ValueError`.
- No constructor parameters (`get_params() == {}`). The class must work with `clone` and inside a `Pipeline`.
Example:
```python
X = [[5.0, 1.0], [5.0, 2.0], [5.0, 4.0]]
sc = ScratchStandardScaler().fit(X)
sc.var_[0], sc.scale_[0] # 0.0, 1.0
sc.transform([[7.0, 1.0]])[0, 0] # 2.0 (7 - 5) / 1
```
```hint Constant columns
In floating point, the mean of identical values is not always exactly that value, so the computed variance can come out as a tiny positive number. Decide how you will recognize a constant column.
```
### What a Strong Answer Covers
- Which statistics `fit` stores, why the variance divides by n, and why `transform` and `inverse_transform` reuse the stored values.
- How constant columns end up with `var_` of exactly 0 and a scale that never divides by zero.
- Input conversion that leaves arrays and DataFrames untouched and returns `float64` ndarrays, plus the feature-count check in both transform methods.
- What makes the class work with `get_params`, `clone` and `Pipeline`.
- The time and space cost of fitting and transforming.
### Follow-up Questions
- How would you add `partial_fit` so the scaler can learn from data that arrives in batches?
- How would you handle NaN values during `fit` and `transform`?
- Which models need standardized features, and which are unaffected by them?
- If you added `with_mean` and `with_std` constructor parameters, what rules must `__init__` follow so `get_params` and `clone` keep working?
Overview: Implement a standard scaler from scratch as a scikit-learn compatible transformer with fit, transform and inverse_transform. It tests population variance, handling of constant columns, input validation without mutation, and the estimator rules that make clone and Pipeline work.