Two-Tier Stacking With Shared Folds
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: hard
Interview Round: Other
Implement `out_of_fold_predictions(estimators, X, y, folds)` and a regressor `TwoTierStacker(level1, level2, final_estimator, folds, passthrough=False)` that stacks two levels of base models under a final estimator. `level1` and `level2` are lists of regressors, and the class exposes `fit(X, y)` (returning `self`) and `predict(X)`. Both levels must use the same per-row `folds` labels, so no row's out-of-fold prediction at either level comes from a model that was trained on that row.
The code must meet these requirements:
- `out_of_fold_predictions` returns a float array of shape `(n_samples, n_estimators)`. For each distinct fold label, fit a `clone` of each estimator on all other folds and predict the held-out rows. Label values are arbitrary.
- Raise `ValueError` if `folds` does not have shape `(n_samples,)` or has fewer than 2 distinct labels.
- `fit` sets `level1_oof_` (OOF predictions on `X`), `level2_oof_` (OOF predictions on the level-2 input, same folds) and `final_estimator_`, which is fit on `level2_oof_`.
- The level-2 input is `level1_oof_`, or `np.hstack([level1_oof_, X])` when `passthrough=True`. `level1_estimators_` and `level2_estimators_` are clones refit on the full `X` and the full level-2 input, respectively.
- `predict` chains the full refits (level 1, optional passthrough, level 2, final estimator) and returns a 1-D float array.
Estimators are scikit-learn regressors. Never fit the passed-in instances directly; use `sklearn.base.clone`.
For example, with a regressor that predicts the mean of its training targets:
```python
import numpy as np
from sklearn.base import BaseEstimator, RegressorMixin
class MeanRegressor(BaseEstimator, RegressorMixin):
def fit(self, X, y):
self.mean_ = float(np.mean(y))
return self
def predict(self, X):
return np.full(len(X), self.mean_)
X = np.arange(12.0).reshape(6, 2)
y = [1, 2, 3, 4, 5, 6]
folds = [0, 0, 1, 1, 2, 2]
out_of_fold_predictions([MeanRegressor()], X, y, folds)
# -> [[4.5], [4.5], [3.5], [3.5], [2.5], [2.5]]
```
Rows 0 and 1 (fold 0) are predicted by a model trained on targets 3, 4, 5 and 6, whose mean is 4.5. Folds 1 and 2 give 3.5 and 2.5 the same way.
```hint One helper, used twice
Write the out-of-fold routine so it accepts any feature matrix. Level 2 is the same routine applied to a different input with the same fold labels.
```
```hint Fold labels
Validate the labels before any fitting, and pick a fold's rows by comparing labels. Nothing should assume the labels are 0 to K-1.
```
```hint Two sets of models
Keep the fold clones that produce OOF features during `fit` apart from the full refits that `predict` chains together. Ask which level-2 input each set should be trained on.
```
### Constraints & Assumptions
- `X` is a numeric array of shape `(n_samples, d)`, and `y` holds `n_samples` numeric targets.
- `folds` has one label per row. Labels can be any comparable values, such as non-contiguous integers or strings, and at least two distinct labels must appear.
- Every estimator follows the scikit-learn regressor API (`fit`, `predict`, and `get_params` so that `clone` works).
- The stacker receives the fold labels at construction, so `fit` is called on data with exactly `len(folds)` rows.
### What a Strong Answer Covers
- One OOF helper that clones every estimator per fold, fills the held-out rows column by column, and validates the label shape and the number of distinct labels.
- Reuse of the same fold labels at level 2, with the level-2 input built from `level1_oof_` and, under passthrough, `X` appended after the OOF columns.
- A clear split between fold clones (used for OOF features) and full refits (used for prediction), with the level-2 refits trained on the OOF-based input.
- A `predict` that chains the refits in the same column order as `fit` and returns a 1-D float array.
- The cost in model fits, and an accurate account of which leakage shared folds prevent and which they do not.
### Follow-up Questions
- Does sharing folds remove all target leakage between the tiers, and what changes if level 2 uses a different split than level 1?
- Why fit `level2_estimators_` on OOF features but predict with full-refit level-1 outputs?
- How would you adapt this for classification?
Overview: Implement out-of-fold predictions and a two-level stacking regressor that reuses the same per-row fold labels at both levels under a final estimator. It tests leakage-aware cross-validation, clone-based refitting, passthrough features, and how the refit models chain together at prediction time.