Sub topic 11
A worked example with scikit-learn
This chapter trains a random forest on a real dataset, checks it with an out-of-bag (OOB) score and a test set, and compares it with a single tree. It assumes you know supervised learning basics, Python and NumPy, and accuracy as a metric. It also assumes you have met bootstrap sampling, feature subsampling and OOB estimation in earlier chapters.
The workflow
The dataset is scikit-learn's breast cancer data. It has 569 samples, 30 numeric features, and a binary label. The steps are:
- Split the data into training and test sets.
- Fit a forest on the training set.
- Read the OOB score.
- Score the held-out test set.
- Compare with a single tree using cross-validation.
Seeing the mechanism by hand
Before using the library class, build a small forest yourself. Each tree gets a bootstrap sample, and max_features="sqrt" makes each split consider a random subset of features.
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
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
)
rng = np.random.default_rng(0)
trees = []
for i in range(25):
idx = rng.integers(0, len(X_train), size=len(X_train)) # bootstrap sample
tree = DecisionTreeClassifier(max_features="sqrt", random_state=i)
trees.append(tree.fit(X_train[idx], y_train[idx]))
votes = np.stack([t.predict(X_test) for t in trees])
pred = (votes.mean(axis=0) > 0.5).astype(int) # majority vote for 0/1 labels
print("Hand-built forest accuracy:", (pred == y_test).mean())The mean of 0/1 votes is the fraction of trees voting for class 1, so comparing it to 0.5 is a majority vote. This trick works only for binary labels coded 0 and 1.
Using RandomForestClassifier
The library class does the same work and adds OOB scoring and parallel training.
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))Points to note:
oob_score=Truemakesfitcomputeoob_score_. Each training sample is scored only by the trees whose bootstrap sample left it out.n_jobs=-1trains trees on all CPU cores. It does not change the result.random_state=0makes the run repeatable.stratify=ykeeps the class proportions the same in both splits.
The two accuracies should be close, because the OOB score is a validation estimate made from the training data alone. They need not match exactly. The test set here has only 114 samples, so its score is noisy.
Comparing with a single tree
A single fully grown tree fits the training data almost perfectly. Its predictions change a lot from one sample to the next. Cross-validation shows the effect of averaging.
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
from sklearn.tree import DecisionTreeClassifier
X, y = load_breast_cancer(return_X_y=True)
tree = DecisionTreeClassifier(random_state=0)
forest = RandomForestClassifier(n_estimators=200, random_state=0, n_jobs=-1)
for name, model in [("single tree", tree), ("random forest", forest)]:
scores = cross_val_score(model, X, y, cv=5)
print(f"{name}: mean={scores.mean():.3f}, std={scores.std():.3f}")Expect the forest to have a higher mean. Its standard deviation across folds is usually lower too, though with five folds that comparison is rough.
Common errors
| Mistake | Effect | Fix |
|---|---|---|
| Reading `oob_score_` without `oob_score=True` | `AttributeError` | Set `oob_score=True` before `fit` |
| Using too few trees | Noisy OOB score and predictions | Start at 200 to 500 trees |
| Judging the forest only on training accuracy | Looks near 100%, hides overfitting | Use OOB, test, or cross-validation scores |
| Tuning on the test set repeatedly | Optimistic test score | Tune with OOB or cross-validation, then test once |
Exercise
Why is the OOB score a fair estimate of performance on new data, even though it is computed from the training set?
Show answer
Each sample is predicted only by trees whose bootstrap sample did not include it. Those trees never saw that sample during training, so its prediction is made without leakage, as in a validation set.
Exercise
In the hand-built forest, what would go wrong if you removed the bootstrap sampling and kept max_features="sqrt" with the same data in every tree?
Show answer
The trees would differ only through feature randomness, so they would be more correlated. Averaging correlated trees reduces variance less. The OOB idea would also no longer apply, since every tree would see every sample.