Leak-Free Out-of-Fold Predictions for Stacking
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement four functions that build contiguous k-fold splits, validate them against self-prediction, produce out-of-fold (OOF) predictions with a `StandardScaler` + `Ridge` pipeline, and compare per-fold versus pooled MSE. OOF predictions like these are what a stacking meta-learner trains on, so each one must come from a model that never saw its row.
Requirements:
- `kfold_indices(n_samples, n_splits)` returns a list of `(train_idx, val_idx)` int arrays, contiguous in input order, where the first `n % k` folds get one extra row (this matches `KFold` without shuffle). Raise `ValueError` unless `2 <= n_splits <= n_samples`.
- `assert_no_self_prediction(folds, n_samples)` raises `ValueError` if any validation row is in its own train set, or if rows are not predicted exactly once (missing, duplicate, or out of range).
- `out_of_fold_predictions(X, y, n_splits=5, alpha=1.0)` fits the scaler and `Ridge(alpha)` on the train rows only, per fold. It returns `(oof, fold_id)`: float64 predictions and the int64 fold index `0..k-1` of each row.
- `compare_fold_and_pooled_metrics(y, oof, fold_id)` returns a DataFrame with int64 `fold`, int64 `n_val` and float64 `mse` columns (sorted by fold), and a dict with `mean_fold_mse`, `weighted_fold_mse` (weighted by `n_val`) and `pooled_mse` as floats.
Example:
```python
kfold_indices(10, 3) # validation blocks: [0, 1, 2, 3], [4, 5, 6], [7, 8, 9]
y = np.arange(10, dtype=float)
oof = y + np.array([1, 1, 1, 1, 2, 2, 2, 0, 0, 3], dtype=float)
fold_id = np.array([0, 0, 0, 0, 1, 1, 1, 2, 2, 2])
table, summary = compare_fold_and_pooled_metrics(y, oof, fold_id)
# table: fold=[0, 1, 2], n_val=[4, 3, 3], mse=[1.0, 4.0, 3.0]
# summary: mean_fold_mse=8/3, weighted_fold_mse=2.5, pooled_mse=2.5
```
```hint Counting coverage
One array of per-row counts, updated once per validation fold, answers both the missing and the duplicate checks. Think about what NumPy does with a negative index before you update it.
```
```hint Two averages
Write the pooled MSE as a sum over folds of each fold's squared-error total, then compare that expression with each of the two fold averages.
```
### Constraints & Assumptions
- `X` is numeric with shape `(n_samples, n_features)` and `y` is a numeric vector of length `n_samples`, with no missing values.
- `assert_no_self_prediction` accepts folds from any splitter, so it cannot assume they came from `kfold_indices`.
- Rows stay in input order. Shuffling is out of scope.
### What a Strong Answer Covers
- Folds that match unshuffled `KFold`, including uneven sizes and the `ValueError` bounds.
- A validator that catches train and validation overlap, missing rows, duplicated rows and out-of-range validation indices.
- Scaler and ridge fitted on training rows only, with predictions and fold ids written to the right positions in the right dtypes.
- The per-fold table and the three summary numbers, with a reason why the size-weighted mean equals the pooled MSE and the simple mean does not.
### Follow-up Questions
- How would you turn these OOF predictions into a stacking meta-learner without leakage?
- Why can the simple mean of fold MSEs differ from the pooled MSE?
- What changes for time-series or grouped data?
Overview: Build contiguous k-fold splits, validate that no row is predicted by a model trained on it, generate out-of-fold ridge predictions for stacking, and compare per-fold, size-weighted and pooled MSE. It tests leak-free cross-validation and why fold averages and pooled errors can differ.