Balanced Random Forest Bootstrap and Calibration

Quick Overview

Implement a Balanced Random Forest from scikit-learn decision trees, with per-class undersampled bootstraps, out-of-bag masks and OOB probability averaging. Then compare its minority-class calibration gap against a class-weighted random forest. It tests bootstrap mechanics, probability alignment and calibration under class imbalance.

Balanced Random Forest Bootstrap and Calibration

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: hard

Interview Round: Other

Implement a Balanced Random Forest from scikit-learn `DecisionTreeClassifier` trees, where each tree's bootstrap undersamples every class to the minority count. Then compare its out-of-bag (OOB) minority calibration gap with the gap of `RandomForestClassifier(class_weight="balanced")`. Implement these functions: - `balanced_bootstrap(y, rng)`: with `m` = minority count, draw `m` row indices with replacement from each class (classes ascending, concatenated) via `rng.choice`. Return an integer array. - `oob_masks(n_samples, bootstrap_indices)`: a bool array of shape `(n_trees, n_samples)`, `True` where row `i` is absent from bootstrap `t`. - `fit_balanced_forest(X, y, bootstrap_indices, max_features="sqrt", random_state=0)`: tree `t` fits `X[idx], y[idx]` with `random_state + t` and the given `max_features`. - `forest_predict_proba(trees, X, classes)`: average the per-tree probabilities aligned to the sorted `classes`. Classes missing from a tree are zero-filled. - `oob_proba(trees, X, masks, classes)`: average only over the trees where the row is OOB. A row that is never OOB is all `NaN`. - `minority_probability_gap(proba, y, classes, minority_label)`: mean predicted minority probability minus observed minority rate, over rows whose probabilities are all finite. Return a `float`. - `compare_calibration(X, y, minority_label, n_trees, seed)`: use `np.random.default_rng(seed)` for the `n_trees` bootstraps, and `max_features="sqrt"` with `random_state=seed` for both forests. The scikit-learn forest uses `oob_score=True` and `oob_decision_function_`. Return `{"balanced_rf": ..., "class_weight_balanced": ...}`. Example for the gap function: ```python nan = float("nan") proba = [[0.8, 0.2], [nan, nan], [0.4, 0.6], [0.9, 0.1], [0.5, 0.5]] y = [0, 1, 1, 0, 0] minority_probability_gap(proba, y, classes=[0, 1], minority_label=1) # finite rows 0, 2, 3, 4: 0.35 - 0.25 = 0.10 ``` Row 1 is dropped from both terms. The mean minority probability over the other four rows is 0.35, and one of those four rows has the minority label, so the observed rate is 0.25. ```hint Align the columns A tree's `predict_proba` columns follow its own `classes_`, which can be a subset of the global classes. Find where each of the tree's classes sits in the sorted global array before adding. ``` ```hint Count OOB trees per row Keep a running count of how many trees left each row out, and divide the summed probabilities only where that count is positive. ``` ```hint Think about the training prior For the comparison, look at the class mix each balanced tree trains on and where a left-out majority row tends to land in such a tree. ``` ### Constraints & Assumptions - `X` is a numeric array of shape `(n_samples, n_features)` and `y` holds the class labels, with two or more classes. - Every class has at least one row, so the minority count `m` is at least 1. - Apart from `max_features` and `random_state`, the trees use scikit-learn defaults, so they grow until their leaves are pure. ### What a Strong Answer Covers - A per-class bootstrap that draws exactly `m` rows with replacement from each class in ascending class order, with all draws coming from the one seeded generator. - Probability averaging that maps each tree's columns onto the global sorted classes and handles rows that no tree left out. - A gap that uses the same finite rows for the predicted mean and the observed rate, matching the example. - A like-for-like comparison with the class-weighted forest: OOB probabilities on both sides, same seed, same `max_features`. - A reasoned explanation of why the two gaps differ, tied to the class mix each tree trains on. ### Follow-up Questions - Why does the balanced forest overpredict the minority class, and how would you correct it? - Why does the comparison use OOB probabilities, and what goes wrong with in-sample predictions? - How does undersampling compare to `class_weight="balanced_subsample"` when the majority class is large?

Overview: Implement a Balanced Random Forest from scikit-learn decision trees, with per-class undersampled bootstraps, out-of-bag masks and OOB probability averaging. Then compare its minority-class calibration gap against a class-weighted random forest. It tests bootstrap mechanics, probability alignment and calibration under class imbalance.

General logo
General
Nov 24, 2026
hardMachine Learning EngineerOtherMachine Learning
0
0

Implement a Balanced Random Forest from scikit-learn DecisionTreeClassifier trees, where each tree's bootstrap undersamples every class to the minority count. Then compare its out-of-bag (OOB) minority calibration gap with the gap of RandomForestClassifier(class_weight="balanced").

Implement these functions:

  • balanced_bootstrap(y, rng) : with m = minority count, draw m row indices with replacement from each class (classes ascending, concatenated) via rng.choice . Return an integer array.
  • oob_masks(n_samples, bootstrap_indices) : a bool array of shape (n_trees, n_samples) , True where row i is absent from bootstrap t .
  • fit_balanced_forest(X, y, bootstrap_indices, max_features="sqrt", random_state=0) : tree t fits X[idx], y[idx] with random_state + t and the given max_features .
  • forest_predict_proba(trees, X, classes) : average the per-tree probabilities aligned to the sorted classes . Classes missing from a tree are zero-filled.
  • oob_proba(trees, X, masks, classes) : average only over the trees where the row is OOB. A row that is never OOB is all NaN .
  • minority_probability_gap(proba, y, classes, minority_label) : mean predicted minority probability minus observed minority rate, over rows whose probabilities are all finite. Return a float .
  • compare_calibration(X, y, minority_label, n_trees, seed) : use np.random.default_rng(seed) for the n_trees bootstraps, and max_features="sqrt" with random_state=seed for both forests. The scikit-learn forest uses oob_score=True and oob_decision_function_ . Return {"balanced_rf": ..., "class_weight_balanced": ...} .

Example for the gap function:

nan = float("nan")
proba = [[0.8, 0.2], [nan, nan], [0.4, 0.6], [0.9, 0.1], [0.5, 0.5]]
y = [0, 1, 1, 0, 0]
minority_probability_gap(proba, y, classes=[0, 1], minority_label=1)
# finite rows 0, 2, 3, 4: 0.35 - 0.25 = 0.10

Row 1 is dropped from both terms. The mean minority probability over the other four rows is 0.35, and one of those four rows has the minority label, so the observed rate is 0.25.

Constraints & Assumptions

  • X is a numeric array of shape (n_samples, n_features) and y holds the class labels, with two or more classes.
  • Every class has at least one row, so the minority count m is at least 1.
  • Apart from max_features and random_state , the trees use scikit-learn defaults, so they grow until their leaves are pure.

What a Strong Answer Covers Guidance

  • A per-class bootstrap that draws exactly m rows with replacement from each class in ascending class order, with all draws coming from the one seeded generator.
  • Probability averaging that maps each tree's columns onto the global sorted classes and handles rows that no tree left out.
  • A gap that uses the same finite rows for the predicted mean and the observed rate, matching the example.
  • A like-for-like comparison with the class-weighted forest: OOB probabilities on both sides, same seed, same max_features .
  • A reasoned explanation of why the two gaps differ, tied to the class mix each tree trains on.

Follow-up Questions Guidance

  • Why does the balanced forest overpredict the minority class, and how would you correct it?
  • Why does the comparison use OOB probabilities, and what goes wrong with in-sample predictions?
  • How does undersampling compare to class_weight="balanced_subsample" when the majority class is large?