Implement RUSBoost With Per-Round Majority Undersampling
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: hard
Interview Round: Other
Implement a binary `RUSBoostClassifier`: discrete AdaBoost where each round trains a weak learner on all minority rows plus an equal-size random draw of majority rows, then scores and reweights on the full training set. Implement `fit`, `decision_function`, `predict_proba` and `predict`. The constructor takes `n_estimators`, `learning_rate`, `random_state` and `base_estimator_factory`.
Requirements:
- The minority is the class with the smaller count (the first in `np.unique` order on ties). `classes_[1]` maps to +1. Raise `ValueError` unless there are exactly two classes.
- Follow the round procedure below exactly, using one `np.random.default_rng(random_state)` for all draws.
- Default learner: `DecisionTreeClassifier(max_depth=1, random_state=0)`. Otherwise call `base_estimator_factory()`.
- After `fit`, expose `classes_`, `estimators_`, `estimator_alphas_` and `estimator_errors_` (arrays), `sample_indices_` (one subset per kept round) and `sample_weights_` (final full-set weights, shape `(n,)`). Raise `ValueError` if no round is kept.
- `decision_function(X)` returns $f(x) = \sum_t \alpha_t h_t(x)$, where $h_t(x)$ is round $t$'s vote written as +1 or -1.
- `predict_proba(X)` returns `[1 - p, p]` with $p = 1 / (1 + e^{-2f})$.
- `predict(X)` returns `classes_[1]` if and only if `f > 0`, and `classes_[0]` otherwise.
Round procedure:
```text
w = full(n, 1/n)
for each of n_estimators rounds:
chosen = rng.choice(majority_idx, size=n_min, replace=False)
subset = np.sort(np.concatenate([minority_idx, chosen]))
fit learner on X[subset], y[subset], sample_weight=w[subset]/w[subset].sum()
pred_full = learner.predict(X) # on ALL n rows
err = w[pred_full != y].sum()
if err >= 0.5: break # round discarded
e = max(err, 1e-10)
alpha = learning_rate * 0.5 * log((1-e)/e)
keep round (estimator, alpha, err, subset)
if err == 0 (no misses): break
w = w * exp(-alpha * y_pm * h_pm); w /= w.sum()
```
Here `y_pm` and `h_pm` are the true labels and the full-set predictions written as +1 or -1, with `classes_[1]` as +1.
A factory learner exposes `fit(X, y, sample_weight=None)` and `predict(X)`. Labels may be arbitrary values (for example `2` and `5`).
```hint Two sets of rows
The subset only decides what the learner trains on. For each step of a round, be clear about whether it uses the subset or all `n` rows.
```
```hint Signs and labels
The vote and the weight update need +1 and -1, but the learners predict the original label values. Fix one mapping from labels to signs and use it in `fit` and at prediction time.
```
```hint Order of the stops
The two `break` conditions sit at different points in the round. Check whether the round is recorded before or after each one, and which weights end up in `sample_weights_`.
```
### What a Strong Answer Covers
- Choosing the minority with the tie rule, mapping `classes_[1]` to +1, and rejecting anything other than two classes.
- Drawing each round's balanced subset from one shared generator and fitting the learner with the subset's renormalized weights.
- Computing the error, alpha and weight update on the full training set, with the error clip and both stopping rules in the specified order.
- Exposing the fitted attributes in the required shapes and raising when no round is kept.
- Building `decision_function`, `predict_proba` and `predict` from the alpha-weighted votes, and the cost per round.
### Follow-up Questions
- Why compute the error and weight update on the full set instead of the undersampled subset?
- How would you extend this to multiclass problems?
- Is `sigmoid(2f)` a calibrated probability on imbalanced data, and what would you do about it?
Overview: Implement a binary RUSBoost classifier, discrete AdaBoost in which every weak learner trains on all minority rows plus a fresh random sample of majority rows. It tests boosting weight updates on the full training set, reproducible sampling, stopping rules, and turning weighted votes into scores and probabilities.