Split by recordings, not by windows
When training examples come from the same sample: leakage, heuristics, scikit-learn and dynamic programming.
On this page
- Two different things we call a “sample”
- The case: windows from radar recordings
- How similar are the windows?
- What is needed
- A number partitioning problem
- A greedy heuristic with a trick
- If we use scikit-learn
- The optimal solution: dynamic programming
- How much does leakage matter?
- Comparison and recommendations
- Closing
- Data
- References
Splitting a dataset into train and test looks like the easiest part of the whole process:
we call train_test_split, pick 70/30 and move on to what seems more interesting. This
works well as long as the examples are independent of each other. When they are not, the
test set stops measuring what we think it measures, and nothing in the code warns us. It
seems like something sensible that we take for granted, but I have seen many projects with
splitting errors caused by not taking this into account.
Two different things we call a “sample”
In statistics, a sample is what we get when we observe the problem domain: a patient, a user session, a machine measured on a given day, a radar recording. Each one is a “capture” from the sample space, and what we want to know is how the model will behave on new captures from that same space.
In machine learning, on the other hand, we usually call “sample” each data point that goes into the model. And often those data points are not different captures: they come from processing the same observation. A recording is cut into windows, a medical image into patches, a time series into fragments, and sometimes data augmentation is added on top. A single sample from the domain yields tens or hundreds of training examples, very similar to each other.
I have often seen data scientists and ML engineers mix up the two: treating the processed
examples as if they were independent samples, shuffling them and splitting them at random
into train, validation and test. As a result, validation and test end up contaminated with
examples that are not independent of the ones in train, because they come from the same
observation. The model is evaluated on almost identical versions of what it already saw,
the metric is inflated, and since validation is contaminated too, the decisions made with it
(when to stop training, which hyperparameters to choose, which model to keep) are biased as
well. It is an easy mistake to make because in the code both things have the same name: X,
y, n_samples.
It happens with patients who contribute several images, with users who have several sessions, with machines measured many times, with audio cut into fragments. The literature treats it as a case of data leakage [2, 3]. The question to ask is always the same: which unit will be new when the model is in production? That unit is the domain sample, and it is the one that has to be split between train, validation and test.
In my thesis I ran into this problem while classifying radar signals. In this article I explain how I approached it, what scikit-learn offers, how to find the optimal solution and what biases each alternative has. To keep it from staying in theory, I also trained the same model with correct and incorrect splits, and measured the difference. To avoid adding confusion, from here on I use recording for the domain sample and window for the training example that comes out of it.
The case: windows from radar recordings
The thesis dataset is made of radar recordings of people, vehicles and animals (the first article of the series, What a radar sees when you walk, shows what they look like). Each recording lasts between a few seconds and a minute and a half, and to classify it, it is cut into 4 s windows that are converted into images. The windows overlap: each one starts half a second after the previous one, so two consecutive windows share 87.5 % of the signal.
The result is 30,459 windows (frames) that come from only 569 recordings. If the windows are
split at random with train_test_split, even stratifying by class, 557 of the 569
recordings end up with windows in both train and test. The model is evaluated on images
almost identical to others it saw during training, and the test metric no longer tells how
it will behave on a new recording.
There is an intermediate case worth keeping in mind: cutting each recording in time before building the windows, and sending one portion to train and another to test. This way no test window shares signal with a train window (those that would cross the cut are discarded), but both still come from the same person, in the same take, a few seconds earlier or later. The figure shows the three ways of splitting on two example recordings.

How similar are the windows?
Besides saying that windows are “not independent”, it is worth measuring how similar they are. To compare two windows I used the 2D cross-correlation of their spectrograms along time: I shift one image relative to the other by up to 2 s, compute the correlation coefficient over the overlapping part and keep the maximum. This compares the full pattern (frequency and time) and tolerates it appearing shifted in time (for example, the same step half a second later). Beforehand I subtract the mean spectrum of the dataset, so that the background common to all images does not dominate.

Two consecutive windows have a correlation of 0.99 (1 would mean identical): in practice, they are the same image shifted by half a second. Two windows from the same recording that no longer share signal (between 4 and 10 s apart) are around 0.62, and two windows from different recordings of the same class, 0.42. Even without overlap, a recording looks more like itself than like the others: it is the same person, at the same speed and in the same place.
The consequence for the split shows up when looking, for each test window, for the most similar train window. With the split by frames, in 98 % of the cases that window comes from the same recording, and the distance is about 30 times smaller than with the split by recordings: train and test have almost the same windows. With the time cut, the near duplicates disappear. The most similar train window usually comes from another recording (only in 16 % of the cases is it from the same one), and the distance is the same as with the split by recordings. Among more than 18,000 train windows, there is almost always another recording as similar as its own.

What is needed
In this case the answer is the recording: in operation, the radar will see objects it has never seen. So the split has to meet two conditions:
- Hard constraint: each recording goes entirely to train or to test.
- Goal: a given proportion (here, 70/30) in each class, measured in windows and not in recordings, because the model is trained and evaluated on windows.
What complicates the second condition is that recordings have very different sizes. In the “one person” class there are 231 recordings, with a median of 32 windows and a maximum of 147. And some classes have very few recordings: the tracked vehicle class has 9, almost all of them long.
| Class | Windows | Recordings | Windows per recording (median / max) |
|---|---|---|---|
| one person | 8,586 | 231 | 32 / 147 |
| two people | 8,472 | 127 | 62 / 166 |
| animal | 5,056 | 69 | 71 / 167 |
| noise (synthetic) | 4,160 | 80 | 52 / 52 |
| car | 3,043 | 53 | 50 / 142 |
| tracked vehicle | 1,142 | 9 | 132 / 172 |
A number partitioning problem
Looked at class by class, the problem can be stated like this: given a set of numbers (the windows of each recording), choose a subset whose sum (in number of windows) is as close as possible to 30 % of the total. That subset goes to test and the rest to train.
This is the subset sum problem, a classic in complexity theory: it is NP-complete [4]. In practice it is not as bad as it sounds: the difficulty appears when the numbers are very large; if the total is manageable, it can be solved in time proportional to (number of groups) × (total number of windows), which is called pseudo-polynomial time. With totals of a few thousand windows, that is solved in a fraction of a second.
The 50/50 case is the partition problem: splitting into two equal halves. There is a classic reduction between the two, which is the idea behind the heuristic I used in the thesis.
A greedy heuristic with a trick
For the 50/50 case there is a well-known heuristic: sort the numbers from largest to smallest and assign each one to the partition with the smallest sum at that moment. It works very well when there are many small numbers to balance things at the end (the large ones are distributed first and the small ones even out the sums).
For 70/30 a trick is needed. If is the class total and the target for test (), a dummy element of value is added to train. When the heuristic manages to equalize both sums, test is worth and train, without the dummy, is worth . This is the reduction from subset sum to partition.
def greedy_dummy(sizes, rate): """Indices of the groups that go to test.""" K = sum(sizes) W = int(K * rate) test_sum, train_sum = 0, 2 * W - K # the dummy goes in train test = [] for i in np.argsort(sizes)[::-1]: # largest to smallest if test_sum < train_sum: test.append(i) test_sum += sizes[i] else: train_sum += sizes[i] return testOn this dataset it does very well in terms of proportions: 30.0 % in all classes except the tracked vehicle class, which ends up at 31.5 %. But it has a property that is not obvious from reading the code. With 70/30 the dummy is worth , so train starts “in the negative” and the largest groups all go to train until train accumulates about 40 % of the class. Only then does it start alternating. In practice, the longest 20 % of the recordings of each class almost never end up in test (0 % and 4 % in the first two deciles, over 100 splits with different seeds), and the rest end up in test more often than they should.
If the duration of a recording has nothing to do with what we want to classify, this does no harm. But it usually does: long recordings may come from another scenario, from slower objects or from a different measurement campaign. In that case the test set is less representative, and there is no way to see it by looking only at the proportions.
If we use scikit-learn
scikit-learn has two tools for group splits.
GroupShuffleSplit picks groups at random. It is simple and has no size bias, but it
has two problems for this case. The first is that test_size is a fraction of groups,
not of examples. The second is that it does not stratify by class. Over 100 seeds, the test
fraction per class strayed up to 54 points from the target: the tracked vehicle class ended
up between 0 % and 84 % depending on the seed.
StratifiedGroupKFold (since version 1.0) is designed for cross-validation: it builds
folds that respect the groups and try to keep the class proportions. Looking at its
source code (version 1.9.1) [5], the algorithm does this:
- counts the examples of each group per class;
- sorts the groups by the standard deviation of those counts, from largest to smallest;
- assigns each group to the fold where the class distribution ends up most even.
When each group has a single class, as here, step 2 amounts to sorting the groups by size, and step 3 amounts to sending each group to the fold with the fewest examples of its class. It is the same greedy heuristic as before, but with equal bins instead of two unequal ones. To build a 70/30 hold-out, it is enough to ask for 10 folds and join 3:
from sklearn.model_selection import StratifiedGroupKFold
sgkf = StratifiedGroupKFold(n_splits=10, shuffle=True, random_state=seed)folds = [test for _, test in sgkf.split(X, y, groups)]test_idx = np.concatenate(folds[:3]) # 3 of 10 folds = 30 %train_idx = np.setdiff1d(np.arange(len(y)), test_idx)Equal bins have an advantage: since all of them receive large and small groups alike, choosing any 3 does not introduce size bias. The price is precision in classes with few groups: with 9 tracked vehicle recordings spread over 10 folds, the test fraction was 41.5 % for every seed. It also supports groups with several classes, something the other alternatives I present in this article do not handle.
The optimal solution: dynamic programming
Given that we have on the order of thousands of windows, there is no need to settle for a heuristic. Dynamic programming finds the subset whose sum is as close as possible to the target without trying every combination (with the 231 recordings of the “one person” class there would be , a 70-digit number).
Let us recall what we are looking for: within each class, choose which recordings go to test, so that all their windows add up to 30 % of the class total. All the others go to train. Each recording goes entirely to one partition or the other, so the problem is to choose a subset of recordings: that subset is test and the rest is train.
The idea is to go through the recordings one at a time and keep track of which sums can be made with the recordings seen so far. At the start, with no recordings, the only possible sum is 0. Each time a recording of windows is added, the possible sums become the ones we already had (if we do not take it) plus those same sums increased by (if we take it). It does not matter which combination led to each sum, only whether it can be reached, and that is what avoids the combinatorial explosion: the table has (number of groups + 1) × (total + 1) cells and each one is computed only once.
A small example makes it clearer. Suppose a class with five recordings, A to E, of 4, 3, 6, 2 and 5 windows. The total is 20 and the target for test is 6 windows (30 %). The reachable sums grow like this:
- no recordings: {0};
- with A (4): {0, 4};
- with B (3): the previous ones, plus the previous ones + 3 → {0, 3, 4, 7};
- with C (6): {0, 3, 4, 6, 7, 9, 10, 13};
- and the same with D and E.
In the figure each row is one of those steps, and each blue cell is a reachable sum. A recording appearing in a row does not mean it goes to test: it means it has already been taken into account, whether taken or not. At this stage nothing has been decided yet; the table only says which sums are possible. In row C the 6 already appears: there is at least one combination that adds up exactly to the target.

The table says that 6 can be reached, but not with which recordings. To find out, we go through it backwards, starting from the last row and the target sum. In each row there are two options: if the same sum was in the row above, it can be reached without that row’s recording (vertical arrow); if the sum minus the recording’s size was in the row above, it can be reached by taking it (diagonal arrow, which subtracts its size). In the example, E cannot be taken (6 − 5 = 1 is not reachable without it), so we go straight up. In row D both options work: without D, the 6 comes from taking C; with D, we need to reach 4 with A, B and C. When both options are possible, the code picks one at random. In the figure D was taken, and the path ends up taking A as well. The recordings the path takes go to test and the ones it skips go to train: test gets A and D (4 + 2 = 6 windows, 30 %) and train gets B, C and E (3 + 6 + 5 = 14 windows, 70 %).
If in row D the random choice had been not to take it, the result would be different. The path goes straight up to row C, and there the only option is to take C (6 cannot be reached without it, and 6 − 6 = 0 can). From there on, it only goes straight up, because the sum is already 0. Test gets only C (6 windows) and train gets A, B, D and E (4 + 3 + 2 + 5 = 14 windows). Both splits meet the 30/70 exactly; which one comes out depends on chance, and that is why different seeds give different splits.

In the code, the table is a boolean matrix reach, where reach[i, s] says whether some
combination of the first i recordings adds up exactly to s. Adding a recording is a
single line: the new row is the previous one, combined (with an OR) with the same row
shifted by w positions. Then the reachable sum closest to the target is chosen (the target
itself may not be exactly reachable) and the subset is reconstructed backwards:
def subset_sum_optimal(sizes, target, rng): """Indices of a subset whose sum is the closest to target.""" sizes = np.asarray(sizes) n, K = len(sizes), int(sizes.sum()) reach = np.zeros((n + 1, K + 1), dtype=bool) reach[0, 0] = True # with no groups, only 0 is reachable for i, w in enumerate(sizes, start=1): reach[i] = reach[i - 1] # without taking group i reach[i, w:] |= reach[i - 1, :K + 1 - w] # taking it: everything shifted by w sums = np.flatnonzero(reach[n]) gap = np.abs(sums - target) s = rng.choice(sums[gap == gap.min()]) # best reachable sum chosen = [] for i in range(n, 0, -1): # backward reconstruction w = sizes[i - 1] can_skip = reach[i - 1, s] # vertical arrow can_take = s >= w and reach[i - 1, s - w] # diagonal arrow if can_take and (not can_skip or rng.rand() < 0.5): chosen.append(i - 1) s -= w return chosenFor each class the groups are shuffled, this function is called with
target = 0.3 * total and the chosen groups go to test. Shuffling the order of the groups
and choosing at random during the reconstruction makes each seed give a different split.
The result is as close to 30 % as the numbers allow: the maximum deviation was 0.05 points in all
classes, including the tracked vehicle class (29.95 %), and each full split of the 6 classes
takes about 0.1 s.
There is a detail I did not expect, and the example already shows it: the target can be reached with C alone (one large recording) or with A and D (two smaller ones). For a class with many groups there is usually a huge number of subsets that give the optimal sum, and the way one of them is chosen is not neutral. There are many more optimal combinations with many small groups than with a few large ones, so small groups end up in test more often: the shortest 10 % of the recordings end up in test 40 % of the time instead of 30 %. I also tried sampling uniformly among all the optimal subsets, by counting the solutions in the table, and the bias was even larger.
The solution is to ask one more thing of the subset: that it also contain 30 % of the groups. If test has 30 % of the windows and 30 % of the groups, the mean size of its groups has to be the same as that of the class, and the advantage of the small ones disappears. In the example, 30 % of 5 recordings, rounded, is 2, so only the A + D solution remains: C alone has the right sum, but it is a single group.
In dynamic programming terms, that means adding a dimension to the table: the number of
chosen groups. Each cell reach[i, k, s] now says whether the sum s can be reached using
exactly k of the first i recordings. It is like having a table like the one in the
figure for each value of k, and taking a recording means moving one position in k and w
positions in s at the same time:
# reach[i, k, s]: k of the first i groups add up exactly to sreach = np.zeros((n + 1, m + 1, S), dtype=bool)reach[0, 0, 0] = Truefor i, w in enumerate(sizes, start=1): reach[i] = reach[i - 1] reach[i, 1:, w:] |= reach[i - 1, :-1, :S - w]with m = round(0.3 * n) and S just above the target, because there is no need to record
larger sums. The reconstruction is the same, keeping track of k. With this constraint the
per-class fraction is still practically equal to the target (the tracked vehicle class ends up at 30.4 %),
the probability of ending up in test is fairly even (between 0.27 and 0.34 in all size
deciles), and the time does not change: about 0.1 s.

How much does leakage matter?
Everything so far is about how to build the split. The underlying question remains: how much do the performance metrics change if the split is done wrong? To measure it I trained pollito, the convolutional network from the thesis (about 4 M parameters), with three different splits, and repeated everything with 5 seeds.
Here is a bit of the process. First I set aside 20 % of the recordings of each class as an
external set, used for nothing but measuring at the end. With the remaining 80 % I built
three 70/30 splits: by frames, with stratified train_test_split; by time, cutting each
recording and sending one portion to test (about 12 % of the windows are lost, those that
cross the cut); and by recordings, with the dynamic programming method with a fixed number
of groups. The model was trained for 40 epochs, without early stopping and without choosing
weights by looking at test.
The results, as per-window accuracy (mean and range over the 5 seeds):
| Split | Internal test | Never-seen recordings | Difference |
|---|---|---|---|
| By frames | 96.5 % (95.2–97.3) | 88.5 % (86.0–91.5) | 8.0 points (5.4–10.2) |
| By time | 86.6 % (80.6–90.2) | 83.0 % (77.1–88.3) | 3.6 points (1.8–5.7) |
| By recordings | 87.6 % (86.4–89.4) | 87.2 % (82.3–89.9) | 0.4 points (−0.9–4.1) |

With the split by frames, the internal test says something close to 96 %. On recordings the model never saw, the real number is around 88 %. The difference, about 8 points, is exactly what leakage adds: the model recognizes windows almost identical to the ones it saw during training. With the split by recordings, on the other hand, the internal test and the external set give practically the same result, which is what we expect from a good estimate.
The time cut sits in between. Removing the overlap eliminates most of the leakage, but not all of it: the internal test still promises about 3.6 points more than what the model achieves on new recordings, and that difference shows up in all 5 seeds. This is what the similarity between windows anticipated: a portion of the same recording a few seconds later is not a duplicate, but it is more similar than any other recording. This model also did somewhat worse on new recordings (83.0 %), partly because it trains on fewer windows and partly because of two seeds that came out quite a bit lower.
What surprised me was the other comparison. On new recordings, the model trained with the split by frames did not do worse than the other one (88.5 % versus 87.2 %, a difference smaller than the variation between seeds). It makes sense: by splitting windows, that model gets to see at least part of almost every recording, and it trains on more variety. In other words, leakage did not make the model worse, it made the measurement of its performance worse. And that is more serious than it seems, because the measurement is what we use to compare alternatives, choose hyperparameters and decide whether the system is ready.
There is one more thing worth looking at: with the correct split, the result on never-seen recordings ranged from 82 % to 90 % depending on the seed, that is, depending on which recordings landed in each set. With 569 recordings, a single split can move the result by several points. That is why it is worth repeating with several seeds, and for that the splitting method needs to produce different splits with each seed.
Comparison and recommendations
Results on this dataset (coronita, 6 classes), with 100 seeds per method. “Test per class” is the test fraction in each class, with its worst deviation; “Tracked” is that fraction for the class with 9 recordings; “Longest 10 %” is the fraction of times those recordings end up in test, not counting the noise class (ideally 0.30). The optimal version without the count constraint over-represents the shortest recordings (0.40); StratifiedGroupKFold was used by joining 3 of 10 folds.
| Method | Test per class | Tracked | Longest 10 % | Leakage |
|---|---|---|---|---|
| By frames, at random | 0.30 | 0.30 | — | yes: 557 of 569 rec. |
| GroupShuffleSplit | 0.30 ± 0.54 | 0 to 0.84 | 0.29 | no |
| StratifiedGroupKFold | 0.30 | 0.415 | 0.33 | no |
| Greedy with dummy | 0.30 | 0.315 | 0.00 | no |
| Optimal | 0.30 ± 0.0005 | 0.2995 | 0.29 | no |
| Optimal, fixed recording count | 0.30 ± 0.004 | 0.304 | 0.32 | no |

My recommendations, then:
- Never split at random data that comes from the same domain sample. It is the only mistake on this list that invalidates the evaluation: in this case, the test set promised about 8 points more than what the model achieved on new recordings.
- Cutting each group in time and separating the portions removes the duplicates, but it is not enough if in production the whole group will be new: here the test stayed inflated by about 3.6 points. It only makes sense when the model will work on the same individuals it saw (for example, predicting the future of a machine it already knows).
- If groups have a single class and the per-class totals are in the thousands of examples, the optimal solution with a fixed number of groups gives proportions practically equal to the target, without size bias, in a fraction of a second.
- For cross-validation, or if groups have several classes,
StratifiedGroupKFoldis the natural option. It is worth checking classes with few groups by hand. - If the totals are too large for dynamic programming (hundreds of thousands of examples per class), a greedy heuristic is still reasonable, but it is worth checking how the large groups were distributed.
- In any case, measure on your own dataset the same things as in this article: the fractions per class and in which partition the groups end up according to their size. It takes two lines of pandas and avoids surprises.
Closing
Solving this problem does not require a complicated algorithm. What matters is not to confuse the training data with the domain samples it comes from, to decide which unit will be new in production, and to choose the tool according to the size and structure of the groups. To go further into partitioning into more than two sets, the Karmarkar–Karp heuristic [6] and optimal algorithms for multi-way partitioning [7] are good starting points.
The previous article of the series, From the raw signal to a real-time classifier, explains how this split was used within the complete work.
Data
The original dataset is “The Database of Radar Echoes from Various Targets”, from the Signal Processing Laboratory of Ben-Gurion University of the Negev [8]; the windows and spectrograms are the ones generated in the thesis [1].
This article was originally written by me in Spanish and translated into English using the Claude Opus 5.5 model (Anthropic).
References
- Alcaraz, F. A. (2026). Classification of Doppler Signals from Radar Echoes Using Deep Learning. Master's thesis in Engineering, revised English edition, Instituto Balseiro, Universidad Nacional de Cuyo. https://doi.org/10.5281/zenodo.23227057 ↩
- Kaufman, S., Rosset, S., Perlich, C., & Stitelman, O. (2012). Leakage in data mining: formulation, detection, and avoidance. ACM Transactions on Knowledge Discovery from Data, 6(4). ↩
- Roberts, D. R., et al. (2017). Cross-validation strategies for data with temporal, spatial, hierarchical, or phylogenetic structure. Ecography, 40(8), 913–929. ↩
- Garey, M. R., & Johnson, D. S. (1979). Computers and Intractability: A Guide to the Theory of NP-Completeness. W. H. Freeman. ↩
- scikit-learn (n.d.). StratifiedGroupKFold: documentation and source code of version 1.9.1. https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.StratifiedGroupKFold.html ↩
- Karmarkar, N., & Karp, R. M. (1982). The differencing method of set partitioning. Technical Report UCB/CSD 82/113, University of California, Berkeley. ↩
- Korf, R. E. (2009). Multi-way number partitioning. Proceedings of IJCAI. ↩
- Signal Processing Laboratory, Ben-Gurion University of the Negev (n.d.). The Database of Radar Echoes from Various Targets. http://www.ee.bgu.ac.il/~spl/ ↩
- Alcaraz, F. A. (2020). Clasificación de Señales Doppler de Ecos Radar usando Deep Learning. Master's thesis in Engineering (original Spanish version), Instituto Balseiro, Universidad Nacional de Cuyo. https://doi.org/10.5281/zenodo.23226363