Artificial Intelligence Fundamentals / Prepare Data for Learning

Avoid data leakage

Lesson 8 of 26. Open to read. No account needed.

When a Score Is Too Good

A team builds a model to predict which customer complaints will be escalated to a manager. It scores 100% on the test set. A week after launch it is barely better than guessing. Nothing was wrong with the algorithm: one of the features, "manager notes present", is only filled in after a complaint has been escalated. In the historical data it gave the answer away; at the moment a new complaint arrives, it is always empty.

This is data leakage: information that would not be available when the model is used found its way into training. Leakage produces scores that are too good, and nothing in the training code warns you. A suspiciously high score is the most common clue.

Two Common Forms

A feature that contains the answer. Some columns are recorded after, or because of, the outcome you want to predict: a refund issued, a follow-up call booked, a final diagnosis code. For each feature, ask: "would I know this value at the moment I need the prediction?" If not, it must go.

Preprocessing that learns from the test data. Many models work better when features are put on a common scale, which needs statistics such as each feature's average. If those statistics are calculated from all the data before splitting, a little information about the test samples is built into the training data. The effect is often small, but it breaks the rule from the split lesson: nothing about the test set may influence training. The fix is to calculate such statistics from the training set only, and to make that automatic.

Standardising Features

StandardScaler puts every feature on a comparable scale. When it is fitted, it records each feature's mean and standard deviation. When it transforms data, it subtracts that mean and divides by that standard deviation, so a value becomes "how many standard deviations above or below the average". A feature measured in thousands and one measured in fractions end up on similar scales.

The statistics come from whatever data the scaler was fitted on. Fitted on the training set, they describe the training set only, which is what you want.

Pipelines

A pipeline chains preprocessing steps and a model into one object that behaves like a model:

pipeline = make_pipeline(StandardScaler(), LogisticRegression())
pipeline.fit(X_train, y_train)          # fits the scaler, scales, then fits the model
pipeline.score(X_test, y_test)          # scales with the training statistics, then scores

When you call fit on the pipeline, the scaler is fitted on X_train only, the training data is transformed, and the model is trained on the result. When you call score or predict, the test data is transformed with the statistics already learned from training, never refitted. You cannot leak test statistics by accident, because you never handle the scaler yourself. LogisticRegression is a classification model you will meet properly in the classifier lesson; here it is simply the model at the end of the pipeline.

Before: all 400 rows are standardised together, so the scaler's averages include the test rows, and only then are the rows split into training and test sets. After: the rows are split first; inside a pipeline, the scaler is fitted on the 300 training rows only and the same averages are reused to transform the test rows.

Compare the two halves from top to bottom. In the first, the scaler is fitted on all 400 rows before the split, so the test rows are already inside its averages. In the second, the split comes first, the scaler inside the pipeline learns only from the 300 training rows, and the arrow to the test rows shows those same averages being reused. The order of the steps is the whole difference.

Exercise: Find the Leak

You will train a model with and without a leaking column, then build the leak-free pipeline and confirm where its statistics came from.

Starting state: the course environment, active in your terminal. The script generates its own data, so nothing is downloaded.

  1. Create the exercise folder. macOS and Linux:

    mkdir -p ~/ai-practice/leak-check
    cd ~/ai-practice/leak-check
    

    Windows PowerShell:

    mkdir $HOME\ai-practice\leak-check
    cd $HOME\ai-practice\leak-check
    

    Save this as leak_check.py in that folder:

    """Find a leaking feature, then fit scaling inside a Pipeline."""
    import numpy as np
    from sklearn.datasets import make_classification
    from sklearn.linear_model import LogisticRegression
    from sklearn.model_selection import train_test_split
    from sklearn.pipeline import make_pipeline
    from sklearn.preprocessing import StandardScaler
    
    X, y = make_classification(n_samples=400, n_features=5, n_informative=3, flip_y=0.1, random_state=1)
    rng = np.random.default_rng(1)
    recorded_later = y + rng.normal(0, 0.2, size=len(y))  # written down after the outcome was known
    X_leaky = np.column_stack([X, recorded_later])
    
    for name, data in [("with the leaking column", X_leaky), ("without it", X)]:
        X_train, X_test, y_train, y_test = train_test_split(data, y, random_state=1, stratify=y)
        model = LogisticRegression().fit(X_train, y_train)
        print(f"Test accuracy {name}: {model.score(X_test, y_test):.3f}")
    
    X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1, stratify=y)
    pipeline = make_pipeline(StandardScaler(), LogisticRegression())
    pipeline.fit(X_train, y_train)
    print(f"Pipeline test accuracy: {pipeline.score(X_test, y_test):.3f}")
    scaler = pipeline.named_steps["standardscaler"]
    print("Scaler fitted on", int(scaler.n_samples_seen_), "rows; feature means:", scaler.mean_.round(2))
    
  2. Predict which of the first two accuracies will be higher, then run it:

    python leak_check.py
    

    Output, which should match exactly:

    Test accuracy with the leaking column: 1.000
    Test accuracy without it: 0.900
    Pipeline test accuracy: 0.900
    Scaler fitted on 300 rows; feature means: [-0.12  0.35  0.45 -0.09  0.39]
    

How the Script Works

The data. make_classification generates 400 samples with 5 features for a two-class problem; only 3 features carry real information, and flip_y=0.1 gives a random tenth of the samples the wrong label, as real data would have mistakes. random_state=1 makes the data the same on every run.

The leaking column. np.random.default_rng(1) creates a random-number generator with a fixed seed. recorded_later is the label itself plus a little random noise: like the "manager notes" field, it is close to the answer because it was recorded after the answer was known. np.column_stack adds it as a sixth column.

The comparison. The loop splits each version of the data the same way, trains a model and prints its test accuracy, the share of test samples it labels correctly. With the leaking column, the model scores 1.000: it simply reads the answer. Without it, 0.900 is the honest estimate. When this model is used, recorded_later would not exist yet, so 1.000 was never achievable.

The pipeline. make_pipeline names each step after its class in lower case, so named_steps["standardscaler"] retrieves the fitted scaler. Its n_samples_seen_ is 300: the training rows, a quarter of 400 having gone to the test set. Its mean_ holds the five training-set averages it will use for every later transformation. Here the pipeline's accuracy equals the unscaled model's, 0.900; scaling does not always change a score, but it matters for models that are sensitive to feature scales, as the classifier lesson shows.

Success: the leaking column produces a perfect score that disappears when it is removed, and the scaler reports 300 rows. You can say why 0.900, not 1.000, is the score to report.

If something differs:

What you seeLikely causeNext step
Accuracies other than 1.000 and 0.900A random_state or the seed in default_rng was changedRestore the values shown
Scaler fitted on 400 rowsThe scaler was fitted before splittingFit only the pipeline, after the split, as shown
KeyError: 'standardscaler'The step name was typed differentlyUse the lowercase class name, standardscaler
ModuleNotFoundErrorThe course environment is not activeActivate it and rerun
  1. Clean up. macOS and Linux:

    cd ~/ai-practice
    ls
    rm -rf leak-check
    ls
    

    Windows PowerShell:

    cd $HOME\ai-practice
    ls
    Remove-Item -Recurse leak-check
    ls
    

    Check that the first ls shows leak-check before removing it. Do the independent task first.

Independent task: a colleague's script contains this excerpt, which standardises the data before splitting it. Rewrite it as a short complete script that uses the same data and a pipeline, and print the number of rows the scaler was fitted on.

scaler = StandardScaler().fit(X)
X_scaled = scaler.transform(X)
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, random_state=1, stratify=y)
model = LogisticRegression().fit(X_train, y_train)

Check Your Understanding

Which of these workflows leak, and why?

  1. A model predicting whether a customer will cancel uses the feature "account closed date".
  2. A scaler is fitted on the training set, and the same fitted scaler is then used to transform the test set.
  3. Missing values are replaced with the average of the whole column, and the data is split afterwards.

Answer and Reasoning

Independent task

from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = make_classification(n_samples=400, n_features=5, n_informative=3, flip_y=0.1, random_state=1)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1, stratify=y)
model = make_pipeline(StandardScaler(), LogisticRegression())
model.fit(X_train, y_train)
print(f"Test accuracy: {model.score(X_test, y_test):.3f}")
print(int(model.named_steps["standardscaler"].n_samples_seen_))

The split now comes first, and the scaler lives inside the pipeline, so it is fitted on the 300 training rows; the last line prints 300. In the colleague's version the scaler saw all 400 rows. The test score may not change noticeably on this data, but the workflow is only correct in the second form.

Understanding check

  1. Leaks. A closing date exists only for customers who have already cancelled, so the feature contains the answer and is unavailable when a prediction is needed.
  2. Does not leak. The statistics come from the training set only; reusing them on the test set is exactly what a pipeline does.
  3. Leaks, slightly. The averages include the test rows. Split first, then calculate any filling values from the training set, ideally inside a pipeline.

References

Study this course with an account

Course access adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 199 plus 18% GST. 90 days of online access. No auto-renewal.

See course access

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy