Standardise features with train-only statistics
Problem
train and test are 2-D lists (rows × columns). Compute the per-column mean and population standard deviation (ddof=0) from train only, and return (train_z, test_z) as numpy arrays. Columns whose train std is 0 become all zeros in both outputs.
Signature
def standardize(train: list[list[float]], test: list[list[float]]) -> tuple[np.ndarray, np.ndarray]: ...Examples
The visible tests, as an interactive Python session would show them: each call and the value it should give.
>>> close(standardize([[1.0],[3.0]], [[2.0],[5.0]]), ([[-1.0],[1.0]], [[0.0],[3.0]]))
True
>>> close(standardize([[1.0,7.0],[3.0,7.0]], [[3.0,9.0]]), ([[-1.0,0.0],[1.0,0.0]], [[1.0,0.0]]))
TrueHints
Compute per-column mean and population std from train only.
Vectorise with numpy axis=0; standardise train and test with the same fitted stats.
Guard zero-variance columns: the output must be zeros, not NaNs.
Reference solution
import numpy as np
def standardize(train, test):
tr = np.asarray(train, dtype=float)
te = np.asarray(test, dtype=float)
mu = tr.mean(axis=0)
sd = tr.std(axis=0)
safe = np.where(sd == 0, 1.0, sd)
trz = (tr - mu) / safe
tez = (te - mu) / safe
trz[:, sd == 0] = 0.0
tez[:, sd == 0] = 0.0
return trz, tezWhat a strong solution covers
- Vectorised numpy with axis handling.
- Uses train statistics for test.
- Guards against zero variance without NaNs.
- Mentions persisting the fitted parameters for serving.
Common mistakes
- fitting on train + test
- dividing by zero and producing NaN or inf.