Gradient LabStart the lesson

Lessons › Chapter 5: Generalization

Data leakage

One feature, “was given treatment X”, is only known after a doctor diagnosed the disease. The model learned a shortcut, not medicine. That is data leakage.

Watch it move. This lesson is interactive on Gradient Lab: every step is an animated scene you can replay.

Start the interactive lesson

Step by step

Story

Too good to be true

A new model scores 99.8% on its very first day. Maya is immediately suspicious.

Problem

A suspiciously perfect score

The model scores 99% on the test set on its very first try. That should make you suspicious, not happy. Real problems are rarely that easy.

Key idea

A clue that gives the answer away

One feature, “was given treatment X”, is only known after a doctor diagnosed the disease. The model learned a shortcut, not medicine. That is data leakage.

Build

Test rows sneaking into training

Leaks also happen when copies of test examples end up in the training data, for example duplicated rows, or scaling computed on the full dataset before splitting. The test stops being a fair exam.

Insight

The fix: only use what you’d really know

Remove anything you wouldn’t have at the moment of prediction, and split the data before any processing. The honest score drops to 84%, and real-world results now match it.

Real life

In real life: the hospital shortcut

Medical models can look brilliant in testing because of hidden shortcuts, like which hospital or which scanner an image came from, or whether a test was ordered. In a new hospital those shortcuts vanish, and so does the accuracy.

Quick check: Your model scores 99.9% on its first try. What should you check first?

Near-perfect first results are a classic sign of leakage.

Pseudocode

# leak: information about the answer sneaks into the features
features = [age, symptoms, "was given treatment X"]   # ← leak!
model.learn(features, has_disease)
score on test = 99%          # suspiciously perfect
in the real clinic: much worse

# fix: only use what you would really know at prediction time
features = [age, symptoms]

Key terms

data leakage
When information about the answer sneaks into training, making scores look better than reality.