Python for AI Engineers · Part C · Lesson 22 of 26

Overfitting, cross-validation and data leakage in Python (with scikit-learn)

Overfitting and data leakage for Java and JavaScript developers: underfitting vs overfitting, bias and variance, Ridge and max_depth, k-fold cross-validation, the leaks that fake a great score (and the Pipeline fix), and eval sets leaking into LLM prompts and fine-tuning data.

⏱ 45 min3 exercises that check your codeRuns in your browser

By the end you can

  • Spot underfitting and overfitting from training and validation error, and explain bias and variance in plain words
  • Rein a model in with regularization: Ridge(alpha=...) and a tree's max_depth
  • Get a trustworthy score with k-fold cross-validation and cross_val_score
  • Find and fix data leakage: preprocessing before the split, target leakage, duplicates and time order, with a Pipeline as the default fix
  • Apply the same ideas to LLM work: keep eval questions out of prompts, fine-tuning data and training sets
1 / 6

1Underfitting and overfitting

The first lesson of this part said a model is only as good as its score on data it never trained on. This lesson is about the two ways that goes wrong. A model can be too simple to capture the pattern (underfitting), or so flexible that it memorises the training rows, noise included, and fails on new ones (overfitting).

The box makes data from a known curve, sin(3x), plus random noise, then fits polynomials of growing degree to 20 training points. Degree 1 is a straight line, degree 3 can bend twice, degree 12 can bend eleven times. A higher degree is a more flexible model, the same way a deeper tree or a bigger neural network is. Each model is scored twice: on the 20 rows it trained on, and on 200 fresh validation rows. The error is the mean squared error from the first lesson: the average of (true value minus prediction) squared, lower is better.

Try it: edit and run
import numpy as np

rng = np.random.RandomState(3)           # seeded: the same "random" data on every run


def make_data(n):
    x = rng.uniform(-1, 1, n)
    y = np.sin(3 * x) + rng.normal(0, 0.2, n)    # the real pattern, plus noise
    return x, y


x_train, y_train = make_data(20)         # a small training set
x_val, y_val = make_data(200)            # data the model never trains on


def mse(y, pred):
    return float(np.mean((y - pred) ** 2))


for degree in [1, 3, 5, 7, 9, 12]:
    coefs = np.polyfit(x_train, y_train, degree)       # fit a polynomial of this degree
    train = mse(y_train, np.polyval(coefs, x_train))
    val = mse(y_val, np.polyval(coefs, x_val))
    print(f"degree {degree:2}   train error {train:.3f}   validation error {val:.3f}")
Expected output
degree  1   train error 0.175   validation error 0.206
degree  3   train error 0.037   validation error 0.067
degree  5   train error 0.036   validation error 0.085
degree  7   train error 0.035   validation error 1.879
degree  9   train error 0.031   validation error 10.813
degree 12   train error 0.027   validation error 108.405

How to read the new lines:

  • np.random.RandomState(3) is a random generator with a fixed seed, so every run (and your browser) gets exactly the same numbers. rng.uniform(-1, 1, n) draws n decimals between -1 and 1, and rng.normal(0, 0.2, n) draws n noise values centred on 0 with a spread (standard deviation) of 0.2.
  • np.polyfit(x, y, degree) finds the polynomial of that degree that best fits the points and returns its coefficients. np.polyval(coefs, x) evaluates that polynomial at every x, giving the predictions.
  • float(...) turns the NumPy number into a plain Python float, and {train:.3f} prints it with 3 decimals.

Read the two columns together. Training error only goes down as the degree grows: a more flexible model can always hug its own training points more closely. Validation error goes down, then up. Degree 1 is wrong on both (underfitting: a line cannot follow a wave). Degree 3 is close to the noise level: the noise has a spread of 0.2, so even a perfect model scores about 0.2 squared, 0.04. From degree 7 on, the curve bends to pass close to every one of the 20 training points and swings wildly between them, so validation error explodes: 1.9, then 10.8, then 108. That gap, low train error and high validation error, is the signature of overfitting.

Tip Always print training and validation scores side by side. Train bad, validation bad: underfitting, use a richer model or better features. Train great, validation much worse: overfitting, simplify, regularize or get more data.

2Bias and variance, in plain words

Interviewers love the words bias and variance. They describe the two kinds of error from the last box:

  • Bias: the model is wrong in the same way whatever data you give it, because it is too simple. A straight line through a wave is always off. High bias means underfitting.
  • Variance: the model changes a lot when the training data changes a little, because it is flexible enough to fit the noise. High variance means overfitting.

You can see both directly: draw five different training sets from the same source, train the same kind of model on each, and ask every model for its prediction at one point, x = 0.5, where the true answer is about 1.00.

Try it: edit and run
import numpy as np

rng = np.random.RandomState(1)


def make_data(n):
    x = rng.uniform(-1, 1, n)
    y = np.sin(3 * x) + rng.normal(0, 0.2, n)
    return x, y


truth = np.sin(3 * 0.5)                      # the real answer at x = 0.5
print(f"true value at x=0.5: {truth:.2f}")

for degree in [1, 3, 15]:
    preds = []
    for _ in range(5):                       # 5 different training sets from the same source
        x, y = make_data(20)
        coefs = np.polyfit(x, y, degree)
        preds.append(float(np.polyval(coefs, 0.5)))
    shown = " ".join(f"{p:5.2f}" for p in preds)
    print(f"degree {degree:2}: {shown}   average {np.mean(preds):5.2f}   spread {np.std(preds):.2f}")
Expected output
true value at x=0.5: 1.00
degree  1:  0.53  0.75  0.51  0.47  0.48   average  0.55   spread 0.10
degree  3:  0.92  0.96  1.07  1.14  0.83   average  0.98   spread 0.11
degree 15: -0.23  3.97  0.85  1.00 -14.26   average -1.73   spread 6.42

for _ in range(5) repeats the block five times; _ is the Python name for "a loop variable I do not use". " ".join(...) glues the five formatted predictions into one string with spaces between them, and {p:5.2f} pads each one to 5 characters with 2 decimals. np.std is the standard deviation: how far the five predictions are from their average.

Degree 1 is consistently wrong: every model says about 0.5 when the truth is 1.0. That is bias. Degree 15 is right on average for some training sets and wildly off for others (3.97, -14.26): that is variance. Degree 3 is close to 1.0 and stable. The bias-variance trade-off is the search for that middle: flexible enough to follow the real pattern, not so flexible that it follows the noise.

Tip More training data lowers variance (the noise averages out) but does nothing for bias. If a model is bad on its own training data, more of the same data will not save it.

3Regularization: Ridge pulls the weights in

You do not always have to pick a simpler model by hand. Regularization keeps a flexible model but adds a penalty for large weights to the loss it minimises, so it only uses big, wild coefficients when the data really demands them.

Ridge is linear regression plus that penalty (the sum of the squared weights, called L2). Its one setting, alpha, says how strongly to punish big weights: at exactly 0 it would be plain LinearRegression, very large and it flattens everything towards zero. The box uses the same data as the first box and an even more flexible model, degree 15. PolynomialFeatures(degree=15) turns each x into 15 columns, x, x², ... x¹⁵, so a linear model on those columns is a degree 15 polynomial. StandardScaler puts those columns on the same scale first, which a penalty on weights needs to be fair.

Try it: edit and run
import numpy as np
from sklearn.linear_model import Ridge
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler

rng = np.random.RandomState(3)               # the same data as the first box


def make_data(n):
    x = rng.uniform(-1, 1, n)
    y = np.sin(3 * x) + rng.normal(0, 0.2, n)
    return x.reshape(-1, 1), y               # scikit-learn wants a table: n rows, 1 column


X_train, y_train = make_data(20)
X_val, y_val = make_data(200)


def mse(y, pred):
    return float(np.mean((y - pred) ** 2))


for alpha in [0.000001, 0.0001, 0.01, 1, 100]:
    # x -> [x, x**2, ... x**15] -> rescale each column -> linear regression with a penalty
    model = make_pipeline(PolynomialFeatures(degree=15), StandardScaler(), Ridge(alpha=alpha))
    model.fit(X_train, y_train)
    weight = float(np.abs(model[-1].coef_).max())        # the largest weight it learned
    print(f"alpha {alpha:<8} train {mse(y_train, model.predict(X_train)):.3f}"
          f"   validation {mse(y_val, model.predict(X_val)):8.3f}   largest weight {weight:5.1f}")
Expected output
alpha 1e-06    train 0.028   validation  326.260   largest weight  57.0
alpha 0.0001   train 0.030   validation   30.182   largest weight   5.0
alpha 0.01     train 0.034   validation    0.070   largest weight   1.3
alpha 1        train 0.055   validation    0.092   largest weight   0.9
alpha 100      train 0.373   validation    0.448   largest weight   0.1

The new pieces:

  • x.reshape(-1, 1) turns a flat array of 20 numbers into a table of 20 rows and 1 column. scikit-learn always wants features as a 2-D table (X, capital by convention) even when there is only one feature; -1 means "work out this size yourself".
  • make_pipeline(a, b, c) chains steps into one model, as in the scikit-learn lesson. model[-1] is its last step, and .coef_ holds the weights that step learned.
  • np.abs(...).max() is the largest weight ignoring sign. {...:8.3f} right-aligns a number in 8 characters with 3 decimals, so the columns line up.
  • {alpha:<8} left-aligns the number in 8 characters. Python prints 0.000001 as 1e-06, scientific notation for 1 times 10 to the power -6.

With an almost-zero penalty (alpha=0.000001) the model uses large weights and its validation error is 326. Plain LinearRegression, no penalty at all, is worse still: its error runs into the thousands, and the exact number even changes from one computer to the next, because fitting 15 columns that are almost copies of each other (x¹³ and x¹⁵ look nearly the same) to 20 points is numerically unstable. A little more penalty shrinks the weights; at alpha=0.01 the validation error (0.070) is almost as good as the hand-picked degree 3 model from the first box (0.067). Push alpha to 100 and the model is flattened into underfitting: both errors rise. So alpha is a dial from overfitting to underfitting, and you choose it with validation data, never with the test set.

Lasso is the sibling with an L1 penalty (the sum of absolute weights). It pushes some weights to exactly zero, which also selects features. Neural networks use the same idea under the name weight decay.

4Regularizing a tree: max_depth

Trees do not have weights to shrink. They overfit by growing: with no limit, a decision tree keeps splitting until every leaf holds a single training row, which is pure memorisation. The regularization knobs are limits on growth: max_depth (how many questions deep), min_samples_leaf (the fewest rows a leaf may hold) and max_leaf_nodes.

Same wave, now with 60 training points, and a regression tree at different depths. max_depth=None means no limit.

Try it: edit and run
import numpy as np
from sklearn.tree import DecisionTreeRegressor

rng = np.random.RandomState(0)


def make_data(n):
    x = rng.uniform(-1, 1, n)
    y = np.sin(3 * x) + rng.normal(0, 0.2, n)
    return x.reshape(-1, 1), y


X_train, y_train = make_data(60)
X_val, y_val = make_data(200)


def mse(y, pred):
    return float(np.mean((y - pred) ** 2))


for depth in [1, 2, 3, 4, 6, None]:              # None = grow until every leaf is pure
    tree = DecisionTreeRegressor(max_depth=depth, random_state=0).fit(X_train, y_train)
    print(f"max_depth {str(depth):4}  leaves {tree.get_n_leaves():2}"
          f"  train {mse(y_train, tree.predict(X_train)):.3f}  validation {mse(y_val, tree.predict(X_val)):.3f}")
Expected output
max_depth 1     leaves  2  train 0.127  validation 0.132
max_depth 2     leaves  4  train 0.079  validation 0.090
max_depth 3     leaves  8  train 0.032  validation 0.061
max_depth 4     leaves 14  train 0.019  validation 0.056
max_depth 6     leaves 36  train 0.007  validation 0.066
max_depth None  leaves 60  train 0.000  validation 0.074

.fit(...) returns the model itself, so DecisionTreeRegressor(...).fit(X, y) builds and trains in one line. random_state=0 fixes the tie-breaking inside the tree so the result is repeatable. get_n_leaves() counts the leaves, and str(depth) is needed because None cannot be formatted with a width otherwise. The pattern is the same as the polynomials: the unlimited tree has 60 leaves for 60 rows and a training error of exactly 0, which is memorisation, and its validation error is worse than depth 4. Random forests and gradient boosting (XGBoost, LightGBM) fight the same problem by averaging many trees and by these same depth limits.

Watch out A training score of 100% (or an error of 0) is not a success. It almost always means the model memorised the training set. Look at the validation score before you celebrate.

5k-fold cross-validation

So far we judged each model on one validation set. With little data that is noisy: which rows happen to land in validation can move the score by several points, and then you pick the wrong alpha or max_depth by luck.

k-fold cross-validation fixes that. Cut the data into k equal parts (folds, usually 5). Train on 4 folds and score on the fifth, then repeat so every fold is the validation set once. You get k scores; report their mean and how much they vary. cross_val_score does the whole loop for you: it makes a fresh copy of the model for every fold, trains it and returns the k scores as an array.

Try it: edit and run
from sklearn.datasets import make_moons
from sklearn.model_selection import KFold, cross_val_score, train_test_split
from sklearn.tree import DecisionTreeClassifier

X, y = make_moons(n_samples=200, noise=0.35, random_state=0)   # 200 points, 2 classes, overlapping

# One train/validation split: the score depends on which rows happened to land in validation.
for seed in [0, 1, 2, 3]:
    X_tr, X_val, y_tr, y_val = train_test_split(X, y, test_size=0.25, random_state=seed)
    tree = DecisionTreeClassifier(max_depth=4, random_state=0).fit(X_tr, y_tr)
    print(f"split {seed}: validation accuracy {tree.score(X_val, y_val):.2f}")

# 5-fold cross-validation: 5 splits, every row is in validation exactly once.
folds = KFold(n_splits=5, shuffle=True, random_state=0)
for depth in [1, 4, None]:
    model = DecisionTreeClassifier(max_depth=depth, random_state=0)
    scores = cross_val_score(model, X, y, cv=folds)       # accuracy on each of the 5 folds
    shown = " ".join(f"{s:.2f}" for s in scores)
    print(f"max_depth {str(depth):4}  folds {shown}   mean {scores.mean():.3f} +/- {scores.std():.3f}")
Expected output
split 0: validation accuracy 0.90
split 1: validation accuracy 0.88
split 2: validation accuracy 0.80
split 3: validation accuracy 0.88
max_depth 1     folds 0.80 0.72 0.65 0.72 0.70   mean 0.720 +/- 0.048
max_depth 4     folds 0.88 0.85 0.80 0.75 0.78   mean 0.810 +/- 0.046
max_depth None  folds 0.80 0.88 0.82 0.80 0.72   mean 0.805 +/- 0.048

Line by line:

  • make_moons (from the scikit-learn lesson) makes two interleaving half-circles of points, with noise=0.35 so the classes overlap and no model can be perfect.
  • train_test_split(..., test_size=0.25, random_state=seed) holds out a random 25% of the rows; a different seed holds out different rows. tree.score(X, y) is accuracy for a classifier.
  • KFold(n_splits=5, shuffle=True, random_state=0) describes how to cut the data: 5 folds, rows shuffled first with a fixed seed. Without shuffle=True the folds are simply rows 0-39, 40-79 and so on, which is wrong if the rows are sorted.
  • cross_val_score(model, X, y, cv=folds) returns a NumPy array of 5 accuracies, and .mean() and .std() summarise it.

The same model scored anywhere from 0.80 to 0.90 depending only on the split. Cross-validation says depth 4 is about 0.81 and the unlimited tree about the same, both clearly better than depth 1. The spread (+/- 0.05) tells you that differences smaller than that are noise, not a better model.

Cross-validation replaces the validation set, not the test set. The usual workflow: put a test set aside first, run cross-validation on the rest to choose the model and its settings, then score the final choice on the test set once. GridSearchCV automates the middle step: it runs cross_val_score for every combination of settings you list.

Tip For classification, StratifiedKFold keeps the share of each class the same in every fold, which matters when one class is rare (the metrics lesson). Passing cv=5 with a classifier uses it automatically, but without shuffling; pass StratifiedKFold(5, shuffle=True, random_state=0) to shuffle.

6Data leakage: a great score that is not real

Data leakage means information from the validation or test rows (or from the future, or from the answer itself) sneaks into training. The model then scores brilliantly in your notebook and badly in production. Leakage never shows up as an error: the only symptom is a score that is too good.

The most common leak is doing a preprocessing step on all the data before splitting. Scaling, filling missing values, choosing features, building a vocabulary: each of these learns something from the rows it sees (a mean, a list of useful columns). If it sees the validation rows, the model has peeked at them. For scaling the effect is usually small; for choosing features using the labels it can be huge. The box shows the worst case: 5000 columns of pure random noise and labels that have nothing to do with them, so the honest accuracy is 50%, a coin flip.

Try it: edit and run
import numpy as np
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

rng = np.random.RandomState(0)
X = rng.normal(size=(100, 5000))      # 100 rows, 5000 columns of pure noise
y = np.array([0, 1] * 50)             # labels with no link at all to X: honest accuracy is 50%
folds = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)

# LEAKY: scale and pick the 20 "best" columns using ALL rows, then cross-validate.
X_scaled = StandardScaler().fit_transform(X)
X_best = SelectKBest(f_classif, k=20).fit_transform(X_scaled, y)     # looked at every label
leaky = cross_val_score(LogisticRegression(), X_best, y, cv=folds)
print(f"leaky    accuracy {leaky.mean():.2f}")

# FIXED: the same steps inside a Pipeline, so each fold fits them on its training rows only.
pipe = make_pipeline(StandardScaler(), SelectKBest(f_classif, k=20), LogisticRegression())
honest = cross_val_score(pipe, X, y, cv=folds)
print(f"pipeline accuracy {honest.mean():.2f}")
Expected output
leaky    accuracy 0.86
pipeline accuracy 0.47

What the new pieces do:

  • rng.normal(size=(100, 5000)) makes a 100 x 5000 table of random numbers. np.array([0, 1] * 50) is 50 zeros and 50 ones, alternating: labels chosen without looking at X at all.
  • fit_transform(X) is fit (learn the means and spreads, or which columns to keep) followed by transform (apply it) in one call.
  • SelectKBest(f_classif, k=20) scores every column by how far apart its average is in class 0 and class 1, compared with its spread (an ANOVA F-test), and keeps the 20 highest. Out of 5000 noise columns, some line up with the labels by pure chance; it finds exactly those.
  • In the fixed version cross_val_score receives the whole pipeline. For each fold it fits the scaler, the selector and the model on the 80 training rows only, then scores on the 20 held-out rows.

The leaky version reports 86% on pure noise. The selector looked at every label, including the rows used for scoring, and picked the columns that happen to match them. Inside a Pipeline the selector never sees the held-out labels, and the score drops to the honest coin flip (47% is 50% plus noise). The same thing happens with fewer columns and real data, just less visibly: every "fit" step must learn from training rows only.

The rule: split first, then fit anything. A Pipeline makes that automatic, which is why scikit-learn code that uses one is easier to trust. If you preprocess with pandas, compute statistics like means on the training frame and apply them to the others.

Watch out Calling StandardScaler().fit(X) (or TfidfVectorizer().fit(texts)) on the full dataset and then splitting is the most common leak in tutorials and take-home tasks. Interviewers look for it. Put the step in a Pipeline, or fit it on X_train only.

7Target leakage and duplicates

Two more leaks that a Pipeline cannot fix, because they live in the data itself:

  • Target leakage: a feature that is only known after the thing you want to predict, or is computed from it. To predict which customers will cancel, a column "refund issued" looks amazing, because refunds are issued to people who already cancelled. At prediction time (before they cancel) that column is always empty. Other examples: "days in hospital" to predict a diagnosis, "ticket resolution note" to predict the ticket's category.
  • Duplicates across splits: the same or nearly the same row in both training and validation. The model only has to remember it. Scraped web pages, support tickets copied between systems, an upsampled class, or many rows from one user all cause it.
Try it: edit and run
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import KFold, cross_val_score
from sklearn.neighbors import KNeighborsClassifier

rng = np.random.RandomState(0)
folds = KFold(n_splits=5, shuffle=True, random_state=0)

# 1. Target leakage: predict which customers will cancel (churned = 1).
n = 400
tickets = rng.poisson(2, n)                                  # support tickets last month: a real signal
churned = (rng.uniform(0, 1, n) < 0.1 * tickets).astype(int)
refunded = churned * (rng.uniform(0, 1, n) < 0.9)            # refunds are issued AFTER someone cancels
honest = tickets.reshape(-1, 1)
leaky = np.column_stack([tickets, refunded])
print(f"always say 'stays'     accuracy {1 - churned.mean():.2f}")
print(f"tickets only           accuracy {cross_val_score(LogisticRegression(), honest, churned, cv=folds).mean():.2f}")
print(f"tickets + refunded     accuracy {cross_val_score(LogisticRegression(), leaky, churned, cv=folds).mean():.2f}")

# 2. Duplicates across splits: 100 rows of noise, each copied 3 times (the same ticket scraped 3 times).
X = rng.normal(size=(100, 10))
y = rng.randint(0, 2, 100)                                   # random labels: honest accuracy is about 50%
X3, y3 = np.repeat(X, 3, axis=0), np.repeat(y, 3)
knn = KNeighborsClassifier(n_neighbors=1)
print(f"with duplicates        accuracy {cross_val_score(knn, X3, y3, cv=folds).mean():.2f}")
_, first = np.unique(X3, axis=0, return_index=True)          # position of one copy of each distinct row
print(f"duplicates removed     accuracy {cross_val_score(knn, X3[first], y3[first], cv=folds).mean():.2f}")
Expected output
always say 'stays'     accuracy 0.80
tickets only           accuracy 0.80
tickets + refunded     accuracy 0.98
with duplicates        accuracy 0.97
duplicates removed     accuracy 0.42

The new lines:

  • rng.poisson(2, n) draws whole-number counts that average 2, a typical shape for "how many tickets". rng.uniform(0, 1, n) < 0.1 * tickets is True with a probability of 0.1 times the ticket count (2 tickets: 20%), so customers with more tickets cancel more often; .astype(int) turns True/False into 1/0.
  • churned * (... < 0.9) is 1 for 90% of the customers who cancelled and 0 for everyone else: the refund column copies the answer.
  • np.column_stack([a, b]) puts arrays side by side as columns. np.repeat(X, 3, axis=0) repeats every row 3 times in a row.
  • np.unique(X3, axis=0, return_index=True) finds the distinct rows and returns two things: the rows and the index of one copy of each. _, first = ... unpacks the pair and throws the first part away. X3[first] picks those rows.
  • KNeighborsClassifier(n_neighbors=1) answers with the label of the single closest training row, which makes it the perfect memoriser.

The honest model is no better than always guessing "stays" (both 0.80): one weak feature is just not enough, and that is a real, useful finding. Add the refund column and it jumps to 0.98, a number that will collapse in production. With duplicates, the 1-nearest-neighbour model finds the exact copy of almost every validation row in training and scores 0.97 on random labels. Remove the duplicates and it falls to coin-flip level.

Exact duplicates you can drop (df.drop_duplicates() in pandas). For rows that belong together without being identical, many messages from one user or many chunks from one document, keep each group entirely on one side of the split: GroupKFold(n_splits=5) with cross_val_score(..., groups=user_ids), or GroupShuffleSplit for a single split. The model is then scored on users or documents it has never seen, which is what production looks like.

Tip For every feature, ask: "would I have this value at the moment I need the prediction?" If the honest answer is "only later", it is target leakage. A single feature that makes a hard problem easy deserves suspicion before applause.

8Time-series leakage: do not train on the future

When rows have a time order (daily signups, prices, logs, sensor readings), a shuffled split lets the model train on Wednesday and Friday and then "predict" Thursday. In production you only ever have the past. Shuffling therefore makes the problem look much easier than it is.

TimeSeriesSplit keeps the order: each fold trains on an early stretch and validates on the stretch right after it, so the model is always predicting the future, like in production.

Try it: edit and run
import numpy as np
from sklearn.model_selection import KFold, TimeSeriesSplit, cross_val_score
from sklearn.tree import DecisionTreeRegressor

rng = np.random.RandomState(0)
days = np.arange(200)                                          # day 0 .. day 199, in order
signups = 100 + 2 * days + rng.normal(0, 10, 200)              # a growing product, plus noise
X = days.reshape(-1, 1)
model = DecisionTreeRegressor(min_samples_leaf=3, random_state=0)   # each leaf: a few nearby days


def mean_error(cv):
    scores = cross_val_score(model, X, signups, cv=cv, scoring="neg_mean_absolute_error")
    return -scores.mean()                                      # sklearn scores are "higher is better", so errors come negated


print(f"shuffled KFold    average error {mean_error(KFold(5, shuffle=True, random_state=0)):6.1f} signups")
print(f"TimeSeriesSplit   average error {mean_error(TimeSeriesSplit(n_splits=5)):6.1f} signups")

for train, val in TimeSeriesSplit(n_splits=5).split(X):
    print(f"  train days {train[0]:3}-{train[-1]:3}   validate days {val[0]:3}-{val[-1]:3}")
Expected output
shuffled KFold    average error   10.1 signups
TimeSeriesSplit   average error   39.6 signups
  train days   0- 34   validate days  35- 67
  train days   0- 67   validate days  68-100
  train days   0-100   validate days 101-133
  train days   0-133   validate days 134-166
  train days   0-166   validate days 167-199

np.arange(200) is the numbers 0 to 199, like a for loop range as an array. DecisionTreeRegressor(min_samples_leaf=3) cuts the timeline into stretches of at least 3 training days and predicts the average signups of the stretch a day falls in. scoring="neg_mean_absolute_error" asks cross_val_score for the average absolute error instead of the default score; scikit-learn always treats a bigger score as better, so it returns errors as negative numbers and we flip the sign back. .split(X) yields pairs of index arrays, one pair per fold, and train[0] and train[-1] are the first and last training day.

With shuffled folds the model always has training days on both sides of the one it predicts, so it just averages its neighbours: an error of about 10, which is the noise. Forced to predict days after its training data, every future day falls into the last stretch it saw, so it keeps predicting those old values while the product keeps growing: an error four times larger. That 39.6 is the number your forecast will really have.

The same applies to features: a "7-day average" that includes days after the row, or a statistic computed over the whole history, leaks the future. Build every feature from data older than the moment of prediction.

9Leakage in the LLM era: contaminated evals

Everything above has an LLM version, and it is just as easy to fall into:

  • Eval questions in the prompt. You copy a few examples from your eval set into the prompt as few-shot examples, or into the RAG knowledge base, then grade the system on the same questions. It "answers" them by copying.
  • Eval questions in fine-tuning data. You fine-tune on support tickets and evaluate on tickets from the same export. Same leak as duplicates across splits.
  • Test questions in pre-training data (contamination). Public benchmarks are all over the web, so a model may have seen the questions, and even the answers, while it was trained. A high benchmark score can partly be memory. That is why serious teams keep a private eval set that never leaves the company, and refresh it with new questions over time.
  • Prompt overfitting. Tweak a prompt 50 times against the same 20 eval questions and you have tuned it to those 20. Keep a held-out set you only run before a release, exactly like a test set.

A simple first check for the first two is n-gram overlap: break texts into runs of n consecutive words and see how many of an eval question's runs also appear in what the model saw. Big labs report contamination with this kind of check.

Try it: edit and run
import re


def ngrams(text, n=5):
    words = re.findall(r"[a-z0-9]+", text.lower())          # lowercase words, punctuation dropped
    return {tuple(words[i:i + n]) for i in range(len(words) - n + 1)}


# What the model saw: fine-tuning examples, or the few-shot examples pasted into your prompt.
training_text = [
    "Q: How do I reset my password? A: Open Settings, choose Security, then click Reset password.",
    "Q: Can I export my invoices as CSV? A: Yes, from Billing, click Export and pick CSV.",
    "Q: Why was my card declined? A: The bank refused it; try another card or call the bank.",
]

# Your eval set: questions you grade the model on.
eval_questions = [
    "How do I reset my password?",
    "can i export my invoices as csv",
    "How do I reset my password on the mobile app?",
    "How do I delete my account?",
    "Why does the app log me out every hour?",
]

seen = set()
for doc in training_text:
    seen |= ngrams(doc)                                      # every 5-word sequence the model saw

for q in eval_questions:
    grams = ngrams(q)
    overlap = len(grams & seen) / len(grams) if grams else 0.0
    label = "LEAKED" if overlap >= 0.5 else "ok"
    print(f"{overlap:4.0%}  {label:6}  {q}")
Expected output
100%  LEAKED  How do I reset my password?
100%  LEAKED  can i export my invoices as csv
 33%  ok      How do I reset my password on the mobile app?
  0%  ok      How do I delete my account?
  0%  ok      Why does the app log me out every hour?

How it works:

  • re.findall(r"[a-z0-9]+", text.lower()) returns every run of lowercase letters and digits as a list, so case and punctuation stop mattering. The r before the string makes it a raw string, the usual way to write a regular expression in Python.
  • {tuple(words[i:i + n]) for i in range(...)} is a set comprehension: every window of 5 consecutive words, as a tuple (tuples can go in a set; lists cannot, because they can change). "how do i reset my password" gives two: (how, do, i, reset, my) and (do, i, reset, my, password).
  • seen |= ngrams(doc) adds one set into another (set union, like addAll in Java). grams & seen is the intersection: the windows that appear in both.
  • ... if grams else 0.0 guards against questions shorter than 5 words, which have no windows at all (dividing by zero would crash). {overlap:4.0%} prints 0.333 as 33%.

Different case and punctuation did not hide the second question. The third shares only "how do i reset my password", so it scores 33% and passes, which is right: it asks something new. What n-gram overlap cannot catch is a paraphrase ("I forgot my login, what now?"). For that, compare embeddings of eval questions and training texts and review anything above a similarity threshold, which you will build in the semantic search lab.

The fix is the same as in classic ML: split first. Freeze your eval set before you write prompts, pick few-shot examples from a separate pool, keep eval items out of fine-tuning data and RAG documents, and run this check in CI whenever either side changes.

Tip When a new model "crushes" a public benchmark, ask how it does on questions written after its training cutoff, or on your own private eval set. That is the test set it cannot have memorised.

Common mistakes

  • Judging a model by its training score. Always compare it with the validation score: a big gap means overfitting.
  • Fitting a scaler, vectorizer or feature selector on all the data before splitting or cross-validating. Put it in a Pipeline so each fold fits it on training rows only.
  • Shuffling time-ordered data. Use TimeSeriesSplit or a cut by date, and build features only from the past.
  • Letting the same user, document or near-duplicate row land on both sides of the split. Drop duplicates, and use GroupKFold with groups= for related rows.
  • Tuning alpha, max_depth or a prompt against the test set. Tune with cross-validation or a validation set, and touch the test set once at the end.
  • Reusing eval questions as few-shot examples, RAG documents or fine-tuning data, then trusting the eval score.

Practice

Write the code, then press Check. Your work is saved in this browser.

1Scale without leaking

scale_without_leak(X_train, X_val) should standardise both arrays (subtract a mean, divide by a standard deviation, per column) using statistics learned from X_train only, exactly like StandardScaler().fit(X_train) followed by transform on each. The starter leaks: it learns from both. Fix it and return the two scaled arrays.

Exercise
import numpy as np


def scale_without_leak(X_train, X_val):
    X_all = np.vstack([X_train, X_val])                 # the leak: validation rows are included
    mean, std = X_all.mean(axis=0), X_all.std(axis=0)
    return (X_train - mean) / std, (X_val - mean) / std


X_train = np.array([[1.0], [2.0], [3.0]])
X_val = np.array([[10.0]])
a, b = scale_without_leak(X_train, X_val)
print(a.ravel().round(2).tolist(), b.ravel().round(2).tolist())
Hint

Compute `mean` and `std` from `X_train` with `axis=0` (one value per column), then apply the same two arrays to both inputs.

2k-fold by hand

Write kfold_splits(n, k) that returns a list of k pairs (train, val) of index lists for rows 0 .. n-1, without shuffling, the way KFold(n_splits=k) does: the folds are consecutive blocks, the first n % k folds get one extra row, and each pair's train is every index not in val, in order.

Exercise
def kfold_splits(n, k):
    # your code here
    return []


for train, val in kfold_splits(5, 2):
    print(train, val)
Hint

Fold i has `n // k + (1 if i < n % k else 0)` rows. Keep a `start` position, take `range(start, start + size)` as `val`, and build `train` from the indices not in it.

3Flag contaminated eval questions

Write find_leaks(eval_items, training_text, n=5, threshold=0.5) that returns the eval items (in their original order) whose share of word n-grams also found in training_text is at least threshold. Use the ngrams helper given. An item with fewer than n words has no n-grams and is never flagged.

Exercise
import re


def ngrams(text, n=5):
    words = re.findall(r"[a-z0-9]+", text.lower())
    return {tuple(words[i:i + n]) for i in range(len(words) - n + 1)}


def find_leaks(eval_items, training_text, n=5, threshold=0.5):
    # your code here
    return []


print(find_leaks(["How do I reset my password?", "Delete my account"],
                 ["Q: How do I reset my password? A: Use Settings."]))
Hint

Build one set of every n-gram in `training_text` first. Then for each item compute `len(grams & seen) / len(grams)` and skip items whose `grams` is empty.

Interview questions

Q1What is the difference between underfitting and overfitting, and how do you spot each?

Underfitting: the model is too simple, so both training and validation error are high. Overfitting: the model memorises the training data, noise included, so training error is low but validation error is much higher. Compare the two scores side by side; the size of the gap is the signal.

Q2Explain the bias-variance trade-off.

Bias is error from a model that is too simple: it is wrong in the same way whatever data it sees. Variance is error from a model that is too flexible: its predictions change a lot with small changes in the training data. Making a model more flexible lowers bias and raises variance. You pick the complexity (and regularization strength) where validation error is lowest. More data lowers variance but not bias.

Q3What is regularization? Give examples.

Anything that limits how closely a model can fit its training data, to reduce overfitting. L2 (Ridge, weight decay) adds the sum of squared weights to the loss; L1 (Lasso) adds the sum of absolute weights and can zero some out. For trees: max_depth, min_samples_leaf. For neural networks: weight decay, dropout, early stopping. The strength is a hyperparameter chosen with validation data or cross-validation.

Q4Why use k-fold cross-validation, and does it replace a test set?

One validation split gives a noisy score that depends on which rows landed in it. k-fold trains k times, each time validating on a different fold, so every row is validated once; the mean is more reliable and the spread shows how much differences matter. It replaces the validation set for model selection, not the test set: keep a test set aside and use it once at the end. Use StratifiedKFold for classification, GroupKFold for related rows, TimeSeriesSplit for time-ordered data.

Q5What is data leakage? Give examples and how you prevent them.

Information that would not be available at prediction time reaches training, so offline scores are too good. Examples: fitting a scaler or feature selector on all data before splitting (fix: a Pipeline inside cross-validation), target leakage like a refund column to predict churn (fix: only use features known at prediction time), duplicates or the same user in train and test (fix: deduplicate, group splits), shuffling time series (fix: split by time). The symptom is a score that is too good to be true.

Q6How would you check whether an LLM eval is contaminated?

Keep eval items out of prompts, few-shot pools, RAG documents and fine-tuning data, and verify it: compute n-gram overlap (for example 8 to 13 word windows) between eval items and everything the model was given, and embedding similarity to catch paraphrases. For public benchmarks, assume the base model may have seen them; compare with questions created after its training cutoff and rely on a private, refreshed eval set. Hold out part of your eval set so prompt tuning does not overfit to it.