WRITE · TRACE · UNDERSTAND

Split identities before splitting examples

Implement group_folds(groups,k) returning k lists of row indices.

Read lesson: Split identities before splitting examples →

Your experiment

Implement group_folds(groups,k) returning k lists of row indices. Sort distinct group names and assign group number modulo k. Require 2<=k<=number of distinct groups.

Python runs in your browser. Your draft stays on this device.

What to look for

The split unit should match the deployment question. Group separation estimates new-group performance; it does not estimate future drift within groups, so a time-aware design may also be required.

Watch your code work

Ready to experiment

Write a solution or load the worked answer, then choose Trace & check.

Step through arrays, variables and training curves produced by your own Python.

About this algorithm

How Split identities before splitting examples works

The idea

Rows that share an identity, such as several records from one patient or several sentences from one author, are not independent. If some of them land in training and others in validation, a model can score well by recognising the identity instead of learning the task, and the validation score overstates what happens on new identities.

group_folds(groups, k) therefore splits the identities, not the rows. It sorts the distinct group names, gives the group at position i to fold i % k, and then sends every row to the fold of its group. All rows of a group stay together, at the price of folds whose row counts can be uneven.

How it works

  1. Collect the distinct group names and sort them, so the assignment does not depend on row order.
  2. Raise ValueError unless k is at least 2 and no larger than the number of distinct groups.
  3. Map each group to a fold with i % k, where i is its position in the sorted names.
  4. Walk the rows in order and append each row index to the fold of its group.
  5. Return the k lists of row indices, one list per fold.

What it costs

Time
O(n + g log g)
Space
O(n + g)

Sorting the g distinct group names dominates the setup, and each of the n rows is then placed with one dictionary lookup.

Where it is used

  • scikit-learn's GroupKFold guarantees that the same group never appears in two different folds.
  • The CheXNet chest X-ray paper split its data by patient, so no patient's images appear in both the training and test sets.
  • LibriSpeech keeps the speakers in its training, development and test sets disjoint, so recognition is tested on unheard voices.

Watch out for

  • Shuffling and splitting rows directly, which scatters one identity across training and validation and inflates the validation score.
  • Assigning folds in order of first appearance instead of sorted name, so the split changes whenever the rows are reordered.
  • Expecting equal fold sizes: a group with many rows makes its fold larger, because rows follow their group.