Stratified Group K-Fold Splitter
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: hard
Interview Round: Other
Given labels `y` and `groups`, implement `assign_folds(y, groups, n_splits=5)`, which returns each sample's fold id, and `stratified_group_kfold(y, groups, n_splits=5)`, which returns a list of `(train_idx, test_idx)` tuples in fold order with ascending integer indices. Every group lands in exactly one fold, and the output must match scikit-learn's `StratifiedGroupKFold(shuffle=False)`.
Requirements:
- Classes and groups are indexed in `np.unique` (sorted) order. Build a per-group class-count matrix.
- Visit groups by decreasing population std of their class counts (stable sort: ties keep sorted-group order).
- Place each group in the fold that minimises the mean over classes of the std across folds of `fold_class_count / total_class_count`.
- Near ties (`np.isclose`) go to the fold with fewer samples, then to the lowest fold index.
- Raise `ValueError` if `n_splits < 2`, if the shapes mismatch, or if there are fewer distinct groups than `n_splits`.
Example:
```python
y = ['cat','dog','cat','dog','cat','cat','dog','dog','cat','dog','cat','dog']
groups = ['a','a','b','b','c','c','d','d','e','e','f','f']
assign_folds(y, groups, n_splits=3)
# -> [2, 2, 0, 0, 0, 0, 1, 1, 2, 2, 1, 1]
```
Both samples of each group share a fold. Fold 0 (groups b and c) ends up with 3 cats and 1 dog, fold 1 (groups d and f) with 1 cat and 3 dogs, and fold 2 (groups a and e) with 2 of each. The greedy places one group at a time and does not search for the most balanced split, which here would give 2 and 2 in every fold.
```hint Work at the group level
Represent each group as a vector of class counts. A group-by-class matrix lets you score a placement without touching individual samples.
```
```hint Visit order
The default `np.argsort` algorithm is not stable, and groups with equal std must keep their sorted-group order.
```
```hint Tie-breaks
Walk the folds in index order and compare each candidate with the best fold found so far, the way a running minimum works.
```
### Constraints & Assumptions
- `y` and `groups` are 1-D, have equal length, and may hold ints or strings.
- No shuffling: the output is deterministic.
### What a Strong Answer Covers
- A group-by-class count matrix with classes and groups encoded in sorted order.
- The stable visit order by decreasing population std of each group's class counts.
- The placement score and the near-tie rule (fewer samples, then lowest index), applied exactly the way scikit-learn applies them.
- Input validation for `n_splits`, the shapes and the number of distinct groups.
- Mapping group folds back to samples and building sorted train and test index arrays in fold order, with no group split across folds.
### Follow-up Questions
- Why must a group never be split across folds, and what happens to the validation score if it is?
- How would you add shuffling while keeping the folds reproducible?
- When a few very large groups make the classes impossible to balance, what would you report or change?
- How does this greedy compare with solving the balance objective exactly?
Overview: Implement a deterministic stratified group k-fold splitter that keeps every group in a single fold while balancing class proportions across folds, matching scikit-learn's unshuffled StratifiedGroupKFold. It tests greedy placement, stable ordering, exact tie-breaking and leakage-free validation design.