131. Score a random forest with out-of-bag votes
Why it matters Out-of-bag error lets you tune a random forest without a separate validation split, which matters on small datasets.
Each tree in a random forest trains on a bootstrap sample, so about a third of the rows were never seen by that tree. Voting with only those trees gives a free validation score.
Write oob_score(y, boot_idx, tree_preds). y has n labels. boot_idx is a list of T integer arrays, the bootstrap row indices each tree trained on (repeats allowed). tree_preds is a (T, n) array: tree t's predicted label for every training row. For each row i, collect votes from trees whose bootstrap did NOT contain i, and predict the majority label (smaller label on ties); if no tree left i out, predict -1. Return (oob_pred, acc): oob_pred is a list of ints and acc is the accuracy over rows with at least one vote (0.0 if none).
def oob_score(y, boot_idx, tree_preds)Example 1
Input: y [0, 1, 1, 0], boot_idx [[0, 0, 1, 2], [1, 2, 3, 3], [0, 3, 3, 1]], tree_preds [[0, 1, 1, 1], [1, 0, 1, 0], [0, 0, 1, 0]]
Output: ([1, -1, 1, 1], 0.333333): row 1 is in every bootstrap
Explanation: So it gets -1.
Example 2
Input: y = [1, 1, 0], boot_idx = [[0, 1, 2], [0, 0, 1]], tree_preds = [[1, 1, 0], [0, 1, 1]]
Output: ([-1, -1, 1], 0.0)
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
Hint 1
Build a T x n in-bag mask first, then vote only where the mask is False.
Hint 2
inbag[t, idx] = True handles repeated indices fine.
Hint 3
P[~inbag[:, i], i] are the out-of-bag predictions for row i.
Hint 4
Skip rows with no out-of-bag trees when computing accuracy.
Common mistakes
- Including in-bag trees in the vote.
- Counting rows without any OOB vote as wrong.
- Breaking ties inconsistently.
Understand the idea
A random forest trains each tree on a bootstrap sample: n rows drawn with replacement. Some rows get picked twice and some not at all. On average about 37% of rows are left out of each tree, because the chance a row is never drawn is (1 - 1/n)^n, which is about 1/e.
Those left-out rows are a free test set for that tree. For each row, ask only the trees that never saw it, and take their majority vote. Comparing those votes with the true labels gives the out-of-bag (OOB) accuracy, an honest estimate without holding data back.
row 0 appears in the bootstraps of trees 1 and 3 but not tree 2. Only tree 2 votes for row 0. If tree 2 says 1 but the label is 0, row 0 counts as wrong.
oob_pred_i = majority of { pred_t(i) : i not in bootstrap_t }, accuracy over rows with at least one voteRandom forest libraries report this as an OOB score, often used instead of cross-validation.
Shapes and data flow
tree_preds (T, n), inbag (T, n) -> oob_pred (n,)
Topics
Companies1
- Apple a candidate reported this question Apple Machine Learning Engineer Interview Questions | Screna AI
From public interview reports and guides. Not affiliated with or endorsed by these companies.