v9.1.1
Menu

Stratified Train-Test Split

mediumFREEModel EvaluationMachine Learning 1

Implement stratified train-test split that preserves the class distribution in both sets.

Given data indices and their labels, split into train and test sets such that each set has approximately the same proportion of each class.

For each unique label, assign floor(count * train_ratio) samples to training and the rest to test (using the original order of indices within each class).

Return a tuple (train_indices, test_indices) where both lists are sorted.

Example

Input
labels = [0, 0, 0, 0, 1, 1, 1, 1, 1, 1]
train_ratio = 0.5
Output
([0, 1, 4, 5, 6], [2, 3, 7, 8, 9])
Reasoning
  • labels gives one class per data point; position ii in the list is data point ii. Here points 00–33 are class 0 and points 44–99 are class 1 — a 40%40\% / 60%60\% mix.
  • train_ratio =0.5= 0.5 is applied to each class separately. Class 0: ⌊4×0.5⌋=2\lfloor 4 \times 0.5 \rfloor = 2 points go to training. Class 1: ⌊6×0.5⌋=3\lfloor 6 \times 0.5 \rfloor = 3 points go to training.
  • Within a class, the earliest points are the training ones: points 0,10, 1 from class 0 and 4,5,64, 5, 6 from class 1. The rest (2,32, 3 and 7,8,97, 8, 9) becomes the test set.
  • Both sets are reported in ascending order, giving ([0, 1, 4, 5, 6], [2, 3, 7, 8, 9]).
  • Notice the training set is 22 of class 0 and 33 of class 1: still 40%40\% / 60%60\%, the same mix as the full data. Because of the floor, an odd class size (e.g. 55 at ratio 0.50.5) sends the extra point to test.

Constraints

  • labels: list of class labels (integers)
  • train_ratio: float between 0 and 1
  • Return tuple of two sorted lists of indices
  • Preserve class proportions as closely as possible

Learn this in

More from Machine Learning 1

solution.py

Test results

Sign in to run your code against the test cases.