Balanced Bagging Classifier From Scratch
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `BalancedBaggingClassifier`, which wraps any scikit-learn classifier and is constructed as `BalancedBaggingClassifier(base_estimator, n_estimators=10, random_state=0)`. Each of the `n_estimators` bags draws, for every class, as many samples as the smallest class has, with replacement. A fresh clone of the base estimator is fitted on each bag, and predictions are soft-voted (the estimators' probabilities are averaged).
The class must meet these requirements:
- `fit(X, y)` sets `classes_ = np.unique(y)` and seeds one `np.random.default_rng(random_state)`. For each bag it concatenates `rng.choice(class_indices, size=n_min, replace=True)` over the classes in `classes_` order, where `class_indices` comes from `np.flatnonzero(y == c)` and `n_min` is the smallest class count.
- Each bag's index array is stored in `bag_indices_` and each fitted `sklearn.base.clone` in `estimators_`. The `base_estimator` passed in is never fitted. `fit` returns `self`.
- `predict_proba(X)` returns the mean of the estimators' `predict_proba` outputs, with shape `(n_samples, len(classes_))` and columns aligned to `classes_` through each estimator's own `classes_`.
- `predict(X)` returns `classes_[argmax(proba, axis=1)]`, so it gives the original labels (for example `3` and `7`, not `0` and `1`).
- Both binary and multiclass `y` must work.
Bag indices are checked exactly against the seeded draw order described above.
Example, using scikit-learn's prior-only model, which predicts the class frequencies it saw during training:
```python
import numpy as np
from sklearn.dummy import DummyClassifier
X = np.zeros((33, 2))
y = np.array([0] * 20 + [1] * 8 + [2] * 5) # class 0 -> 20, class 1 -> 8, class 2 -> 5
m = BalancedBaggingClassifier(DummyClassifier(strategy="prior"), n_estimators=6).fit(X, y)
len(m.bag_indices_[0]) # 15 (5 per class)
m.predict_proba(X[:1]) # [[0.3333, 0.3333, 0.3333]]: each prior model sees a balanced bag
```
```hint Reproducible draws
The grader replays your random stream draw by draw. Think about how many generators you create, where you create them, and the order of the `rng.choice` calls across classes and bags.
```
```hint Column alignment
Each fitted estimator orders its `predict_proba` columns by its own `classes_`. Find the matching positions in the ensemble's `classes_` before adding the outputs, and remember that `predict` has to return labels.
```
### Constraints & Assumptions
- `X` is array-like with shape `(n_samples, n_features)`, and `y` is a 1-D array of labels that `np.unique` can sort (integers or strings).
- The base estimator follows the scikit-learn API: it can be cloned, and it implements `fit`, `predict_proba` and `classes_`.
- Every class present in `y` has at least one sample, so `n_min` is at least 1.
### What a Strong Answer Covers
- Grouping row indices per class, computing `n_min`, and drawing from a single seeded generator in class order within each bag, bag after bag.
- Fitting a fresh clone per bag, storing the clones and the index arrays, and leaving the passed-in estimator unfitted.
- Averaging `predict_proba` with columns mapped onto the ensemble's sorted `classes_`, and returning original labels from `predict`.
- Fit and predict cost in terms of the number of bags, the number of classes and the bag size.
- Edge cases such as a single-class `y`, a minority class with only a few rows, and string labels.
### Follow-up Questions
- Why do balanced bags distort predicted probabilities, and how would you fix calibration?
- How would you add out-of-bag evaluation?
- When would you sample without replacement, or use a sampling ratio below 1:1 (minority to majority)?
Overview: Implement a balanced bagging classifier that wraps any scikit-learn estimator, draws class-balanced bootstrap bags from one seeded generator, and soft-votes the fitted clones. It tests reproducible sampling, estimator cloning, probability column alignment, and how undersampling affects calibration.