Implement Monte Carlo Shuffle-Split Cross-Validation
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `shuffle_split(n_samples, n_splits=10, test_size=None, train_size=None, random_state=None)`. It returns a list of `n_splits` tuples `(train_idx, test_idx)` of disjoint, sorted integer index arrays drawn from `range(n_samples)`.
Sizes and sampling follow these rules:
- If both sizes are `None`, use `test_size = 0.1`.
- A float size must be in the open interval (0, 1). The test count is `ceil(f * n_samples)` and the train count is `floor(f * n_samples)`.
- An int size must be in `[1, n_samples - 1]`. A `bool` or any other type raises `ValueError`.
- If only one size is given, the other is `n_samples` minus it.
- Create `rng = np.random.default_rng(random_state)` once. For each split, compute `perm = rng.permutation(n_samples)`, then `test = sort(perm[:n_test])` and `train = sort(perm[n_test:n_test + n_train])`.
Example:
```python
splits = shuffle_split(10, n_splits=3, test_size=0.25, train_size=0.55, random_state=2)
len(splits) # 3
[len(te) for _, te in splits] # [3, 3, 3] (ceil(2.5))
[len(tr) for tr, _ in splits] # [5, 5, 5] (floor(5.5))
```
```hint Validate before sampling
Turn both sizes into integer counts and run every check before you touch the generator. In Python, `True` passes an `isinstance(x, int)` test, so the order of your type checks matters.
```
```hint Where the generator lives
Think about what the splits would look like if the generator were recreated from the same seed inside the loop.
```
### Constraints & Assumptions
- `n_samples < 2`, `n_splits < 1`, or `n_train + n_test > n_samples` raises `ValueError`.
- `random_state` may be `None`, an int, or a `np.random.Generator`. The same seed must reproduce identical splits.
### What a Strong Answer Covers
- Size resolution that uses `ceil` for a float test size and `floor` for a float train size, the 0.1 default, and the complement when only one size is given.
- Type and range validation, including rejecting `bool` before the integer check and catching a float train size that rounds down to zero.
- One generator created once from `random_state`, so the splits differ from each other but repeat exactly for the same seed.
- Train and test arrays that are disjoint, sorted, and sliced from a single permutation per split.
- The time and memory cost for k splits.
### Follow-up Questions
- How would you make this a stratified shuffle-split?
- How does Monte Carlo cross-validation differ from K-fold in coverage and variance?
- How would you change the function to yield splits lazily when `n_samples` is very large?
Overview: Implement a Monte Carlo shuffle-split function in NumPy that returns repeated random train and test index splits. It tests converting float and int sizes into counts, careful input validation, and reproducible sampling from a single seeded generator.