Data leakage
Watch a perfect test score fall apart on new patients, and find the leak.
Explain it simply
A clinic wants to spot flu at check-in. It has 48 past patients, and it knows who had flu. Before anything else, it splits them: 32 rows to learn from and 16 to test on. The test rows are like a sealed exam. Nothing may look at them until the end.
Two panels of patients: 32 train rows and 16 test rows. Filled dots had flu. A third panel waits for 64 new patients.
Split the past rows once, before any step looks at them.
Show the code ▾Hide the code ▴ · Try it yourself · Python 3
import math
def mulberry32(seed): # the lesson's seeded random numbers
a = seed & 0xFFFFFFFF
def rnd():
nonlocal a
a = (a + 0x6D2B79F5) & 0xFFFFFFFF
t = ((a ^ (a >> 15)) * (1 | a)) & 0xFFFFFFFF
t = ((t + (((t ^ (t >> 7)) * (61 | t)) & 0xFFFFFFFF)) & 0xFFFFFFFF) ^ t
return ((t ^ (t >> 14)) & 0xFFFFFFFF) / 4294967296
return rnd
def gauss(rnd): # a standard normal draw (Box-Muller)
u1, u2 = 1 - rnd(), rnd()
return math.sqrt(-2 * math.log(u1)) * math.cos(2 * math.pi * u2)
def rounded(x, places):
f = 10 ** places
return math.floor(x * f + 0.5) / f
SEED = 2630
WITH_ANTIVIRAL = True # columns: with antiviral
RANK_ON_ALL_ROWS = False # rank columns on: train rows
NOISE = 100 # noise columns
rnd = mulberry32(SEED)
sets, flu = [], []
for name, n in [("train", 32), ("test", 16), ("new", 64)]:
ys = [1] * (n // 2) + [0] * (n // 2) # half of each set has flu
for q in range(n - 1, 0, -1):
s = math.floor(rnd() * (q + 1))
ys[q], ys[s] = ys[s], ys[q]
sets += [name] * n
flu += ys
temp = [rounded(37.2 + 1.0 * y + 0.7 * gauss(rnd), 1) for y in flu] # measured at check-in
antiviral = [(1 if rnd() < (0.9 if y else 0.1) else 0) if s != 'new' else 0 # filled after diagnosis:
for s, y in zip(sets, flu)] # new patients read 0
columns = {'temperature': temp}
if WITH_ANTIVIRAL:
columns['antiviral'] = antiviral
for m in range(1, NOISE + 1):
r = mulberry32(SEED * 7919 + m)
columns[f'noise {m}'] = [rounded(gauss(r), 2) for _ in flu] # pure noise
rows = lambda name: [i for i, s in enumerate(sets) if s == name]
train, test, new = rows('train'), rows('test'), rows('new')
fit_rows = train + test if RANK_ON_ALL_ROWS else train # who picks the columns
def mean(v, idx):
return sum(v[i] for i in idx) / len(idx)
def corr(v, idx):
mx, my = mean(v, idx), mean(flu, idx)
sxy = sum((v[i] - mx) * (flu[i] - my) for i in idx)
sxx = sum((v[i] - mx) ** 2 for i in idx)
syy = sum((flu[i] - my) ** 2 for i in idx)
return sxy / math.sqrt(sxx * syy)
ranked = sorted(columns, key=lambda name: -abs(corr(columns[name], fit_rows)))
top = ranked[:2]
print(top) # ['antiviral', 'temperature']
print(*(f'{abs(corr(columns[c], fit_rows)):.2f}' for c in top)) # 0.75 0.50
scale = [] # z-scores from the train rows
for c in top:
m = mean(columns[c], train)
sd = math.sqrt(sum((columns[c][i] - m) ** 2 for i in train) / len(train))
scale.append((m, sd))
z = lambda i: [(columns[c][i] - m) / sd for c, (m, sd) in zip(top, scale)]
centroid = {} # the mean train row of each class
for y in (0, 1):
pts = [z(i) for i in train if flu[i] == y]
centroid[y] = [sum(p[k] for p in pts) / len(pts) for k in (0, 1)]
def predict(i):
d = {y: sum((a - b) ** 2 for a, b in zip(z(i), centroid[y])) for y in (0, 1)}
return 1 if d[1] < d[0] else 0
def score(idx):
right = sum(predict(i) == flu[i] for i in idx)
return f'{right}/{len(idx)} = {math.floor(100 * right / len(idx) + 0.5)}%'
print('test', score(test)) # test 16/16 = 100%
print('new ', score(new)) # new 41/64 = 64%
Copy it into a file and run it. It builds the same patients from the same seed, so the printed numbers match the diagram.
Common mix-ups
MYTHA high test score proves the model works.
FIXThe antiviral column is filled after diagnosis. The test score is 100%, but new patients get 64%. Use only columns known at prediction time.
MYTHChoosing columns on all rows is harmless.
FIXColumn choice is part of training. With 1000 noise columns, test labels pick lucky columns: test 88%, new 63%.
Takeaways
- Leakage lets test labels or later facts into training, so the test score lies.
- Split first, then fit every step on train rows, column choice too.
- Use only columns that exist at prediction time.