Implement Leave-One-Out and Leave-P-Out Cross-Validation Splitters
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement `leave_one_out(n_samples)` and `leave_p_out(n_samples, p, max_combinations=10000)`. Each yields `(train_idx, val_idx)` pairs of integer NumPy arrays over the indices `0` to `n_samples - 1`.
Requirements:
- `leave_one_out`: the validation index `i` runs from `0` to `n - 1` in order, with `val_idx = [i]`.
- `leave_p_out`: the validation sets are all size-`p` subsets in lexicographic order, each sorted ascending.
- `train_idx` is always the sorted complement of `val_idx`.
- Raise `ValueError` when `n_samples < 2`, `p < 1` or `p >= n_samples`.
- Raise `ValueError` when `C(n_samples, p) > max_combinations` (equality is allowed).
Example:
```python
list(leave_p_out(4, 2))[:3]
# [([2, 3], [0, 1]), ([1, 3], [0, 2]), ([1, 2], [0, 3])]
list(leave_p_out(5, 2, max_combinations=9)) # ValueError: C(5,2)=10 > 9
```
```hint Count before you enumerate
Python's standard library can both count and list the size-`p` subsets of a range. Check the count against the cap before producing a single split.
```
### What a Strong Answer Covers
- Validation sets in the required order: single indices for leave-one-out, lexicographic size-`p` subsets for leave-p-out.
- Train indices that are the sorted complement, returned as integer NumPy arrays.
- Every `ValueError` case, including the combination cap with equality allowed.
- When the checks run, given that a function containing `yield` defers its whole body until the first iteration.
- The cost of full iteration and why the cap exists.
### Follow-up Questions
- Leave-one-out trains on almost all the data in every split. What does that do to the bias and the variance of the error estimate, and when is it a poor choice?
- For which models can you get the leave-one-out error without refitting `n` times?
- Leave-p-out validation sets overlap. What does that mean if you use the spread of the split scores as an error bar?
Overview: Implement leave-one-out and leave-p-out cross-validation splitters in Python that yield sorted train and validation index arrays and refuse to enumerate too many subsets. It tests subset enumeration order, input checks, eager validation with generators and the cost of exhaustive cross-validation.