Stratified Train/Test Split

medium
Unit 17 · Data Splitting0/3 to milestone

A random split can leave a rare class missing from the test set. A stratified split keeps each class's share the same in both parts.

Implement stratified_split(y, test_size, seed=0) returning (train_idx, test_idx) as sorted integer arrays:

  • for each class, shuffle its indices with np.random.default_rng(seed) and put round(test_size * count) of them in the test set
  • every index appears in exactly one of the two arrays
#data-splitting#validation#imbalance2 visible + 1 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Stratified Train/Test Split · TechGradify