Implement Nested Cross-Validation with the One-SE Rule to Tune Ridge Alpha
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: hard
Interview Round: Other
Tune the Ridge regularization strength `alpha` with nested cross-validation by implementing the four functions below. Every model is `make_pipeline(StandardScaler(), Ridge(alpha=a))` fit on training rows only, and every score is the test-fold mean squared error (MSE).
```python
def kfold_indices(n_samples, n_splits): ...
def cv_mse_by_alpha(X, y, alphas, n_splits): ...
def one_se_select(alphas, mean_scores, std_scores, n_splits): ...
def nested_cv(X, y, alphas, n_outer=5, n_inner=4): ...
```
- `kfold_indices` returns a list of `(train_idx, test_idx)` tuples of sorted index arrays. Folds are contiguous in input order with no shuffling, and the first `n_samples % n_splits` folds get one extra sample. `n_splits < 2` or `n_splits > n_samples` raises `ValueError`.
- `cv_mse_by_alpha` returns `(mean, std)`, the mean and standard deviation of the fold MSE for each alpha, in input order, with `std` computed using `ddof=1`.
- `one_se_select` sets `threshold = mean[best] + std[best] / sqrt(n_splits)`, where `best` is the alpha with the lowest mean, and returns the largest alpha (as a `float`) whose mean is at most the threshold. The alphas may be unsorted.
- `nested_cv` runs, for each outer fold, an inner CV with `n_inner` folds on the outer-train rows only. It records the lowest inner mean, picks alpha by the one-SE rule, refits on outer-train and scores on outer-test.
- For the final model, `nested_cv` runs CV on all the data with `n_outer` folds, picks `final_alpha` by the one-SE rule and refits on all the data. `optimistic_bias` is the mean of the outer scores minus the mean of the best inner scores.
Example:
```python
one_se_select([0.1, 1.0, 10.0, 100.0], [5.0, 4.0, 4.3, 6.0], [1.0, 1.2, 0.9, 0.5], 4)
# threshold = 4.0 + 1.2 / 2 = 4.6, candidates {1.0, 10.0}
# returns 10.0
nested_cv(...)
# returns {
# "outer_scores": ndarray, "selected_alphas": ndarray, "best_inner_scores": ndarray,
# "optimistic_bias": float, "final_alpha": float, "final_model": fitted Pipeline,
# }
```
```hint Keep the inner search blind
Write the inner search so it only sees the rows it is handed. Then check which rows `nested_cv` hands it, and whether the outer test fold can reach the scaler or the choice of alpha.
```
```hint Unsorted alphas
The one-SE rule returns the largest qualifying alpha value, which need not be the last qualifying entry in the list.
```
### Constraints & Assumptions
- `X` is a 2-D numeric array with one row per sample, and `y` is a 1-D array of the same length.
- `alphas` is a non-empty list of non-negative floats, in any order.
- No step shuffles the rows. Every split comes from `kfold_indices`.
### Clarifying Questions to Ask
- If two alphas tie for the lowest mean MSE, whose standard deviation sets the threshold?
- Are the rows in a meaningful order, such as time or a sorted target? Contiguous unshuffled folds would then be unrepresentative.
- Should `nested_cv` check that `n_inner` fits inside every outer training set, or let `kfold_indices` raise?
### What a Strong Answer Covers
- Fold construction that follows the size rule and keeps the index arrays sorted and disjoint.
- A fresh scaler and Ridge pipeline fit on training rows only at every level, so no test fold leaks into scaling or selection.
- The one-SE rule with the right standard error and correct handling of unsorted alphas.
- Outer scores computed only on data the inner search never saw, and a correct `optimistic_bias`.
- The number of model fits the whole procedure needs.
### Follow-up Questions
- Why is the minimum inner score an optimistic estimate of generalization error?
- How would you adapt this for time-series data?
- How would you reduce the cost of nested CV for a large grid?
Overview: Implement contiguous k-fold splits, a per-alpha cross-validation search, the one-standard-error rule and nested cross-validation to tune Ridge regularization. It tests leakage-free model selection, honest error estimates and how optimistic the best inner score is.