Split a dataset so every class keeps its share

With rare classes, a random split can put almost none of them in the test set. A stratified split takes the same fraction from every class.

Write stratified_split(labels, test_frac). For each class, in order of first appearance, take its indices in their original order and put the LAST round(count * test_frac) of them in the test set. Return (train_idx, test_idx) as sorted lists of ints.

Use Python's round (banker's rounding is fine).

Signaturedef stratified_split(labels, test_frac)

Understand the idea

A stratified split takes the same fraction of every class for the test set, so rare classes are not lost by chance. Like picking a class representative from each section rather than drawing names from one hat. Group indices by class in order of first appearance. From each group, keeping original order, send the last round(count x test_frac) indices to test and the rest to train. Worked example: labels [a, a, a, a, b, b], test_frac 0.5. Class a has indices [0, 1, 2, 3]; round(2.0) = 2, so 2 and 3 go to test. Class b has [4, 5]; round(1.0) = 1, so 5 goes to test. Test = [2, 3, 5], train = [0, 1, 4], both sorted. Note Python's round uses banker's rounding: round(2.5) is 2 and round(0.5) is 0. Rule: per class, test gets the last round(n_c x frac) indices. Imbalanced problems like fraud detection rely on stratified splits.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: imbalancedstratified_split(['a'] * 8 + ['b'] * 2, 0.5)
  • Sample 2: interleavedstratified_split([0, 1, 0, 1, 0, 1, 0, 1], 0.25)
  • Test 3: zero test fractionstratified_split([1, 2, 3], 0.0)