Sub topic 8
Splitting data without leakage
This chapter assumes you can build a user-item matrix and read the NumPy code from earlier chapters. You should also know what RMSE and precision@k measure. Here you learn how to hold out data so that your evaluation scores are honest.
What leakage is
Leakage happens when information from the test set influences training. The model then looks better offline than it will be in production. In recommenders this is easy to do by accident, because the training data is a matrix and every cell is a potential test case.
Common sources of leakage:
- Fitting similarities, item means, or factor vectors on the full matrix before splitting.
- Using a random split when the real task is to predict future behavior. The model sees later interactions and is tested on earlier ones.
- Tuning hyperparameters on the test set, so the test score is no longer a fresh estimate.
- Duplicate interactions (the same user-item pair twice) landing on both sides of the split.
Choosing a split strategy
| Strategy | How it works | When to use it |
|---|---|---|
| Random per interaction | Hide a random share of interactions | Quick experiments, no timestamps |
| Leave-one-out | Hide each user's last interaction | Top-N ranking with little data per user |
| Temporal per user | Hide each user's most recent share | Closest match to real use |
| Global time cutoff | Train before a date, test after it | Production-style backtests |
Random splits are the weakest choice when timestamps exist. A model that has seen a user's later behavior can infer taste that it could not have known at recommendation time.
A per-user temporal split
The function below sorts each user's events by time. It then moves the latest share into the test set and keeps at least one test event per user.
import numpy as np
# Each row: (user, item, timestamp)
events = np.array([
[0, 0, 1], [0, 1, 2], [0, 3, 3], [0, 2, 4],
[1, 0, 1], [1, 3, 2], [1, 1, 5],
[2, 2, 1], [2, 3, 2], [2, 0, 3], [2, 1, 4],
])
def temporal_split(events, test_frac=0.25):
train, test = [], []
for u in np.unique(events[:, 0]):
rows = events[events[:, 0] == u]
rows = rows[np.argsort(rows[:, 2])]
n_test = max(1, int(round(len(rows) * test_frac)))
train.extend(rows[:-n_test])
test.extend(rows[-n_test:])
return np.array(train), np.array(test)
train, test = temporal_split(events)
print(len(train), "train events,", len(test), "test events")
# Build the matrix from training events only
R_train = np.zeros((3, 4))
for u, i, t in train:
R_train[u, i] = 1.0
# Check: every test event is later than that user's training events
for u in np.unique(test[:, 0]):
assert train[train[:, 0] == u, 2].max() < test[test[:, 0] == u, 2].min()
print(R_train)The matrix R_train is the only thing the model may see. Compute similarities, means, and factors from it, and nothing else.
Details that still bite
- Unseen users and items. A test user or item with no training events cannot be scored by a neighborhood or factorization model. Either drop those rows and report how many you dropped, or evaluate them separately as a cold start case.
- Exclude seen items. When ranking for a user, remove items already in their training history. Otherwise the model is rewarded for repeating what it already knows.
- Three-way split. Tune on a validation set taken from the end of the training period. Touch the test set once, at the end.
- Normalization. Compute rating means and any scaling on the training data, then apply them to the test data.
Exercise
You compute each item's mean rating from the whole dataset, then split into train and test and train a model that uses those means as a baseline. What is wrong, and how do you fix it?
Show answer
The item means include test ratings, so the baseline has seen the answers it is scored on. This is leakage. Split first, compute the means from the training set only, and apply those means to the test set.