Out-of-Fold Predictions for Stacking
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
In stacking, a meta-model is trained on the predictions of several base models. Those predictions have to come from models that never saw the row they predict, otherwise the meta-model learns from leaked labels.
Implement `kfold_indices(n_samples, n_splits, shuffle=False, random_state=None)`, which returns a list of `(train_idx, val_idx)` pairs, and `oof_predictions(estimators, X, y, X_test, n_splits=5, shuffle=False, random_state=None, method="predict")`, which returns `(oof_matrix, test_matrix)` of shapes `(n, m)` and `(n_test, m)`, one column per estimator.
The functions must follow these rules:
- Folds are contiguous blocks of `np.arange(n_samples)`, or of `np.random.default_rng(random_state).permutation(n_samples)` when `shuffle=True`. The first `n_samples % n_splits` folds get one extra sample.
- Both index arrays are sorted ascending. An `n_splits` outside `[2, n_samples]` raises `ValueError`.
- For each fold and estimator, fit a fresh `clone` on the training rows and write its validation predictions into the OOF matrix at the rows' original indices.
- The test column is the mean of the `n_splits` fold models' predictions on `X_test`.
- With `method="predict_proba"`, use column `1` (the positive class). Both outputs are float arrays.
Example:
```python
kfold_indices(11, 4)
# validation folds: [0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10]
# each training set is all remaining indices, sorted
```
Here `11 % 4 = 3`, so the first three folds hold 3 samples and the last one holds 2.
```hint Fold sizes
Work out the size of every fold before slicing anything: integer division gives the base size, and the remainder tells you how many folds get one more.
```
```hint Row alignment
After shuffling, a validation fold is scattered across the rows of `X`. Think about where each prediction has to be written so it still lines up with the matching entry of `y`.
```
### Constraints & Assumptions
- Estimators follow the scikit-learn API (`fit`, `predict`, `predict_proba`), and `sklearn.base.clone` is available.
- Do not use the splitters in `sklearn.model_selection`.
- `n_splits` must be between 2 and `n_samples` inclusive.
- `method="predict_proba"` is for binary classification, where column 1 is the positive class.
### What a Strong Answer Covers
- Fold construction that matches the rules exactly: remainder samples in the first folds, sorted index arrays, and a `ValueError` for an invalid `n_splits`.
- Why each training row must be predicted by a model that never saw it, and how the code makes sure every OOF row is written exactly once.
- A fresh clone for every fold and estimator, so no fitted state carries over between folds.
- Writing predictions back by original row index, so the OOF matrix stays aligned with `y` when the order is shuffled.
- How the test matrix is built from the fold models, and the total cost in model fits.
### Follow-up Questions
- How would you adapt the splitter to stratified folds for imbalanced classification?
- Why average the fold models' predictions on the test set instead of refitting each base model on all of the training data?
- How would you support multiclass `predict_proba`?
Overview: Implement a K-fold splitter and an out-of-fold prediction routine that builds leakage-free meta-features for a stacking ensemble. It tests fold construction, row alignment after shuffling, estimator cloning, and how test-set meta-features are averaged across the fold models.