Essay8 min readAll writing

Data Leakage in Medical Machine Learning: An Audit Checklist

Data leakage examples from medical machine learning, a runnable Python demo of patient-level leakage, and a nine-point audit checklist for your results.

By

Clinical MLResearch MethodsMachine LearningHealthcare AI

Search for data leakage machine learning examples and you get the same three cases in every result: a column that gives away the answer, a scaler fitted before the split, and stock prices from the future. They are correct, but they are not where medical models usually go wrong. Clinical data has patients who come back, notes written after the fact, and timestamps that hide in plain sight. As an AI researcher at the University of Alberta, I worked on clinical prediction from ECG waveforms, clinical notes and structured EHR events across multiple hospital episodes, and leakage audits and patient-disjoint evaluation were part of the evaluation. This essay is the checklist I'd hand to anyone about to report a medical ML result, with a runnable demo of the leak that matters most.

Everything below runs on synthetic data. None of it comes from a clinical dataset, and none of the numbers are research results.

What data leakage means in a clinical dataset

The scikit-learn documentation gives the cleanest definition I know: data leakage "occurs when information that would not be available at prediction time is used when building the model." The important words are prediction time. A clinical model is always meant to be used at a specific moment: at admission, six hours into a stay, at discharge. Any information the model sees that a clinician wouldn't have at that moment is a leak, even when it sits in the same table as everything else.

In medical data, leaks come in four families. Each one inflates results in a different way and needs a different check.

Leak Medical example Why the score inflates The check
Patient leakage The same patient's episodes in training and test The model recognizes the person, not the condition Count patients shared across splits; it must be zero
Temporal leakage Lab results or episodes from after the prediction time The model reads the future Compare every feature's timestamp with the prediction time
Label leakage A note or code that names the outcome One feature carries the answer Single-feature scan; search text for outcome terms
Pipeline leakage Normalization or feature selection fitted on all data Test statistics shape training Fit every step inside the training fold

The rest of this essay takes them one at a time, in the order I would check them.

Patient leakage: the same person on both sides of the split

Most clinical datasets have more rows than patients. A patient with heart failure might have four admissions, a dozen ECGs and hundreds of lab events. If you split rows at random, many patients end up in both training and test sets. The model can then learn the patient: their age, their baseline labs, the quirks of their ECG. On the test set, it recognizes them and scores well. On a new patient, it has nothing to recognize.

The scikit-learn guide on cross-validation for grouped data uses exactly this case as its example: several samples per patient, with the patient ID as the group, so you can test whether a model generalizes to patients it has never seen. GroupKFold, StratifiedGroupKFold and GroupShuffleSplit all keep each group on one side of the split.

Here is the effect on synthetic data. Each patient has between one and six episodes. The outcome depends mostly on a hidden per-patient risk and only weakly on one episode-level feature. Six "stable" features, like age and baseline labs, stay nearly the same across a patient's episodes but say nothing about the outcome on their own.

# leakage_audit.py: synthetic data only, no clinical records
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import GroupShuffleSplit, ShuffleSplit


def make_cohort(n_patients=600, seed=0):
    """Patients with 1-6 episodes each. The outcome depends mostly on a
    hidden per-patient risk, plus a weak signal in one episode feature."""
    rng = np.random.default_rng(seed)
    rows, y, groups = [], [], []
    for pid in range(n_patients):
        hidden_risk = rng.normal()
        stable = rng.normal(size=6)  # e.g. age, sex, baseline labs: same every episode
        for _ in range(rng.integers(1, 7)):
            signal = rng.normal()
            noise = rng.normal(size=3)
            logit = 1.5 * hidden_risk + 0.5 * signal - 0.5
            label = rng.random() < 1 / (1 + np.exp(-logit))
            rows.append(np.r_[stable + rng.normal(scale=0.05, size=6), signal, noise])
            y.append(label)
            groups.append(pid)
    return np.array(rows), np.array(y, dtype=int), np.array(groups)


def split_auc(X, y, groups, splitter, seed):
    by_patient = isinstance(splitter, GroupShuffleSplit)
    train, test = next(splitter.split(X, y, groups) if by_patient else splitter.split(X, y))
    model = RandomForestClassifier(n_estimators=200, min_samples_leaf=2, random_state=seed, n_jobs=-1)
    model.fit(X[train], y[train])
    shared = len(set(groups[train]) & set(groups[test]))
    return roc_auc_score(y[test], model.predict_proba(X[test])[:, 1]), shared


def single_feature_scan(X, y, names, threshold=0.80):
    """Flag any single column that separates the classes on its own."""
    for j, name in enumerate(names):
        auc = roc_auc_score(y, X[:, j])
        auc = max(auc, 1 - auc)
        if auc >= threshold:
            print(f"  suspicious: {name} alone has AUC {auc:.3f}")


X, y, groups = make_cohort()
print(f"{len(y)} episodes from {len(set(groups))} patients, {y.mean():.0%} positive")

for seed in range(5):
    row_auc, row_shared = split_auc(X, y, groups, ShuffleSplit(1, test_size=0.25, random_state=seed), seed)
    pat_auc, pat_shared = split_auc(X, y, groups, GroupShuffleSplit(1, test_size=0.25, random_state=seed), seed)
    print(f"seed {seed}: row split AUC {row_auc:.3f} ({row_shared} patients shared) | "
          f"patient split AUC {pat_auc:.3f} ({pat_shared} shared)")

# Target leakage: a column recorded after the prediction time,
# like a discharge code that is only written once the outcome happened.
rng = np.random.default_rng(1)
leaky = y + rng.normal(scale=0.3, size=len(y))
X_leaky = np.c_[X, leaky]
names = [f"stable_{i}" for i in range(6)] + ["signal", "noise_0", "noise_1", "noise_2", "discharge_code"]
auc, _ = split_auc(X_leaky, y, groups, GroupShuffleSplit(1, test_size=0.25, random_state=0), 0)
print(f"patient split AUC with the post-outcome column: {auc:.3f}")
print("single-feature scan:")
single_feature_scan(X_leaky, y, names)

With scikit-learn 1.9.1 and NumPy 2.4.6, it prints:

2099 episodes from 600 patients, 40% positive
seed 0: row split AUC 0.694 (321 patients shared) | patient split AUC 0.589 (0 shared)
seed 1: row split AUC 0.675 (321 patients shared) | patient split AUC 0.581 (0 shared)
seed 2: row split AUC 0.711 (322 patients shared) | patient split AUC 0.539 (0 shared)
seed 3: row split AUC 0.657 (330 patients shared) | patient split AUC 0.579 (0 shared)
seed 4: row split AUC 0.704 (322 patients shared) | patient split AUC 0.568 (0 shared)
patient split AUC with the post-outcome column: 0.984
single-feature scan:
  suspicious: discharge_code alone has AUC 0.991

The row-level split reports an AUC around 0.66 to 0.71. The patient-level split reports 0.54 to 0.59. Same data, same model, same features. The only difference is whether the test set contains people the model has already met. Over 300 of the 600 patients appear on both sides of the row split, and the random forest uses the stable features to match them. Those features carry no information about the outcome for a new patient, so the honest number is the lower one.

Notice that nothing about the row-split result looks wrong. An AUC of 0.70 looks like a plausible clinical result. That's what makes this leak dangerous: it doesn't produce a suspicious 0.99, it produces a believable number that's simply too high.

The leak that hurts most is the one that produces a believable number.

Temporal leakage: when the features come from the future

Patient-disjoint splits fix patient leakage. They don't fix time. Two temporal leaks are common in EHR data.

The first is a feature measured after the prediction time. If the model predicts at admission, then any lab drawn later in the stay is from the future, even though it belongs to the same episode and sits in the same table. Aggregates hide this well. "Maximum creatinine during the stay" looks like a harmless summary statistic, but it includes values from after the moment the prediction was supposed to be made.

The second is across episodes. When a patient has several admissions, a feature like "number of prior admissions" is fine, but "total admissions for this patient" counts the future ones too. If patients with the outcome tend to be readmitted more often, the count quietly encodes the label.

The scikit-learn guide notes that ordinary cross-validation gives over-optimistic estimates on time-dependent data and offers TimeSeriesSplit for that case. In clinical data I'd treat a time-based split as an addition to a patient split, not a replacement. A temporal cutoff alone can still put a patient's early admissions in training and later ones in test, which brings patient leakage back.

The check is mechanical: for every feature, write down the timestamp it depends on, and confirm it's at or before the prediction time. If you can't say when a feature was recorded, that's a finding in itself.

Label leakage in clinical notes and codes

Clinical text is the richest source of signal in a hospital record and the easiest place for the outcome to hide. A discharge summary describes what happened during the stay, including the outcome. A note written during the episode can mention a diagnosis that is itself the label. Billing and diagnosis codes can be assigned after discharge, so a code that looks like a feature may be a restatement of the outcome.

In the demo, the discharge_code column stands in for this. Added to an otherwise honest patient-level split, it pushes AUC from below 0.6 to 0.984. The single-feature scan catches it: no single legitimate feature in a clinical model should separate the classes almost perfectly on its own.

Text needs its own version of that scan:

  • Search for the outcome by name. Before training, look for the label's terms, abbreviations and codes in the notes you plan to use. If they appear, you need to know whether they appear before or after the prediction time.
  • Check which note types you include. A note written during the episode and a summary written at discharge carry very different risks.
  • Look at what the model attends to. If a text model's strongest tokens are outcome words, the model has learned to read the answer.

This is one reason the early vs. late fusion essay puts leakage audits before any fusion comparison. When ECG and text are fused early, a leaky text feature is mixed into the joint representation from the start, and it's harder to see which modality is doing the work.

Pipeline leakage and seed noise

The textbook leaks still apply. The scikit-learn pitfalls page puts the rule plainly: split into training and test subsets "particularly before any preprocessing steps", and it recommends a pipeline so each step is fitted only on the right subset. In clinical work, the steps to watch are normalization, imputation (filling missing labs with a mean computed over everyone), feature selection and vocabulary building for text. Each one fitted on the full dataset lets the test set shape the model.

Seed noise isn't leakage, but it causes the same mistake: a result that looks better than it is. Look at the patient-level column in the demo. Five seeds on the same data, each changing the split and the model's random state, gave AUCs from 0.539 to 0.589. A difference of 0.03 between two models is inside that spread. If you compare models on one split and one seed, you can't tell an improvement from luck. The DeLong and bootstrap essay covers how to put an interval on a comparison and how to measure seed noise directly.

The medical ML leakage audit checklist

Run this before any result leaves your machine. Each step is something a reviewer can ask to see.

  1. Name the prediction time. Write one sentence: "The model predicts outcome at moment, using data available up to moment." Everything else is checked against it.
  2. Count shared patients. Compute the overlap of patient IDs across training, validation and test. It must be zero. Use a grouped splitter, not a row splitter.
  3. Stratify within groups. If the outcome is rare, use StratifiedGroupKFold so each fold keeps a similar class balance without breaking patient boundaries.
  4. Timestamp every feature. For each feature, record when its underlying data was recorded. Drop or recompute anything recorded after the prediction time, including aggregates over the whole stay.
  5. Check across episodes. Make sure patient-level counts and histories only look backward.
  6. Scan single features. Compute each feature's AUC on its own. Investigate anything above about 0.8 before you train a full model.
  7. Search the text for the label. Look for outcome terms and codes in the notes, and check which note types and which time windows you include.
  8. Fit preprocessing inside the fold. Put scaling, imputation, feature selection and tokenization in a pipeline that is fitted on training data only.
  9. Repeat across seeds and splits. Report the spread. A gap between models that is smaller than the spread is not a finding.

A simple rule sits behind the list: if a result improves after a change you can't explain, audit for leakage before you celebrate. In my experience, an honest clinical result is often less impressive than the first number you see, and the lower number is the one worth publishing.

If you're on the product side of clinical AI, these steps translate into questions you can ask without writing code. The clinical AI product management essay has that version. My research background is in the experience section.