Standardise features without leaking test data

Scaling features to mean 0 and standard deviation 1 helps most models. The classic mistake is computing the mean and standard deviation on all the data, which leaks the test set into training.

Write standardize(train, test) for 2D arrays. Compute each column's mean and population standard deviation on train only, and return (train_scaled, test_scaled).

If a column has standard deviation 0 in train, leave that column's scaled values as 0.

Signaturedef standardize(train, test)

Understand the idea

Standardising puts each feature on the same scale: subtract the mean and divide by the standard deviation. The key rule is to learn those numbers from the training data only, then reuse them on the test data. If test data helps choose them, information leaks and your scores look better than they really are. Like setting an exam using only the syllabus, not by peeking at students' answers. Worked example: train column [1, 3] has mean 2 and population standard deviation 1. Train becomes [-1, 1]. Test value 5 becomes (5 - 2) / 1 = 3, even though that is far outside the train range. A constant train column has standard deviation 0; set its scaled values to 0 instead of dividing by zero. Rule: mu and sigma per column from train (divide by n); scaled = (x - mu) / sigma for both sets. scikit-learn's fit on train, transform on test pattern exists exactly for this.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 2.

  • Sample 1: train scaledstandardize(_tr, _te)[0]
  • Sample 2: test uses train statsstandardize(_tr, _te)[1]