AI & Machine Learning Master Course — 072. Bagging and random forests
Smartyfy AI & Machine Learning Master Course
Course ID: smartyfy-ai-ml-master-200
Lesson 072: Bagging and random forests
Prerequisites: Lesson 071. Learning outcome: Train bootstrap ensembles and interpret out-of-bag estimates carefully.
1. Bagging perturbs training data and aggregates predictions
Bootstrap aggregating, or bagging, fits multiple learners to bootstrap samples of the training dataset. A bootstrap sample of size n draws n rows with replacement, so some original rows appear several times and others are absent. Averaging regression predictions or aggregating classification outputs can reduce instability of a sensitive base learner.
Decision trees are a useful example because small training changes can alter early splits and many later predictions. Bagging does not make the training evidence larger in the sense of collecting new independent observations. It creates alternative fitted views of the same finite dataset.
2. Random forests add feature-level randomness
A random forest usually combines bootstrap sampling with a randomly selected subset of candidate features at each split. Within that candidate subset, a tree seeks a good split under its impurity criterion. Restricting candidate features can reduce similarity between trees, especially when one strong feature would otherwise dominate every root split.
The trade-off is that an individual tree may become weaker when useful features are unavailable at a split. The ensemble benefits only if the resulting diversity and aggregation compensate. max_features, leaf-size controls, depth, and bootstrap settings therefore interact rather than acting as independent guarantees of accuracy.
In scikit-learn's RandomForestClassifier, class probabilities are averaged across trees before the final class decision. This is more specific than saying every implementation simply takes a majority vote of hard tree labels. Inspect the aggregation definition when interpreting output probabilities or reproducing another library.
3. Understand which observations are out of bag
For one bootstrap sample of n draws from n rows, the probability that a particular row is never selected is (1−1/n)^n, approaching e⁻¹≈0.368. Thus a tree sees about 63.2% unique training rows on average for large n, even though the sample contains n draws. The remaining rows are out of bag for that tree.
An out-of-bag prediction for a row aggregates only trees whose bootstrap samples omitted that row. This creates a useful internal assessment without explicitly reserving a separate fold for every tree. With 100 trees and 210 training rows, the expected number of eligible trees per row is about 36.70, not exactly the same count for every row.
With too few trees, some rows may have little or no out-of-bag support. Check warnings and the validity of stored OOB predictions. An OOB score is not computed from the same ensemble composition for every training row, so its interpretation differs from applying the full forest to a common independent validation set.

4. OOB evaluation has boundaries and limitations
OOB separation occurs at the bootstrap-row level. It does not automatically protect against related customer rows, near-duplicate images, temporal dependence, or preprocessing fitted using all training rows before the forest. If those operations expose information from an OOB row to a tree, the internal assessment can be optimistic for the intended task.
Using OOB scores to choose hyperparameters also turns them into development evidence. Repeatedly checking many settings and quoting the best OOB score as independent confirmation repeats the selection problem seen with cross-validation. Keep a suitable external final assessment when that is needed.
An OOB estimate can still be valuable for efficient development and diagnostics under appropriate sampling assumptions. The right conclusion is not to reject it, but to describe which learning stages and dependence structures it actually leaves out.
5. Control forest complexity and operational cost
More trees generally reduce the Monte Carlo variability of the finite ensemble, but increase memory and prediction work. They do not remove shared bias or guarantee better calibration. Tree depth and minimum leaf size can strongly affect both fit and resource use; inspect them rather than assuming tree count is the only important setting.
Impurity-based feature importance can favor variables with many available split points and can divide credit unpredictably among correlated inputs. It is not causal importance. Later interpretation lessons develop better assessment methods; for now, do not attach a business explanation to a large importance bar without additional evidence.
Numerical feature scaling is often unnecessary for ordinary threshold trees, but categorical representation, missing-value policy, and prediction-time availability remain essential. Version-specific native missing-value support should be verified before relying on it. This example uses complete numerical data to keep the ensemble mechanism explicit.
CPU lab: compare training, OOB, and validation evidence
The script generates 300 synthetic observations and holds out ninety for development validation. It fits 100 trees on the other 210 rows using bootstrap sampling, square-root feature subsampling, and minimum leaf size two. It runs locally with NumPy 2.3.5 and scikit-learn 1.8.0, with one parallel job.
Training accuracy is about 0.9952, OOB accuracy 0.8476, and validation accuracy 0.9222 in this run. Those different values reflect different assessment paths and finite samples; OOB need not equal or always exceed external validation. Assertions verify finite OOB probabilities that sum to one. No hyperparameter choice is made from these scores, and no real-world generalization claim is implied.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
X,y=make_classification(n_samples=300,n_features=8,n_informative=5,n_redundant=0,random_state=72)
xt,xv,yt,yv=train_test_split(X,y,test_size=.3,stratify=y,random_state=72)
forest=RandomForestClassifier(n_estimators=100,max_features='sqrt',min_samples_leaf=2,
bootstrap=True,oob_score=True,n_jobs=1,random_state=72).fit(xt,yt)
print('Training/OOB/validation accuracy:',round(forest.score(xt,yt),4),
round(forest.oob_score_,4),round(accuracy_score(yv,forest.predict(xv)),4))
n=len(yt)
print('One-tree omission probability:',round((1-1/n)**n,6))
print('Expected OOB trees per row:',round(100*(1-1/n)**n,4))
assert np.all(np.isfinite(forest.oob_decision_function_))
np.testing.assert_allclose(forest.oob_decision_function_.sum(axis=1),1)
print('Validation probability shape:',forest.predict_proba(xv).shape)
Four practice questions with worked answers
Practice 1
Why does a size-n bootstrap sample contain fewer than n unique rows on average?
Answer: Sampling is with replacement, so some selected rows repeat. A particular original row is omitted with probability (1−1/n)^n, leaving an expected unique fraction 1−(1−1/n)^n. The sample has n draws but not n distinct new observations.
Practice 2
With 100 trees and omission probability 0.367, how many OOB trees are expected per row?
Answer: The expected count is 100×0.367=36.7. Actual counts vary by row and random draw. This expectation does not guarantee that every row has exactly 37 predictions or enough support when the ensemble is very small.
Practice 3
A scaler is fitted on every training row before computing forest OOB predictions. What should be considered?
Answer: The scaler has used information from rows that individual trees call out of bag. Even though scaling may not change ideal tree partitions much, the general OOB workflow no longer excludes all learned preprocessing information. More consequential global feature selection or imputation can create stronger leakage; evaluate the complete intended pipeline appropriately.
Practice 4
Why does tuning many forests by OOB score require a separate final assessment?
Answer: The chosen configuration is selected using those OOB outcomes, so its winning score is selection-influenced. OOB can serve as development evidence, but cannot simultaneously remain untouched confirmation after repeated adaptive choices. Use an appropriate holdout or outer procedure for the final claim.
Five multiple-choice questions
Question 1
What does bootstrap sampling use?
- A. Sampling with replacement
- B. Only the rarest class
- C. A disjoint partition with every row once
Correct: A. Repeated and omitted rows create different training samples for the base learners.
Question 2
What additional randomness distinguishes a typical random forest from basic bagged trees?
- A. A random evaluation metric
- B. Feature subsets considered at splits
- C. Random target labels
Correct: B. Candidate-feature subsampling can decorrelate trees without changing the observed targets.
Question 3
Which trees contribute to a row’s OOB prediction?
- A. Every tree in the forest
- B. Trees whose bootstrap sample omitted that row
- C. Only trees that predicted it correctly
Correct: B. Eligibility is determined by training inclusion, not by the observed prediction result.
Question 4
Does OOB automatically enforce new-customer separation?
- A. No, related rows may still appear in a tree’s training sample
- B. Only if there are 100 trees
- C. Yes, bootstrap sampling identifies customers
Correct: A. Row-level omission is not the same as group-level independence.
Question 5
Which property does adding more trees not establish by itself?
- A. A larger number of stored tree components
- B. More component outputs to aggregate when all trees are used
- C. Removal of shared bias or calibrated probabilities
Correct: C. More members cannot automatically fix common modeling errors or validate probability reliability.
Common pitfalls
Do not describe bootstrap copies as newly collected evidence. Do not equate OOB predictions with a universally independent final test. Avoid using impurity importance as a causal ranking or assuming more trees solve every modeling and data-quality problem.
Summary
Bagging aggregates bootstrap-fitted learners; random forests also randomize candidate features. OOB predictions provide useful internal evidence under specific boundaries. Control complexity, audit dependence and preprocessing, and retain honest assessment after any OOB-guided selection.