Implement a random patches bagging regressor over row and feature subsets
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `RandomPatchesRegressor`, a bagging meta-regressor. Each of its `n_estimators` learners is a fresh clone of `base_estimator`, fit on a subset of the training rows and a subset of the columns (a random patch). `predict` projects `X` onto each learner's columns and returns the mean of the learners' predictions.
The constructor is `RandomPatchesRegressor(base_estimator, n_estimators=10, max_samples=1.0, max_features=1.0, bootstrap=False, random_state=None)`. Implement `fit(X, y, sample_indices=None, feature_indices=None)` and `predict(X)` with these rules:
- `max_samples` and `max_features` set the row and feature counts. An int is a count. A float `frac` with `0 < frac <= 1` gives `max(1, int(frac * total))`. Bools, other types, and counts outside the range 1 to `total` raise `ValueError`.
- Rows: with `bootstrap=True`, draw the row count with replacement. Otherwise use all rows when the count equals `n`, and draw without replacement when it is smaller. Features are always distinct and sorted ascending.
- When given, `sample_indices[i]` and `feature_indices[i]` replace the sampled rows or features for learner `i`. The same `random_state` must produce identical subsets.
- `fit` returns `self` and sets `estimators_`, `estimators_samples_` and `estimators_features_` (lists; the last two hold index arrays) and `n_features_in_`. The caller's `base_estimator` must stay unfitted.
- Bad shapes in `fit`, or a `predict` input whose column count differs from training, raise `ValueError`.
Example:
```python
import numpy as np
from sklearn.linear_model import LinearRegression
X = np.array([[0, 5, 0], [1, 3, 2], [2, 1, 4], [3, 4, 6], [4, 2, 8]], dtype=float)
y = np.array([0, 1, 2, 3, 4], dtype=float)
Xt = np.array([[10, 0, 4]], dtype=float)
m = RandomPatchesRegressor(LinearRegression(), n_estimators=2)
m.fit(X, y, sample_indices=[[0, 1, 2, 3], [1, 2, 3, 4]], feature_indices=[[0], [2]])
m.predict(Xt) # 0.5 * (est0.predict(Xt[:, [0]]) + est1.predict(Xt[:, [2]])), about array([6.])
```
Learner 0 fits rows 0 to 3 on column 0, where `y` equals the feature, so it predicts 10 for `Xt`. Learner 1 fits rows 1 to 4 on column 2, where `y` is half the feature, so it predicts 2. The mean is 6.
```hint Test time sees every column
Each learner was trained on its own columns in a specific order. Work out what its `predict` must receive when the caller passes the full `X`.
```
```hint One is not one point zero
`max_samples=1` and `max_samples=1.0` mean different things. Check how Python's `isinstance` treats `True` before you order your type checks.
```
```hint Matching another implementation
If you sort or deduplicate index arrays that the caller passed in, ask whether you could still reproduce another library's learners from its stored subsets.
```
### Constraints & Assumptions
- `X` is a 2-D numeric array of shape `(n, p)` and `y` is 1-D with length `n`.
- `base_estimator` follows the scikit-learn `fit` / `predict` API. `sklearn.base.clone` and `np.random.default_rng` are available.
- Override lists, when passed, hold one index array per learner and are used exactly as given.
- `random_state=None` means fresh randomness on every fit.
- Given the `estimators_samples_` and `estimators_features_` of a fitted scikit-learn `BaggingRegressor`, predictions must match it (up to floating-point rounding) for a deterministic base model such as `LinearRegression`.
### What a Strong Answer Covers
- Validation of `max_samples` and `max_features`: ints versus floats, booleans, and both range checks.
- The row and feature sampling rule for each `bootstrap` setting, and how one seeded generator makes subsets repeatable.
- Precedence of the override lists and why they are stored without modification.
- Cloning so the caller's estimator stays unfitted, and what each fitted attribute stores.
- Projection of test inputs onto each learner's columns, the shape checks in `fit` and `predict`, and the averaging.
### Follow-up Questions
- How would you add an out-of-bag score to this estimator?
- Why can random subspaces beat plain bagging on high-dimensional data?
- How would you parallelize `fit` while keeping results reproducible?
Overview: Implement a bagging meta-regressor that fits clones of a base model on random subsets of rows and columns and averages their predictions. It tests input validation, seeded sampling with and without replacement, column projection at predict time, and reproducing scikit-learn's BaggingRegressor from stored subsets.