Bootstrap Confidence Interval for a Metric
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `bootstrap_metric_ci(y_true, y_pred, metric_fn, n_bootstraps=1000, alpha=0.05, rng=None)`. Resample row indices with replacement (pairs stay aligned), recompute `metric_fn` on each replicate, and return a dict with keys `estimate`, `lower`, `upper`, `std_error`, `n_valid`.
The function must follow these rules:
- RNG: `None` → `np.random.default_rng(0)`, an int seed → `default_rng(seed)`, a `Generator` is used as-is. Each replicate draws `rng.integers(0, n, size=n)`.
- `estimate` is `metric_fn` on the full data (as `float`). Non-finite replicates are dropped and `n_valid` counts the rest.
- `lower` and `upper` are `np.percentile` (default interpolation) at `100 * alpha / 2` and `100 * (1 - alpha / 2)`. `std_error` is `np.std(valid, ddof=1)`.
- Fewer than 2 valid replicates → `lower`, `upper` and `std_error` are `nan`.
- Raise `ValueError` on length mismatch, empty input, `alpha` not in (0, 1), or `n_bootstraps < 1`.
Example:
```python
acc = lambda t, p: float(np.mean(t == p))
y = ["a", "b", "c", "a", "b", "c", "a"]
bootstrap_metric_ci(y, list(y), acc, n_bootstraps=100, rng=1)
# {'estimate': 1.0, 'lower': 1.0, 'upper': 1.0, 'std_error': 0.0, 'n_valid': 100}
```
Every prediction matches its label, so every replicate scores 1.0 and the interval collapses to a single point.
```hint Reproducible draws
Create the generator once, before the loop, and make exactly one `integers` call per replicate. Any extra random call shifts every later replicate for the same seed.
```
```hint Degenerate replicates
Check what `np.percentile` and `np.std` return when the input array contains a `nan`, and decide where to filter.
```
### Constraints & Assumptions
- Inputs may be lists or NumPy arrays of any dtype. Convert them with `np.asarray`.
- `metric_fn(y_true, y_pred)` returns a scalar and may return `nan` on degenerate resamples, for example recall on a resample with no positives.
### What a Strong Answer Covers
- Paired resampling, with one index array applied to both `y_true` and `y_pred` so each pair stays aligned.
- Generator handling for `None`, an int seed and an existing `Generator`, with one draw per replicate so results are reproducible.
- Dropping non-finite replicates before the percentiles and standard error, and the `nan` fallback when fewer than 2 replicates are valid.
- Input validation that raises `ValueError` for each listed case.
- Time and space cost in terms of the number of replicates and the number of rows.
### Follow-up Questions
- When does the percentile interval undercover, and what would you use instead?
- How would you compare two models on the same test set?
- How would you adapt this for grouped or imbalanced data?
Overview: Implement a paired percentile bootstrap that puts a confidence interval around any model evaluation metric, with reproducible seeding and handling of degenerate resamples. It tests NumPy resampling, percentile intervals, standard error estimates and careful input validation.