Feature Selection Leakage on Pure Noise
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement a k-fold CV pipeline of top-k feature selection followed by a nearest-centroid classifier. Then show that selecting features on the full dataset (leaky) inflates accuracy on pure noise, while selecting inside each training fold (honest) stays near chance.
The functions must meet these requirements:
- `contiguous_kfold(n_samples, n_splits)`: contiguous folds in input order, with the first `n_samples % n_splits` folds getting one extra sample. Returns a list of `(train_idx, test_idx)` with ascending train indices. Raise `ValueError` unless `2 <= n_splits <= n_samples`.
- `select_top_k(X, y, k)`: rank features by the absolute Pearson correlation $|r|$ with `y`. Zero-variance features score 0, and ties go to the lower index. Return the chosen indices sorted ascending.
- `nearest_centroid_predict(X_train, y_train, X_test)`: predict the class with the closest Euclidean training centroid. Ties go to the smaller label.
- `cross_validate_selection(X, y, k, n_splits, select_inside_folds)`: run CV over the `contiguous_kfold` splits and return an array of fold accuracies and a list of the selected indices per fold. When `select_inside_folds` is `False`, select once on all data and reuse that selection in every fold.
- `noise_experiment(n_samples, n_features, k, n_splits, seed)`: build the data with `rng = np.random.default_rng(seed)`, then `X = rng.standard_normal((n_samples, n_features))`, then `y = rng.integers(0, 2, size=n_samples)`. Return a `DataFrame` with `scheme` set to `["leaky", "honest"]` and float `mean_accuracy`.
Use only `numpy` and `pandas`. Shuffling is out of scope.
Example:
```python
[len(te) for _, te in contiguous_kfold(23, 5)]
# [5, 5, 5, 4, 4] test folds are 0-4, 5-9, 10-14, 15-18, 19-22
```
```hint Scoring and ranking features
Check what your correlation returns for a constant column, since a zero standard deviation in the denominator gives NaN. Then make sure equal scores come out in index order; a plain argsort does not promise that.
```
```hint Where the leak enters
In the leaky scheme, ask which labels the selector looked at when it picked the features used on a test fold. That is enough to push a centroid classifier above 0.5 on random data when there are many more features than samples.
```
### What a Strong Answer Covers
- Contiguous folds with the right sizes and ascending indices, plus the `ValueError` check.
- Correlation scoring that gives exactly 0 for constant columns, and a ranking with deterministic tie-breaking.
- Nearest-centroid prediction that follows the smaller-label tie rule.
- A clean separation of the two schemes: one global selection reused in every fold versus selection on each training fold only.
- A clear explanation of why the leaky score beats chance on pure noise while the honest score stays near 0.5.
### Follow-up Questions
- How would you prevent this leak with scikit-learn?
- How would you also tune `k` without biasing the reported score?
- How would you test whether a CV score is really above chance?
Overview: Build a k-fold cross-validation pipeline with top-k correlation feature selection and a nearest-centroid classifier, then compare selecting features on all data against selecting inside each training fold on pure noise. It tests understanding of selection leakage and careful NumPy implementation.