---
title: Standardise features with train-only statistics
url: https://gurkanozkan.ai/learn/coding/mle-standardise-features-with-train-only-statistics-06/
markdown: https://gurkanozkan.ai/learn/coding/mle-standardise-features-with-train-only-statistics-06.md
kind: coding
difficulty: Warm-up
topics:
  - Preprocessing
  - NumPy
  - Leakage
json: https://gurkanozkan.ai/api/learn/coding/mle-standardise-features-with-train-only-statistics-06.json
robots: noindex
---

# Standardise features with train-only statistics

`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

```python
def standardize(train: list[list[float]], test: list[list[float]]) -> tuple[np.ndarray, np.ndarray]: ...
```

## Examples

Each call and the value it should give.

```python
>>> 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
```

## Hints

1. Compute per-column mean and population std from train only.
2. Vectorise with numpy axis=0; standardise train and test with the same fitted stats.
3. Guard zero-variance columns: the output must be zeros, not NaNs.

## Reference solution

```python
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.*
