Stratified Train/Test Split

medium
Checkpoint challenge
Solve this to show you know the material and jump straight to Unit 15. Everything before it counts as cleared.

With imbalanced data, say 5% fraud, a random split can leave the test set with almost no positives. A stratified split keeps each class's proportion the same in train and test.

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

  • For each class (in sorted order), take that class's indices and shuffle them with one shared rng = np.random.default_rng(seed), calling rng.permutation once per class in class order.
  • Put the first round(n_class * test_size) shuffled indices in the test set and the rest in train. Python's round is fine.
  • Every index ends up in exactly one of the two sets.
#sampling#evaluation#numpy2 visible + 2 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Stratified Train/Test Split · TechGradify