Skip to content
KALANBLON
Show contents

Chapter 5 of 7 · 20 min

Prepare the data, know the limits

By the end of this chapter, you'll be able to

  • Standardise variables so that they count in a balanced way
  • Compute preparation parameters on the training set only, to avoid leaks
  • Recognise a model used outside its range of validity
  • Identify the risks of a model that makes decisions about people

Units that crush everything

We want to predict whether a plot needs irrigation, from its area (in m², from 1,000 to 5,000) and the soil's moisture (from 0.05 to 0.6). Only moisture really matters. But for nearest neighbours, a difference of 1,000 m² weighs thousands of times more than a moisture difference of 0.3: the distance only sees the area.

The remedy: standardise each variable, that is, subtract its mean and divide by its standard deviation. Every variable is then expressed in “number of standard deviations”, on a comparable scale.

import numpy as np

rng = np.random.default_rng(0)
area = rng.uniform(1000, 5000, 80)
moisture = rng.uniform(0.05, 0.6, 80)
y = (moisture < 0.3).astype(int)
X = np.column_stack([area, moisture])
train, test = np.arange(60), np.arange(60, 80)

def knn(X_train, y_train, X_test, k=5):
    predictions = []
    for x in X_test:
        distances = np.sqrt(((X_train - x) ** 2).sum(axis=1))
        predictions.append(round(y_train[np.argsort(distances)[:k]].mean()))
    return np.array(predictions)

print("raw:", (knn(X[train], y[train], X[test]) == y[test]).mean())

mean, std = X[train].mean(axis=0), X[train].std(axis=0)
Z = (X - mean) / std
print("standardised:", (knn(Z[train], y[train], Z[test]) == y[test]).mean())
raw: 0.5
standardised: 0.95
  • column_stack assembles the two variables as columns;
  • 1 = irrigation needed (moisture below 0.3);
  • round(y_train[…].mean()) makes the k neighbours vote: the mean of their 0s and 1s, rounded, gives the majority class (with an odd k, there is no tie).

Without preparation, the model answers at random (0.5); standardised, it gets only one wrong out of 20. Models based on distances or on gradient descent are sensitive to scales. Standardising is a habit to build.

The measure stays honest: nothing from the test set influenced the preparation.

Step 5 of 5
Text description of the animation
  1. We only look at the training set.
  2. We get the mean and standard deviation of each variable from it.
  3. We standardise the training set with these values.
  4. The test set is transformed with the training parameters, never its own.
  5. The measure stays honest: nothing from the test set influenced the preparation.

Note the line mean, std = X[train].mean(axis=0), X[train].std(axis=0): the parameters come from the training set only. Computing them on all the data would leak information from the test set into the model. With a lot of data the effect is small, but the principle is strict: everything the model learns, including its preparation, comes from training. Otherwise, the evaluation is no longer reliable.

The range of validity

A model only learns what its examples show it. Let's train a regression on dry seasons (250 to 450 mm of rain), then use it for a much wetter region. In the reality simulated here, the yield levels off when rain is plentiful:

import numpy as np

def real_yield(rain):
    return 1.6 * (1 - np.exp(-rain / 400))

rng = np.random.default_rng(0)
rain_train = rng.uniform(250, 450, 30)
yield_train = real_yield(rain_train) + rng.normal(0, 0.03, 30)
a, b = np.polyfit(rain_train, yield_train, 1)

for rain in (300, 400, 800, 1200):
    print(f"{rain:>5} mm: predicted {a * rain + b:.2f}, real {real_yield(rain):.2f}")
  300 mm: predicted 0.85, real 0.84
  400 mm: predicted 1.02, real 1.01
  800 mm: predicted 1.70, real 1.38
 1200 mm: predicted 2.38, real 1.52

Within its range (300 and 400 mm), the model is excellent. At 1,200 mm, it predicts a yield more than 50% too high: the line keeps rising while reality levels off. Nothing in the model flags the problem: it is up to you to know the range of validity of your data and to distrust any prediction outside it.

When the model decides for people

The same mechanisms become serious when a model is used to decide for human beings:

  • Data bias: a model for sorting job applications trained on past hires reproduces the discrimination of those hires. It does not invent the injustice: it learns it and automates it.
  • Poorly represented groups: a recognition model trained mostly on part of the population makes more mistakes for the others. Measure quality per group, not only on average.
  • Personal data: training a model on people requires respecting the law (the GDPR in Europe, and equivalent laws elsewhere): collect the minimum, inform, secure.
  • Explanations and appeal: a person affected by a decision must be able to understand what drove it and challenge it. A human must remain accountable.

Mini-lab: without standardisationPython 3.13

Output

Click “Run”: Python will load in your browser (about 10 MB the first time).

Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Your turn

Worked exercise

Worked exercise: standardise without leaks

Write a function standardise(X_train, X_test) that returns both arrays standardised with the training parameters. Check on the example below that the standardised training set has a mean of 0 and a standard deviation of 1 per column, and display the standardised test set.

X_train = np.array([[1000, 0.2], [3000, 0.4], [5000, 0.6]])
X_test = np.array([[2000, 0.3], [6000, 0.1]])
Hint 1
X_train.mean(axis=0) and X_train.std(axis=0) give each column's mean and standard deviation.
Hint 2
Apply the same values to the test set. Its means will not be exactly 0, and that is normal.
Show the solution and common mistakes
import numpy as np

def standardise(X_train, X_test):
    mean = X_train.mean(axis=0)
    std = X_train.std(axis=0)
    return (X_train - mean) / std, (X_test - mean) / std

X_train = np.array([[1000, 0.2], [3000, 0.4], [5000, 0.6]])
X_test = np.array([[2000, 0.3], [6000, 0.1]])
Z_train, Z_test = standardise(X_train, X_test)
print(np.round(Z_train.mean(axis=0), 6) + 0, np.round(Z_train.std(axis=0), 6))
print(np.round(Z_test, 3))
[0. 0.] [1. 1.]
[[-0.612 -0.612]
 [ 1.837 -1.837]]

The second test point (6,000 m²) gives 1.837: it is larger than every training example. That is a useful signal: this point is outside the known range, and its prediction should be taken with caution. The + 0 avoids displaying a “-0.”.

Common mistakes:

  • Standardising the test set with its own mean: each set would be on a different scale, and the test set would “cheat” by looking at its own data.
  • Forgetting to standardise new data at real prediction time: the model would receive raw values, on a scale it has never seen.

Summary

  1. 1Standardising (subtract the mean, divide by the standard deviation) puts variables on a comparable scale.
  2. 2Preparation parameters are computed on the training set alone, then applied to the test set and new data.
  3. 3Outside the range covered by its examples, a model can be badly wrong without saying so.
  4. 4A model trained on unfair decisions learns and automates that unfairness.
  5. 5For decisions about people: measure per group, protect the data, explain and keep a human accountable.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.