Incremental OOB Early Stopping for Random Forests
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement two functions that track a random forest's out-of-bag (OOB) error one tree at a time and stop once the error stops improving. `oob_early_stopping_curve` replays precomputed trees in order, and `grow_forest_with_oob_stopping` trains them one at a time. Both maintain running OOB vote tallies.
```python
def oob_early_stopping_curve(tree_preds, inbag_mask, y, n_classes, tol, patience):
... # returns (n_trees_used, curve)
def grow_forest_with_oob_stopping(X, y, n_classes, max_trees, tol, patience,
max_features="sqrt", seed=0):
... # returns (trees, inbag_mask, curve)
```
Both functions follow these rules:
- Each tree adds one vote for its predicted class to every sample not in its bag. The error after tree `t` is computed over the samples with at least one vote (argmax, ties go to the lowest label), or `nan` if no sample has a vote yet.
- Keep a streak counter. If the previous and current errors are both finite and `prev - err < tol`, increment it; otherwise reset it to 0. Stop when `streak >= patience`. The curve includes the stopping tree.
- `patience < 1` raises `ValueError`.
- The replay function returns `(n_trees_used: int, curve: float ndarray)`.
- The grower bootstraps `n` rows per tree with a `default_rng(seed)` and fits `DecisionTreeClassifier(max_features=max_features)` with a seeded `random_state`. It returns `(trees, inbag_mask, curve)`, where `inbag_mask` is a bool array of shape `(T, n)`, and its output is deterministic for a given seed.
Example:
```python
y = [0, 1, 0, 1]
preds = [[0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 0, 1]]
inbag = [[True, True, False, False],
[False, False, True, True],
[False, True, False, True]]
oob_early_stopping_curve(preds, inbag, y, 2, tol=0.0, patience=10) # -> (3, [0.5, 0.5, 0.25])
oob_early_stopping_curve(preds, inbag, y, 2, tol=0.01, patience=1) # -> (2, [0.5, 0.5])
```
In both calls the second tree leaves the error flat at 0.5. With `tol=0.0` a flat step does not count toward the streak, so all three trees are used; with `tol=0.01` it does, and the replay stops after the second tree.
```hint State to keep
You never need to look at earlier trees again. Ask which per-sample array lets you read off the OOB majority vote after any prefix of the forest.
```
```hint Streak edge cases
Decide what the streak does on the very first tree and whenever either error is `nan`, then trace the `tol=0.01, patience=1` example by hand.
```
```hint Reproducibility
Draw the bootstrap rows and each tree's seed from the same generator in a fixed order, and send both functions through the same update code.
```
### Constraints & Assumptions
- Labels and predictions are integers in `[0, n_classes)`.
- `tree_preds` and `inbag_mask` both have shape `(T, n)`.
- `tol` may be negative or zero.
### What a Strong Answer Covers
- An incremental `(n, n_classes)` vote tally that only touches the new tree's OOB rows, with ties resolved to the lowest label.
- Correct handling of uncovered samples: the error is taken over covered rows only, it is `nan` when none are covered, and the streak resets whenever either error is not finite.
- Stopping logic that reproduces both examples, keeps the stopping tree in the curve, and rejects `patience < 1` before any work.
- A grower that is deterministic per seed and whose curve matches a replay of its own trees and masks.
- The per-tree and total cost, compared with recounting every tree's votes after each step.
### Follow-up Questions
- Why is the incremental tally preferable to recomputing the OOB error from scratch after every tree?
- How would you make the stopping rule less sensitive to a noisy OOB curve?
- How would you adapt this to regression or to probability-based OOB scores?
Overview: Implement out-of-bag early stopping for a random forest by keeping running OOB vote tallies as trees are replayed or grown one at a time. Tests incremental bookkeeping with NumPy, careful handling of uncovered samples and NaN errors, patience-based stopping, and reproducible bootstrapping with seeded generators.