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
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]] gives ([1, -1, 1, 1], 0.333333): row 1 is in every bootstrap, so it gets -1.
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.
Worked example: 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.
Rule: oob_pred_i = majority of { pred_t(i) : i not in bootstrap_t }, accuracy over rows with at least one vote.
Random 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,)