Sub topic 8
Splitting Data Without Leakage
This chapter assumes you know basic Python and NumPy, and that you have built a user-item matrix as in the earlier chapters. Here you will learn how to divide interaction data into training and test sets so that your evaluation reflects how the recommender will behave on data it has not seen.
Why splitting is different for recommenders
In a classic classification task, each row is an independent example. You shuffle the rows, hold out 20%, and train on the rest. Recommendation data is different in three ways:
- Each row is an interaction between a user and an item, and one user or item appears in many rows.
- The model must know something about every user it scores. A user with no training interactions has no neighborhood and no factor vector.
- Interactions happen in time. The model will be used to predict the future, not to fill in the past.
A split is leaky when information from the test set reaches the model during training or tuning. Leakage makes the metrics look better than the production system will perform. The goal of this chapter is to avoid it.
What counts as leakage
Leakage in collaborative filtering takes several forms:
- Test ratings in the matrix. If you build the similarity matrix or train the factorization model on the full matrix and then "predict" held-out cells, the model has already seen the answers.
- Future data predicting the past. A random split can place a rating from December in the training set and one from March in the test set. The model learns taste patterns that did not yet exist at the time it is asked to predict.
- Duplicate interactions. Implicit logs often record the same user-item pair many times (repeated plays, repeated clicks). A random split puts some copies in training and some in test, so the model is tested on pairs it has already seen.
- Tuning on the test set. If you pick
k,reg, or the number of factors by looking at test scores, the test set has influenced the model. You need a separate validation set. - Statistics computed globally. Global mean rating, item popularity, and mean-centering values must be computed from training data only.
Three splitting strategies
| Strategy | How it works | Good for | Main risk |
|---|---|---|---|
| Random holdout | Hold out a random fraction of all interactions | Quick experiments, rating prediction | Ignores time, can leak the future |
| Leave-one-out | Hold out one interaction per user (often the latest) | Top-N ranking with sparse users | Small test set, noisy metrics |
| Temporal split | Train on everything before a cutoff date, test after | Systems that run on live data | Users and items may be missing from training |
For any system that will be deployed, prefer a temporal split or a per-user temporal split. It matches the real task: given what we know now, what will the user do next?
A per-user temporal split in code
The following code splits an interaction table by time, per user. For each user it sends the latest interactions to the test set and the rest to the training set. It keeps users with too little history entirely in training, so they are never scored with an empty profile.
import numpy as np
# Each row: (user, item, rating, timestamp)
interactions = np.array([
[0, 0, 5, 100], [0, 1, 3, 110], [0, 3, 1, 120], [0, 2, 4, 130],
[1, 0, 4, 105], [1, 3, 1, 115], [1, 1, 2, 125],
[2, 0, 1, 101], [2, 1, 1, 111], [2, 3, 5, 121], [2, 2, 3, 131],
[3, 0, 1, 102], [3, 3, 4, 112],
[4, 1, 1, 103], [4, 2, 5, 113], [4, 3, 4, 123],
], dtype=float)
def per_user_temporal_split(data, test_fraction=0.25, min_interactions=3):
train_rows, test_rows = [], []
for user in np.unique(data[:, 0]):
rows = data[data[:, 0] == user]
rows = rows[np.argsort(rows[:, 3])] # oldest first
if len(rows) < min_interactions:
train_rows.append(rows) # too little history to evaluate
continue
n_test = max(1, int(round(len(rows) * test_fraction)))
train_rows.append(rows[:-n_test])
test_rows.append(rows[-n_test:])
return np.vstack(train_rows), np.vstack(test_rows)
train, test = per_user_temporal_split(interactions)
print("train:", len(train), "test:", len(test))
# No test interaction is older than the same user's last training interaction.
for u in np.unique(test[:, 0]):
assert train[train[:, 0] == u, 3].max() < test[test[:, 0] == u, 3].min()The assertion at the end is a cheap leakage check. Write checks like it for every split you build.
Building the training matrix correctly
After splitting, build the matrix from the training rows only. Test ratings must stay out of it.
import numpy as np
def to_matrix(rows, n_users, n_items):
R = np.zeros((n_users, n_items))
for u, i, r, _ in rows:
R[int(u), int(i)] = r
return R
R_train = to_matrix(train, n_users=5, n_items=4)
# Statistics come from training data only.
global_mean = R_train[R_train > 0].mean()
print(f"global mean (train only): {global_mean:.2f}")
print("test cells hidden in train matrix:",
all(R_train[int(u), int(i)] == 0 for u, i, _, _ in test))The second print confirms that every test cell is still zero in the training matrix. Because 0 means "not rated", the model cannot tell a hidden test rating from an item the user never saw.
Edge cases
Users and items missing from training
With a temporal split, some test users or items may never appear in training. These are cold-start cases (covered in a later chapter). You have two honest options:
- Drop them from the test set and report how many you dropped.
- Keep them and let the model fall back to a default, such as the global mean or the most popular items, and report metrics for these cases separately.
Silently dropping them makes results look better than they are, because the hardest cases disappear from the evaluation.
Duplicates in implicit data
Deduplicate user-item pairs before splitting, or split by pair rather than by event. If the same song was played ten times, and you want to evaluate "will the user play a new song", remove from the test set any pair that also occurs in training. Whether repeat consumption counts as a good recommendation depends on the product, so decide this on purpose and state it.
Ranking candidates must exclude training items
When you compute top-N lists for evaluation, remove items the user already interacted with in training. Otherwise the list fills with known items, and precision@k measures something other than discovery.
Three-way splits
Hyperparameters such as the neighborhood size k, the number of factors, and the regularization strength need a validation set. Split once into train, validation, and test. Tune on validation, then evaluate on test one time. If you use cross-validation, split by time or by user group in each fold, and keep a final test set outside the loop.
Small data and random splits
For a small research dataset with ratings spread over a short period, a random holdout is acceptable for comparing algorithms. Use a fixed random seed, repeat with several seeds, and report the spread. A single split on a small matrix gives noisy numbers.
A leakage checklist
- The similarity matrix or factors were computed from training rows only.
- Means, popularity counts, and normalization values come from training rows only.
- Every test interaction is later than the same user's training interactions (for temporal splits).
- No user-item pair appears in both training and test, unless repeat consumption is intended.
- Hyperparameters were chosen on validation data.
- The test set was used once.
- You counted and reported users and items that are missing from training.
Exercise
A teammate builds the full 5x4 user-item matrix, computes item-item cosine similarity from it, then sets 20% of the rated cells to 0 and measures RMSE on those cells using predictions from the similarity matrix. The RMSE is surprisingly low. What went wrong, and how do you fix it?
Show answer
The similarity matrix was computed before the cells were hidden, so the held-out ratings influenced the similarities used to predict them. This is leakage. Split the interactions first, build the matrix from the training rows only (test cells stay 0), compute similarities from that matrix, and then evaluate on the held-out cells.
Exercise
Why can a random split give better scores than a temporal split on the same data, and which one better predicts production performance for a system that recommends new items daily?
Show answer
A random split places interactions from the same period in both sets, so the model sees trends, popular items, and context that match the test data. A temporal split forces it to predict the future from the past, as in production. The temporal split scores lower but is the more honest estimate for a live system.