Skip to main content
DARKPC.NET

Split a Dataset Without Leaking Test Answers

Use a grouped train/test split to keep repeated measurements from the same source on one side of an evaluation.

Difficulty Intermediate

What you will check

If six readings from one sensor appear on both sides of a split, a model may recognise that sensor's quirks. A grouped split measures how well your workflow could handle a wholly unseen sensor. Choose the group to match your deployment question. New readings from known sensors may call for a time-based split instead.

Prepare a tiny practice dataset

Use Python 3 and a virtual environment with scikit-learn installed. A CPU laptop is enough. The fixture assigns two observations to each of six fictional sensors and prints which sensors each side contains.

from sklearn.model_selection import GroupShuffleSplit

groups = [name for name in "ABCDEF" for _ in range(2)]
features = [[row, row % 2] for row in range(len(groups))]
split = GroupShuffleSplit(n_splits=1, test_size=1/3, random_state=29)
train, test = next(split.split(features, groups=groups))
train_groups = {groups[row] for row in train}
test_groups = {groups[row] for row in test}
assert train_groups.isdisjoint(test_groups)
assert len(train_groups) == 4 and len(test_groups) == 2
print("Train groups:", sorted(train_groups), "rows:", len(train))
print("Test groups:", sorted(test_groups), "rows:", len(test))

The fraction applies to groups and actual row counts can vary when group sizes differ. Save the assignment before fitting. If duplicate source records have different group identifiers, fix the identifier map before splitting.

Keep the test set reserved

Fit scaling, missing-value handling and feature selection using training data, preferably inside a pipeline. Use separate validation folds drawn from training groups when choosing settings. Evaluate the chosen pipeline once on the reserved groups. Separately check that history-based features only use information available at the prediction time.

Troubleshooting and practice

A rare label can vanish from one side. Print label counts per group, then consider a stratified group cross-validator when class coverage is feasible. If two independent groups are all you have, report that uncertainty instead of claiming a representative benchmark. Add six observations to group A and compare group fractions with row fractions. Repeat with a chronological split and explain which deployment question each version answers. Avoid publishing identifiable group keys.

References and related reading