Sub topic 9
Out-of-bag error as a built-in validation estimate
This chapter assumes you know how bootstrap sampling works, how a random forest combines trees by voting or averaging, and the difference between training and test error. It also assumes basic scikit-learn use. Here you will learn how a forest estimates its own generalization error without a separate validation set.
Why a forest can validate itself
Each tree in a random forest trains on a bootstrap sample. A bootstrap sample draws n rows with replacement from a training set of n rows. Some rows are drawn several times and others are never drawn.
The chance that a particular row is missed by one draw is 1 - 1/n. It is missed by all n draws with probability (1 - 1/n)^n. As n grows, this value approaches e^-1, which is about 0.368. So each tree leaves out roughly 36.8% of the training rows. Those left-out rows are the tree's out-of-bag (OOB) samples.
A tree never saw its OOB rows during fitting. For those rows, the tree acts like a model scored on unseen data. The OOB method uses this fact to get a validation estimate from the training data alone.
The OOB procedure
For each training row i, the method works as follows:
- Find the trees whose bootstrap sample did not include row i.
- Collect predictions for row i from only those trees.
- Aggregate them. Use a majority vote or averaged class probabilities for classification. Use the mean for regression.
- Compare the aggregated prediction with the true label of row i.
The OOB score is the accuracy (or error) over all rows that have an OOB prediction. Each row is predicted by a sub-forest of about 37% of the trees. This sub-forest never trained on that row.
The diagram shows the flow for one row.
Running it in scikit-learn
Set oob_score=True when you build the forest. Note that bootstrap=True is the default and is required, because without resampling there are no OOB rows.
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=0, stratify=y
)
clf = RandomForestClassifier(
n_estimators=300, oob_score=True, n_jobs=-1, random_state=0
)
clf.fit(X_train, y_train)
print("OOB accuracy: ", clf.oob_score_)
print("Test accuracy:", clf.score(X_test, y_test))The two numbers are usually close. They are not identical, because the OOB score uses only the training data and the test score uses a different sample of 20% of the rows. Differences of a point or two are normal on a dataset this small.
The fitted forest also exposes oob_decision_function_. For classifiers this is an array of shape (n_samples, n_classes) with the OOB class probabilities for each training row. For regressors the equivalent is oob_prediction_. You can use these arrays to compute any metric you like, not only accuracy.
from sklearn.metrics import log_loss, roc_auc_score
oob_proba = clf.oob_decision_function_
print("OOB log loss:", log_loss(y_train, oob_proba))
print("OOB ROC AUC: ", roc_auc_score(y_train, oob_proba[:, 1]))Since oob_score=True computes accuracy by default, this is how you get other metrics. Newer scikit-learn versions also let oob_score accept a scoring function. Check the documentation for your installed version before relying on that.
Why the OOB estimate is a fair one
The OOB estimate is close to what leave-one-out cross-validation would give. It uses every training row as a validation point. It needs no extra fitting, because the trees are already trained. Cross-validation on a forest with 5 folds refits the whole forest 5 times. OOB costs one fit.
The estimate is slightly pessimistic in one respect. Each row's prediction comes from about a third of the trees, not all of them. A smaller sub-forest has more variance than the full forest. So the OOB error tends to be a little higher than the error of the full forest would be on truly new data. With 300 or more trees this gap is small. With very few trees it grows.
Edge cases and common errors
Too few trees leave rows without an OOB prediction
A row has an OOB prediction only if at least one tree left it out. With T trees, the chance that a row is in every bootstrap sample is about 0.632^T. For T = 10 this is tiny, but across thousands of rows it can still happen, and for T = 3 it is likely. scikit-learn warns when some samples never appear out-of-bag, and it reports NaN or zero probabilities for those rows. Use at least 100 trees when you rely on OOB.
OOB requires bootstrap sampling
If you set bootstrap=False, every tree sees every row. There are no OOB rows, and scikit-learn raises an error when oob_score=True. If you use max_samples to draw smaller bootstrap samples, the OOB set gets larger, and the estimate stays valid.
Correlated rows break the estimate
The OOB estimate treats rows as independent. Suppose your data has groups, such as several records per patient, or a time series where neighbors resemble each other. A held-out row then has near-duplicates in the trees' training samples. The tree has effectively seen it, and the OOB score becomes too optimistic. In that case use a group-aware or time-aware split, such as GroupKFold or TimeSeriesSplit, and ignore the OOB number.
Preprocessing leaks
Any step fit on the whole training set before the forest, such as target encoding, feature selection by label correlation, or imputation of the target, lets information from the OOB rows reach the trees. The OOB score then overstates performance. Put such steps inside a pipeline and use cross-validation for the honest estimate.
Tuning on OOB overfits the OOB score
OOB is convenient for comparing settings. If you try hundreds of configurations and pick the best OOB score, that best score is optimistically biased, as with any validation set. Keep a final test set that you use once.
Warm start and growing the forest
With warm_start=True you can add trees by raising n_estimators and calling fit again. The OOB score is recomputed over all trees. This lets you plot OOB error against the number of trees cheaply, as shown below.
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
X, y = load_breast_cancer(return_X_y=True)
clf = RandomForestClassifier(
warm_start=True, oob_score=True, random_state=0, n_jobs=-1
)
for n in [25, 50, 100, 200, 400]:
clf.set_params(n_estimators=n)
clf.fit(X, y)
print(f"{n:>4} trees: OOB error = {1 - clf.oob_score_:.4f}")Typically the error falls quickly and then levels off. Once the curve is flat, more trees add cost without improving accuracy. This is the standard way to pick n_estimators: more trees never hurt generalization much, so choose the point where the curve flattens.
OOB compared with other validation methods
| Method | Extra model fits | Uses all rows for validation | Handles grouped or time data | Notes |
|---|---|---|---|---|
| Hold-out test set | 0 | No | Yes, if split correctly | Wastes data. High variance on small sets. |
| 5-fold cross-validation | 5 forests | Yes | Yes, with group or time splitters | Most flexible. 5 times the cost. |
| OOB estimate | 0 | Yes | No | Cheap. Assumes independent rows. |
OOB suits fast iteration on independent, tabular data. For final reporting, or when rows are not independent, use a proper held-out test set or an appropriate cross-validation scheme.
Summary of the main points
- Each tree omits about 36.8% of rows from its bootstrap sample. Those rows are its OOB samples.
- A row's OOB prediction aggregates only the trees that did not train on it.
oob_score_andoob_decision_function_expose the result in scikit-learn.- The estimate costs no extra fitting and is slightly pessimistic.
- It fails when rows are correlated or when preprocessing leaks label information.
Exercise
A forest is trained with 200 trees on 1,000 independent rows. Roughly how many trees will have a given row out-of-bag, and why does the OOB score for that row use fewer trees than the full forest?
Show answer
About 36.8% of 200, so roughly 74 trees. The other trees included the row in their bootstrap sample and have seen its label, so using them would make the prediction optimistic. Only the roughly 74 trees that never saw the row can give an unbiased prediction for it.
Exercise
Your dataset has 10 measurements per patient, and you split no groups. The OOB accuracy is 0.97, but accuracy on new patients is 0.82. Explain the gap and name a better validation method.
Show answer
Measurements from the same patient are similar. When a row is out-of-bag for a tree, other rows from the same patient are usually in that tree's bootstrap sample, so the tree has effectively seen that patient. This inflates the OOB score. Use GroupKFold with patient ID as the group, so that all of a patient's rows fall in the same fold.
Exercise
You call RandomForestClassifier(nestimators=5, oobscore=True) on 50,000 rows. What problem can occur, and how do you fix it?
Show answer
With only 5 trees, some rows can appear in every bootstrap sample, so they have no OOB prediction. The aggregated OOB prediction is also based on only about 2 trees per row, so it is noisy and pessimistic. Increase n_estimators to at least 100, and preferably a few hundred.