Implement a Stratified K-Fold Cross-Validation Splitter From Scratch
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `stratified_kfold_split(y, n_splits=5, shuffle=False, random_state=None)` using only NumPy. Given a 1-D label array `y`, return a list of `n_splits` tuples `(train_indices, val_indices)` whose validation folds preserve class proportions.
The folds must follow these rules:
- Process classes in ascending `np.unique(y)` order. Within a class, take indices in input order, or (if `shuffle=True`) `rng.permutation` of them, using one `rng = np.random.default_rng(random_state)` consumed class by class.
- A class with `n_c` samples gives `n_c // n_splits` to every fold, plus one extra to `r = n_c % n_splits` folds chosen round-robin from a running offset (starts at 0, advances by `r` mod `n_splits` after each class).
- Deal each class's members contiguously to folds `0..n_splits-1` with those sizes.
- Both index arrays are integer and sorted ascending. `train` is the complement of `val`.
- Raise `ValueError` if any class has fewer than `n_splits` samples, `n_splits < 2`, or `y` is not 1-D.
For example:
```python
y = [0, 0, 0, 0, 0, 1, 1, 1, 1]
splits = stratified_kfold_split(y, n_splits=3)
# class 0: sizes [2, 2, 1] (offset -> 2), class 1: sizes [1, 1, 2]
# val folds: [0, 1, 5], [2, 3, 6], [4, 7, 8]
# splits[0] == (array([2, 3, 4, 6, 7, 8]), array([0, 1, 5]))
```
```hint One class at a time
Treat each class as its own small k-fold problem. The only state that carries over from one class to the next is the offset where its extra samples start, plus the random generator when shuffling.
```
```hint Reproducibility
The expected output depends on the exact order of random draws. One generator, created once and used class by class in ascending label order, is the only way to match it.
```
### Constraints & Assumptions
- Labels may be any sortable type (ints, strings).
- `1 <= len(y) <= 10**5`.
- Use only NumPy.
### What a Strong Answer Covers
- All three `ValueError` cases, checked before any folds are built.
- Per-class fold sizes and the remainder offset, following the round-robin rule exactly.
- Shuffling that is reproducible for a given `random_state` and matches the stated draw order.
- Sorted integer train and validation arrays, with every index validated exactly once and train equal to the complement of validation.
- The time and space cost, including how it grows with the number of classes.
### Follow-up Questions
- Why rotate the remainder offset across classes instead of always starting at fold 0?
- How would you stratify when samples belong to groups that must not be split across folds?
- How would you adapt this for a continuous regression target?
Overview: Implement a stratified k-fold cross-validation splitter in NumPy that keeps class proportions in every validation fold and follows a fixed round-robin rule for leftover samples. It tests per-class fold sizing, reproducible shuffling with one shared generator, and sorted train and validation index arrays.