Stratified Cross-Validation With Train-Fold Oversampling
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement three functions that run stratified k-fold cross-validation on an imbalanced classification dataset. Oversample only the training fold, then score a logistic regression on the untouched validation fold.
- `stratified_fold_assignments(y, n_splits)` returns a fold id for every sample.
- `oversample_indices(train_idx, y, rng)` returns the training indices with the minority classes randomly oversampled.
- `oversampled_cv(X, y, n_splits=5, C=1.0, seed=0)` runs the cross-validation and returns a per-fold results `DataFrame`.
The functions must follow these rules exactly:
- Folds (no shuffle): for each class in ascending label order, cut its sorted indices into `n_splits` contiguous chunks. The first `n_c % n_splits` chunks get one extra sample, and chunk `f` goes to fold `f`. Return an `int64` array.
- Oversampling: the output is the sorted `train_idx`, followed, for each class whose count is below the majority count `M` (in ascending label order), by `rng.choice(class_idx, size=M - n_c, replace=True)` drawn over that class's sorted training indices.
- CV: create one `np.random.default_rng(seed)` and share it across folds 0 to k-1 in order, with fold `f` as the validation fold.
- Per fold: fit `StandardScaler` on the resampled training rows, then `LogisticRegression(C=C, solver="lbfgs", max_iter=1000)`. Accuracy is computed on the validation fold.
- The output columns are `fold`, `n_train`, `n_val` and `accuracy`. The first three are `int64` and `accuracy` is `float64`. `n_train` is the size after resampling.
Example:
```python
stratified_fold_assignments(np.array([0,0,0,0,0,0,0,1,1,1]), 3)
# -> [0, 0, 0, 1, 1, 2, 2, 0, 1, 2]
```
Class 0 has 7 samples, so its chunks have sizes 3, 2 and 2. Class 1 has 3 samples, one per fold.
```hint Fold sizes
`divmod(n_c, n_splits)` gives the base chunk size and the number of chunks that need one extra sample.
```
```hint Reproducible draws
The tests replay your generator calls. Check which generator you use, the order of the `rng.choice` calls across folds and classes, and whether the pool you draw from is sorted.
```
### Constraints & Assumptions
- `X` is a numeric 2D array of shape (n_samples, n_features) and `y` is a 1D array of class labels of length n_samples.
- `numpy`, `pandas` and `scikit-learn` are available.
- Tests reproduce your exact RNG draws, so the order and arguments of every `rng.choice` call matter.
### What a Strong Answer Covers
- Fold assignment that matches the contiguous per-class chunking, with the remainder going to the earliest folds.
- Oversampling that touches only training indices, draws from each class's sorted training pool, and makes its draws in the specified order.
- One generator shared across all folds, so the draws are reproducible.
- Scaler and model fitted on the resampled training rows only, with the validation rows transformed by that scaler and scored without resampling.
- The exact output columns and dtypes, with `n_train` counting the resampled rows.
### Follow-up Questions
- Why is oversampling before splitting a leakage bug?
- Is accuracy a good metric here? What would you report instead?
- How would you swap in SMOTE or class weights?
- What happens when a class has fewer samples than `n_splits`?
Overview: Implement stratified k-fold cross-validation that oversamples minority classes inside each training fold only, then scores a scaled logistic regression on the untouched validation fold. It tests exact fold assignment, reproducible random draws and how to keep resampling and scaling from leaking into validation.