Machine LearningEnsemble Learning & Model Evaluation
What is out-of-bag (OOB) error in Random Forests?
Question 281 of 307 · Updated
On this page
- 1. Bootstrap sampling
- 2. Why are about 36.8% of rows OOB for each tree?
- 3. How is an OOB prediction produced?
- 4. How do you calculate OOB error?
- Classification
- Regression
- Small example
- 5. OOB error versus validation split and cross-validation
- 6. Practical Python example with scikit-learn
- 7. OOB error and class imbalance
- 8. OOB error and feature importance
- 9. Does OOB error become better as you add more trees?
- 10. Important assumptions and limitations
- 11. Production selection guidance
- 12. Common interview questions
- Key takeaway
Out-of-bag (OOB) error is an internal estimate of a Random Forest's prediction error. Each tree is trained on a bootstrap sample of the training data. Rows left out of a particular tree's sample are that tree's out-of-bag observations. For each training row, the forest combines predictions only from trees that did not train on that row, then compares the result with the true target.
It provides a useful validation estimate without a separate validation fold for every tree. It is convenient, but it does not replace a final untouched test set.
1. Bootstrap sampling#
Suppose the training set contains five observations:
A bootstrap sample draws five times with replacement from these same five rows. One tree might receive:
A appears twice, while C is not selected. For this tree:
- In-bag: A, B, D, E
- Out-of-bag: C
The tree is trained using only its in-bag sample. It can then predict C because C was not used to fit that tree. A different tree draws a different bootstrap sample and usually leaves out a different subset.
2. Why are about 36.8% of rows OOB for each tree?#
For a dataset with rows, a bootstrap sample draws times with replacement. For one particular row, the probability of not being selected on one draw is . The probability of not being selected in any of the draws is
As becomes large,
So a row is OOB for approximately 36.8% of trees and appears at least once in approximately 63.2% of trees.
For 1,000 training rows and 100 trees, a particular row is expected to be OOB for about
trees. The exact number varies by row and random seed.
3. How is an OOB prediction produced?#
Imagine one customer has the true label Fraud. Across a forest of 100 trees, suppose 38 trees did not include this customer in their bootstrap samples. Only those 38 trees are allowed to vote for this customer's OOB prediction.
Suppose their predictions are:
- Fraud: 30 votes
- Not fraud: 8 votes
The OOB predicted class is Fraud. Its OOB probability estimate is approximately
The other 62 trees are excluded for this row because they trained on it.
For regression, the OOB prediction is typically the average of predictions from trees for which the row was OOB.
4. How do you calculate OOB error?#
Classification#
For each training observation, aggregate only its OOB tree predictions. Compare the predicted class with its true class.
If 1,000 rows receive OOB predictions and 85 are classified incorrectly:
The corresponding OOB accuracy is
Regression#
For regression, aggregate OOB predictions and compare them with actual target values. A common metric is OOB mean squared error:
You can also calculate RMSE or from OOB predictions. Choose a metric that matches the business problem.
Small example#
Suppose five observations have these true and OOB-predicted classes:
- A: 1, predicted 1 — correct
- B: 0, predicted 0 — correct
- C: 1, predicted 0 — incorrect
- D: 1, predicted 1 — correct
- E: 0, predicted 1 — incorrect
There are two errors among five observations:
This tiny example illustrates the calculation. With few trees or very small datasets, OOB predictions can be noisy or unavailable for some observations.
5. OOB error versus validation split and cross-validation#
OOB evaluation uses training rows left out of each tree's bootstrap sample. It produces an internal estimate from a single fitted forest and is convenient for monitoring performance as trees are added.
A validation split holds out a dedicated subset. It is straightforward to interpret, but the estimate depends on the particular split and fewer rows are available for fitting.
K-fold cross-validation trains separate models while holding out a different fold each time. It costs more computation but provides a useful view of variation across splits and supports broader model comparisons.
OOB can be a fast internal estimate and help tune some Random Forest settings. Cross-validation is often preferable when comparing model families, complex preprocessing pipelines, or hyperparameters. A final untouched test set remains important for final performance reporting after model selection.
6. Practical Python example with scikit-learn#
For classification, enable bootstrap sampling and OOB scoring:
PYTHONfrom sklearn.datasets import make_classification from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import ( accuracy_score, balanced_accuracy_score, classification_report, confusion_matrix, ) from sklearn.model_selection import train_test_split X, y = make_classification( n_samples=3000, n_features=20, n_informative=8, weights=[0.90, 0.10], random_state=42, ) X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.20, stratify=y, random_state=42, ) model = RandomForestClassifier( n_estimators=500, bootstrap=True, oob_score=True, class_weight="balanced", random_state=42, n_jobs=-1, ) model.fit(X_train, y_train) print("OOB accuracy:", model.oob_score_) # OOB probabilities use only trees that did not train # on each corresponding training row. oob_probabilities = model.oob_decision_function_ oob_predictions = model.classes_[ oob_probabilities.argmax(axis=1) ] print( "OOB balanced accuracy:", balanced_accuracy_score(y_train, oob_predictions) ) # The test set is not used to fit the forest. test_predictions = model.predict(X_test) print("Test accuracy:", accuracy_score(y_test, test_predictions)) print(classification_report(y_test, test_predictions)) print(confusion_matrix(y_test, test_predictions))
Implementation details:
- Bootstrap sampling must be enabled for the usual OOB mechanism.
- OOB scoring must be requested.
- For scikit-learn's RandomForestClassifier, the default OOB score is accuracy.
- For RandomForestRegressor, the default OOB score is .
- The OOB decision function exposes class probabilities aggregated from OOB trees.
- With too few trees, some rows may not have a reliable OOB prediction. Check for missing values in the OOB decision function and increase the number of trees when needed.
- Supported scikit-learn versions allow a callable OOB metric. Check the installed version's API for the exact signature.
7. OOB error and class imbalance#
Accuracy can be misleading when classes are imbalanced.
Suppose a fraud dataset contains 990 legitimate transactions and 10 fraudulent transactions. A classifier that predicts every transaction as legitimate achieves
accuracy, but detects zero fraud. An OOB accuracy of 99% would not prove the model is useful.
For imbalanced classification, inspect OOB predictions using:
- Recall for the minority class
- Precision and F1-score
- Balanced accuracy
- Precision-recall AUC
- Confusion matrix
- Class-specific calibration or probability quality, where relevant
Class weighting can help a forest learn minority-class patterns, but it does not automatically make OOB estimates representative of every deployment population. Standard bootstrap sampling is not necessarily stratified by class. If rare classes receive too few OOB votes, estimates can be unstable.
For important imbalanced applications, compare OOB results with stratified cross-validation and a representative held-out test set. Choose the decision threshold using validation data, not the final test set.
8. OOB error and feature importance#
OOB observations can also help estimate permutation feature importance:
- Calculate OOB performance using the original feature values.
- Randomly shuffle one feature among the OOB observations.
- Recalculate OOB performance with that feature disrupted.
- Measure the drop in performance.
- Repeat to estimate variability.
If shuffling a feature substantially reduces OOB performance, the model may rely on that feature.
Interpret carefully:
- Correlated features can substitute for one another, making individual importance appear smaller.
- High-cardinality or noisy features can create misleading importance in some methods.
- Permutation importance measures model reliance, not causality.
- Target-based encodings performed before bootstrap sampling can leak target information across in-bag and OOB rows. Fit target-dependent preprocessing inside each resampling boundary or use a separate validation/test strategy.
- For high-stakes conclusions, validate importance on a separate held-out dataset and examine stability across resamples.
A 2024 PeerJ Computer Science study documents how target-based categorical encoding before bagging can bias OOB error and variable-importance estimates.
9. Does OOB error become better as you add more trees?#
Often, the OOB estimate becomes more stable as the number of trees increases, because each observation receives predictions from more OOB trees.
For a forest with trees, each row receives roughly OOB predictions on average:
- 100 trees: about 37 OOB predictions per row.
- 500 trees: about 184 OOB predictions per row.
- 1,000 trees: about 368 OOB predictions per row.
These are expectations, not guarantees. Plot OOB error as trees are added. If it stabilizes, adding many more trees may provide little improvement. A stable curve does not prove the model will generalize under future distribution shift.
10. Important assumptions and limitations#
- Independent, representative observations: ordinary bootstrap sampling assumes rows can be resampled independently. Repeated measurements from the same customer, patient, device, or time series can violate this assumption.
- No leakage before sampling: learned preprocessing—including target encoding, feature selection, imputation, and supervised transformations—must not allow OOB rows to influence the model that predicts them.
- Enough trees: with too few trees, some observations may have few or no OOB predictions, making estimates noisy.
- Representative training distribution: OOB evaluation estimates performance under a sampling process related to the training data. It cannot predict arbitrary future distribution shift.
- Correct metric: accuracy alone is often unsuitable for imbalanced or cost-sensitive problems.
- Bootstrap must be enabled: forests trained without bootstrap samples do not have the usual OOB interpretation.
- Tuning optimism: repeatedly selecting models and settings based on the same OOB estimate can overfit the estimate itself.
- Time and group structure: random row-level bootstrap can put records from the same entity or later time periods into training and OOB sets. For grouped or temporal prediction, use group-aware or time-aware validation too.
11. Production selection guidance#
- Reserve a final test set using a split appropriate to the data's time and group structure.
- Fit all preprocessing within the training boundary.
- Train a Random Forest with bootstrap sampling and OOB scoring enabled.
- Track OOB error as the forest grows and ensure enough OOB votes are available per observation.
- Inspect class-specific metrics, calibration where relevant, and error slices—not only overall accuracy.
- Compare the OOB estimate with cross-validation or a representative validation set.
- Tune hyperparameters without repeatedly optimizing against the final test set.
- Evaluate the selected model once on the untouched test set.
- Monitor live performance when labels become available; OOB error is not a substitute for production monitoring.
- Record the sampling strategy, random seed, preprocessing, metric definitions, and model version for reproducibility.
12. Common interview questions#
Why is a row OOB for about 36.8% of trees? Because the probability it is not selected in draws with replacement from rows is , which approaches .
Does a tree predict a row it used for training when calculating OOB error? No. Only trees whose bootstrap samples excluded that row contribute to its OOB prediction.
Is OOB error the same as test error? No. It is an internal estimate constructed from training observations and their OOB trees. Keep a final untouched test set for final evaluation.
Can OOB evaluation be used for regression? Yes. OOB predictions can be aggregated for regression and evaluated with MSE, RMSE, or .
Does OOB eliminate cross-validation? Not in every situation. It is convenient for bootstrap-based forests, but cross-validation remains valuable for comparing pipelines, model families, and settings, especially with grouped or temporal data.
Why might OOB error look excellent on an imbalanced dataset? A model can achieve high accuracy by predicting the majority class. Inspect minority-class recall, precision, balanced accuracy, and precision-recall performance.
Key takeaway#
OOB error estimates Random Forest generalization by predicting each training row only with trees whose bootstrap samples did not contain that row. Since each row is excluded from roughly 36.8% of trees, the forest can build internal validation predictions without a separate validation split. It is efficient and valuable for model diagnostics, but leakage, class imbalance, dependence between rows, too few trees, and repeated tuning can undermine it. Use OOB alongside appropriate cross-validation and a final untouched test set.
References
- 1.scikit-learn — OOB Errors for Random Forestsscikit-learn.org
- 2.Google for Developers — Out-of-bag evaluationdevelopers.google.com
- 3.Breiman — Random Forestsstat.berkeley.edu
- 4.
- 5.
- 6.scikit-learn — RandomForestClassifier APIscikit-learn.org
- 7.scikit-learn — RandomForestRegressor APIscikit-learn.org
Related questions
Explore other topics:Forward Deployed EngineeringDeep LearningMLOps