Lesson 10 of 227 min
Data leakage
Data leakage is something the model won't have when it really predicts getting into its training or its test, so the score is better than the model will ever be; ask of every column, every step and every row it learns from whether the model would have it then.
After this lesson you can find the ways test information leaks into training, including a split that ignores time.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
Score later calls
Put bank-additional-full.csv from UCI’s Bank Marketing dataset next to your notebook. Keep its date order. TimeSeriesSplit trains on earlier rows and tests on the next block. Each round gets a longer training history. Cross-validation guide
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import StratifiedKFold, cross_val_score
calls = pd.read_csv("bank-additional-full.csv", sep=";")
y = calls["y"].eq("yes")from sklearn.model_selection import TimeSeriesSplit
forward = TimeSeriesSplit(n_splits=5)
for earlier, later in forward.split(calls):
print(f"train through row {earlier[-1]:,} | test starts at {later[0]:,}")train through row 6,867 | test starts at 6,868 train through row 13,731 | test starts at 13,732 train through row 20,595 | test starts at 20,596 train through row 27,459 | test starts at 27,460 train through row 34,323 | test starts at 34,324
Keep a customer together
If you want to predict for customers the model has never seen, keep all of one customer's rows together. The bank's file has no customer IDs, so these six rows use made-up IDs. GroupKFold keeps each group on one side of a split. Cross-validation guide
from sklearn.model_selection import GroupKFold
customers = pd.Series(["A", "B", "C", "A", "B", "C"])
for train, test in GroupKFold(n_splits=3).split(customers, groups=customers):
overlap = set(customers.iloc[train]) & set(customers.iloc[test])
print("shared customers:", len(overlap))shared customers: 0 shared customers: 0 shared customers: 0
Learn the yes shares inside the folds
Target encoding replaces a category like job with a number based on how often people in it said yes. Fit the encoder in the pipeline so the outer validation labels stay out of that number. On the training rows, TargetEncoder uses its own folds to keep a row's answer out of its encoding. TargetEncoder reference
from sklearn.preprocessing import TargetEncoder
inner = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
encoder = TargetEncoder(target_type="binary", cv=inner)
model = make_pipeline(encoder, LogisticRegression())
print(cross_val_score(model, calls[["job"]], y, cv=5, scoring="roc_auc").round(3))[0.519 0.645 0.504 0.694 0.658]
Check for repeated records
A copied record can land in both training and testing. Start by counting exact copies. If you confirm they are copies, remove the extras before splitting. Keep legitimate repeated observations together when the test is meant to measure performance on new people. Leakage taxonomy
print("Repeated full records:", calls.duplicated().sum())
print("Rows after dropping exact copies:", len(calls.drop_duplicates()))Repeated full records: 12 Rows after dropping exact copies: 41176
Check what each column knows
Kapoor and Narayanan describe eight ways a score can leak. They cover evaluating on training data, shared preprocessing, feature selection, duplicate records, unavailable inputs, time splits, related rows, and a test population that differs from the intended one. For the bank, start with an explicit list of inputs available before dialing. Leakage taxonomy
numbers = ["age", "campaign", "previous"]
words = ["job", "marital", "education", "default", "housing", "loan", "contact", "poutcome"]
economy = ["emp.var.rate", "cons.price.idx", "cons.conf.idx", "euribor3m", "nr.employed"]
inputs = numbers + ["pdays"] + words + economy
print("Is call length an input?", "duration" in inputs)Is call length an input? False
Look for benchmark questions in training
A language model can see a benchmark question during training if the question was copied into its training text. This small example checks exact matches after ignoring case and extra spaces. A real overlap audit also looks for near matches and requires access to the training text. The train and test sets lesson
training = ["What is six times seven?", "How long is an hour?"]
benchmark = [" what is six times seven? ", "What is one dozen?"]
training_keys = {" ".join(text.casefold().split()) for text in training}
for question in benchmark:
if " ".join(question.casefold().split()) in training_keys:
print("Seen in training:", question.strip())Seen in training: what is six times seven?
Run on Python 3.13.3, scikit-learn 1.9.1, pandas 3.1.1. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: Training, validation and test data
Your loop printed each setting's score on the validation set, and two questions won with 0.9375. Then the winner, scored once on the test set, printed 0.965. Which number tells you how it will do on new penguins?
2 of 3
A hospital's model predicts who will be admitted. One of its columns is "days in hospital". On a test set it never saw, its score is excellent. What is wrong?
3 of 3
A shop's sales come in date order. With train_test_split(X, y, test_size=0.2) the model scores 0.80. With shuffle=False added, it scores 0.65. Which score do you trust for next month's sales?
The ideas in this lesson
- Data leakage
- Something the model won't have when it really predicts gets into its training or its test, so the score is too good to be true.
- Every step inside the folds
- A step that learns from data, like choosing columns, must learn inside each fold from its training rows, or it saw the answers it is scored on.
- Split by time
- When rows come in time and the model will predict what comes next, learn from the earlier rows and test on the later ones.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
Data leakage
Here's a question. A bank's model picks which customers to call. Add one more column, and its test score jumps.
Should the bank use that column?
Keep your guess
Hold on to your guess. On a thousand calls it never learned from, the bank's model scores zero point seven four. That's the area under the ROC curve, where a coin scores zero point five.
Add one more column, and it scores zero point eight nine.
The call's length
A model is scored on rows it never saw. Here, the new column is how long the call lasted. And long calls are yeses much more often. Under two minutes, about one in a hundred said yes. Ten minutes or more, about half.
Spot the problem. When does the bank know how long a call lasted?
Too good to be true
Only when the call ends. And by then, the bank knows the answer too. On the day it chooses who to call, there is no call yet, so there is no length. Fill in a typical length, the middle one of all the calls, and the model scores zero point seven four. That's no better than without it. The zero point eight nine measured something the bank can't use. So the answer is no: the bank shouldn't use it. It's like an exam where the answers were left in the room. But here, nobody cheated on purpose. This is called data leakage. Something the model won't have when it really predicts gets into its training, or its test.
One question
So how would you catch it?
Here are eight cards from the bank's work, and three bins to sort them into.
Ask one question about every card. When the model really predicts, would it have this?
Would the model have the call's length?
No. The page that comes with this data warns about this column. Keep that question in mind. It works on more than columns.
A leak in a step
A leak is something the model won't have when it really predicts. Can a leak hide in a step, instead of a column?
Give the same thousand calls five thousand columns of coin flips. There's nothing in them to learn. Now choose the twenty columns that best match the answers, using every row. Then cross-validate. Guess the score.
Zero point eight three.
From coins.
Why
Why? With five thousand coins, some match the answers just by luck. The choice found those lucky coins by looking at every row's answer, including the rows it was later tested on. When the model really predicts, it won't have those answers. So let the choice look only at each fold's training rows. Zero point five seven: close to a coin. A pipeline in cross-validation does this for every step that learns.
Two scalers
A scaler is the step that puts numbers on one ruler. If it learns from every row, it leaks the same way. But over forty thousand training calls, the averages it learns, like age's average, barely move. The score is the same either way. Some leaks are big and some are tiny. The rule is the same for both: every step that learns, learns inside the folds.
Rows that come in time
A leak is something the model won't have when it really predicts.
Now look at the order of the rows.
The bank's calls come in date order, from May two thousand eight to November two thousand ten. The share of yeses climbs, from five percent to fifty-two.
Add five columns about the economy: an interest rate, prices, jobs.
They change only from week to week, so they tell the model which week a call was made.
Keep a fifth of the calls aside, picked at random. Without the economy, the model scores zero point seven three.
With it, zero point seven eight.
It looks better.
Split by time
Now keep the calls in their order. Learn from the first four fifths, and test on the last fifth. Does the economy help now, or hurt?
Without the economy, zero point seven. With it, zero point six three. It hurts.
Ask the one question about the rows the model learns from. When it predicts next month, will it have other calls from next month to learn from?
No. But when the calls were shuffled, each test call had calls from the same week in training. And the economy's numbers told the model which week it was.
When rows come in time, split by time.
It happens to experts
This happens to experts too. Researchers who went looking found leaks in almost three hundred published papers, in seventeen fields. In one field, once the leaks were fixed, the new models did no better than plain logistic regression.
In code
In real code, with scikit-learn, cross-validate the model on five folds of the training set. Without the call's length, zero point seven three. With it, zero point eight nine: close to the test set's numbers.
For the coins, put the choice of columns in a pipeline with the model, and cross-validate the pipeline. Will it score near zero point eight three, or near a coin?
Near a coin: zero point five seven. And for rows in time, the split takes one more setting: shuffle equals false. It keeps the rows in their order, so the test set is the last fifth.
So put every step that learns into the pipeline, and cross-validate the pipeline.
Three ideas
So, a leak is something the model won't have when it really predicts. Every step that learns, learns inside the folds. When rows come in time, you split by time. And you ask the one question about every column, every step, and every row.
The lab
That's the end of this unit. In its lab, you use these four lessons to make a call list the bank can trust.
Would the model really have it?
A test can lie, so ask what the model will really have. Now try it on this lesson's page, and take the quiz. Sort all eight cards, and get every one right.
You use this lesson in Lab 3: A call list the bank can trust, which comes next.
Facts last checked on .
