Random Forest OOB Versus Cross-Validation Gap Experiment
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement two functions around a scikit-learn `RandomForestClassifier`. `manual_oob_accuracy(forest, X, y)` recomputes a fitted forest's out-of-bag (OOB) accuracy from its trees and bootstrap samples. `oob_vs_cv_gap(X, y, sizes, n_estimators_list, random_state=0)` returns a `pd.DataFrame` comparing OOB accuracy with 5-fold cross-validation accuracy for every (size, tree count) setting.
Requirements:
- `manual_oob_accuracy`: for each sample, average `predict_proba` over the trees for which it is out-of-bag (find each tree's in-bag rows with `estimators_samples_`), predict the argmax class through `classes_`, and score only the samples that are out-of-bag for at least one tree. When every sample is out-of-bag for at least one tree, the result must equal `oob_score_` exactly, string labels included.
- For each `n` in `sizes`, use the first `n` rows. Fit `RandomForestClassifier(n_estimators=t, oob_score=True, random_state=random_state)` and take `oob_score_`.
- `cv_score` is the mean of `cross_val_score` with an identically seeded forest (no `oob_score`) and `cv=KFold(n_splits=5)` (no shuffle).
- Columns in order: `n_samples` and `n_estimators` as `int64`, then `oob_score`, `cv_score` and `gap` as `float64`, with `gap = oob_score - cv_score`.
- Row order: sizes in the outer loop and tree counts in the inner loop, both in input order.
Example:
```python
df = oob_vs_cv_gap(X, y, sizes=[60, 120], n_estimators_list=[5, 20])
df[["n_samples", "n_estimators"]].values.tolist()
# [[60, 5], [60, 20], [120, 5], [120, 20]]
```
```hint Count the votes
Keep a per-row count of how many trees voted. Check what a count of zero does in your function, and what scikit-learn does with the same row.
```
```hint Which folds
Look at what `cross_val_score` does when `cv` is an integer and the estimator is a classifier.
```
### Constraints & Assumptions
- `X` is numeric with shape `(n_rows, d)`, as an array or DataFrame. `y` has one label per row, integers or strings.
- Every `n` in `sizes` is at least 5, so 5-fold CV can run, and at most `n_rows`.
- The forest passed to `manual_oob_accuracy` was fit with `bootstrap=True` on exactly this `X` and `y`, in the same row order.
- Other forest settings stay at scikit-learn defaults.
### What a Strong Answer Covers
- Rebuilding each tree's out-of-bag rows from `estimators_samples_` and accumulating soft votes with a per-row count.
- Mapping the winning probability column back to a label so that string and non-contiguous labels compare correctly with `y`.
- What happens to rows that no tree left out, and exactly when the manual score equals `oob_score_`.
- The comparison table with the required seeding, unshuffled folds, loop order, column order and dtypes.
- Why the gap depends on dataset size and tree count.
### Follow-up Questions
- Why is OOB often pessimistic for small forests or small datasets?
- How would you measure the instability of the gap across runs for each setting?
- On a 5-tree forest, your manual score and `oob_score_` often disagree. Why, and which number would you report?
- What happens to both scores if the rows are sorted by label before the experiment runs?
Overview: Implement a manual out-of-bag accuracy for a scikit-learn random forest and a table comparing OOB and 5-fold cross-validation accuracy across dataset sizes and tree counts. It tests bootstrap sampling, soft voting over out-of-bag trees, label mapping, and why OOB estimates drift from cross-validation for small forests.