LearnCoding

Standardise features with train-only statistics

Warm-upPreprocessing, NumPy, Leakage

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]]))
True

Solve it in your own editor; nothing on this page runs code.

Hints

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, tez

What 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.

Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.