Stratified Split: Every Class Keeps Its Share

Data ProcessingMedium+15 XP+15

Stratified Split: Every Class Keeps Its Share

Split a dataset at random and you can get unlucky: a rare class ends up entirely in the training set, so the test set can never tell you whether the model handles it. A stratified split prevents that by splitting each class separately, so every class keeps the same proportion on both sides.

So there's no randomness to argue about, use this exact rule:

  • Walk the labels and group the positions by class, keeping each class's positions in the order they appear.
  • For a class with c examples, the first ceil(c × test_ratio) of its positions go to the test set. The rest go to training.

Task: write stratified_split(labels, test_ratio) returning [train_indices, test_indices] — two lists of positions, each sorted ascending.

  • labels is a list of class labels (strings or numbers), never empty.
  • test_ratio is between 0 and 1.
  • Use ceil, rounding up. A class with 3 examples and a ratio of 0.4 sends 2 to test, not 1 — rounding up is what guarantees a one-example class still shows up in the test set at all.
  • Every position appears in exactly one of the two lists.

Notice what this buys you: the test set's class mix matches the full dataset's, so test accuracy means the same thing it would in production.

Examples

labels = ['a', 'a', 'a', 'a', 'b', 'b']
test_ratio = 0.5
returns [[2, 3, 5], [0, 1, 4]]
labels = ['x', 'x', 'y', 'y', 'y']
test_ratio = 0.4
returns [[1, 4], [0, 2, 3]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run