Sub topic 11
A Worked Example with scikit-learn
This chapter puts the earlier ideas into one runnable workflow: split the data, train a forest, check it with the out-of-bag (OOB) score, compare it with a single tree, and tune the main settings. It assumes you know the following:
- How a decision tree splits data, and what bagging and feature subsampling do.
- Basic NumPy and scikit-learn usage (
fit,predict,score). - Accuracy as a classification metric.
The dataset is scikit-learn's built-in breast cancer data. It has 569 samples, 30 numeric features, and a binary label (0 = malignant, 1 = benign). It has no missing values and needs no scaling, so the forest is the only thing being tested.
The workflow
The steps below are the same ones you would use on your own data. The OOB score and the test score are two separate checks on the same model.
Step 1: Split the data
Hold out a test set before doing anything else. The stratify=y argument keeps the class proportions the same in both parts, which matters when one class is rarer than the other.
Step 2: Train a forest and read the OOB score
Each tree is fit on a bootstrap sample, which leaves out roughly 37% of the training rows. Those rows are "out of bag" for that tree. With oob_score=True, scikit-learn predicts each training row using only the trees that did not see it, then reports the accuracy of those predictions.
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))Both numbers should be close, typically in the mid-90% range on this dataset. The OOB score uses only training data, so it costs no extra data. The test score comes from rows the model never touched. With 114 test rows, one mistake changes the test accuracy by about 0.9 percentage points. For that reason, treat a gap of one or two points between the two as noise.
Step 3: Check the forest against a single tree
A forest should beat one fully grown tree, and it should vary less between data splits. Cross-validation measures both effects. This example uses the whole dataset, because cross_val_score does its own splitting.
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 single tree to land around 0.91 to 0.93 and the forest around 0.95 to 0.97. The forest's standard deviation across folds is usually smaller too. This is the variance reduction from averaging that earlier chapters described, now measured on real data.
Step 4: Look at predictions beyond accuracy
A forest can also report class probabilities. For classification, predict_proba averages the per-tree class probabilities. Each tree's probability is the class fraction in the leaf the sample lands in. The class prediction is the class with the highest averaged probability.
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report
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, n_jobs=-1, random_state=0)
clf.fit(X_train, y_train)
print(classification_report(y_test, clf.predict(X_test), target_names=["malignant", "benign"]))
print("First three rows, [P(malignant), P(benign)]:")
print(clf.predict_proba(X_test[:3]).round(3))In a medical setting, the recall of the malignant class matters more than overall accuracy. The report shows it directly. If a missed malignant case costs more than a false alarm, you can threshold predict_proba yourself instead of accepting the default 0.5 cut.
Step 5: Tune with the OOB score
The number of trees is the one setting you can almost always raise safely. More trees reduce the variance of the average and never make the forest overfit more, but they add training and prediction time. The warm_start=True option keeps the existing trees and adds new ones, so you can track the OOB score as the forest grows without retraining from scratch.
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(
warm_start=True, oob_score=True, n_jobs=-1, random_state=0
)
for n in [25, 50, 100, 200, 400]:
clf.set_params(n_estimators=n)
clf.fit(X_train, y_train)
print(f"{n:>4} trees OOB accuracy = {clf.oob_score_:.4f}")The curve typically rises quickly and then flattens, with small fluctuations. Once it is flat, extra trees only cost time. Do not choose n_estimators by picking the single best value on a noisy curve.
The other settings control how complex each tree is and how correlated the trees are. This table lists the ones you will touch most often.
| Parameter | Default (classifier) | Effect of increasing it |
|---|---|---|
| `n_estimators` | 100 | Lower variance, slower training and prediction |
| `max_features` | `"sqrt"` | Stronger individual trees, but more correlation between them |
| `max_depth` | `None` (grow fully) | Deeper trees, lower bias, higher per-tree variance |
| `min_samples_leaf` | 1 | Smoother trees, more bias, less overfitting to noise |
| `max_samples` | `None` (use n rows) | Smaller bootstrap samples, more diverse trees, faster training |
For regression, RandomForestRegressor uses max_features=1.0 by default, which means all features are considered at each split. Reducing it is a common tuning step there.
When the OOB curve is not enough, use a cross-validated search. A small grid on max_features and min_samples_leaf is usually the most productive:
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import GridSearchCV, 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
)
grid = GridSearchCV(
RandomForestClassifier(n_estimators=200, random_state=0),
param_grid={
"max_features": ["sqrt", 0.5, None],
"min_samples_leaf": [1, 3, 5],
},
cv=5,
n_jobs=-1,
)
grid.fit(X_train, y_train)
print("Best parameters:", grid.best_params_)
print("Best CV accuracy:", round(grid.best_score_, 4))
print("Test accuracy:", round(grid.score(X_test, y_test), 4))On a dataset this clean, many combinations score within noise of each other. Prefer the simplest setting among near-ties, and use the test set only once, at the end.
Common errors
- Evaluating on training data.
clf.score(X_train, y_train)is usually close to 1.0 for a forest, because each tree memorizes its bootstrap sample. It says nothing about generalization. Use the OOB score, cross-validation, or a held-out test set. - Tuning on the test set. If you adjust settings after looking at test accuracy, the test score is no longer an honest estimate. Tune with the OOB score or cross-validation, then test once.
- Too few trees for the OOB score. With very few trees, some rows are in every bag, and scikit-learn warns that some inputs have no OOB prediction. Use at least a few dozen trees.
- Forgetting
random_state. Without it, results change between runs, which makes comparing two settings unreliable. Set it while you experiment. - Scaling features "just in case". Trees split on thresholds, so monotonic transformations such as standardization do not change the result. It is harmless but unnecessary.
- Using
n_jobson tiny data. Parallel training has overhead. For a few hundred rows,n_jobs=-1may be no faster than a single core.
Check your understanding
Exercise
You train a RandomForestClassifier with oobscore=True and get an OOB accuracy of 0.955. Your colleague reports that clf.score(Xtrain, y_train) is 1.000 and says the model is clearly overfitting. Which number should you trust for estimating performance on new data, and is the colleague's conclusion justified?
Show answer
Trust the OOB accuracy (0.955). It predicts each training row using only trees that did not see that row, so it estimates generalization. The training score of 1.000 is expected for a forest of fully grown trees, because each tree has memorized its own bootstrap sample and every row is seen by about 63% of the trees. The colleague's conclusion is not justified by that number alone. A forest can score 1.000 on its training data and still generalize well, as the OOB score shows. A real warning sign would be a large gap between the OOB or test score and the cross-validation score of a simpler model.
Exercise
Write the code change needed to make the Step 5 loop also print the test accuracy for each forest size. Why is it still a mistake to pick n_estimators by choosing the size with the highest test accuracy?
Show answer
Add print(f"{n:>4} trees test accuracy = {clf.score(Xtest, ytest):.4f}") inside the loop after the fit call. Choosing the size with the best test accuracy uses the test set to make a modeling decision, so the final test score becomes optimistically biased. With 114 test rows, differences of one or two samples are also just noise. Choose n_estimators from the OOB curve or cross-validation, where the curve flattens, and keep the test set for one final evaluation.