Sub topic 2
Combining Tree Predictions in a Random Forest
Assume you know features, labels, training and test sets, classification accuracy, and basic averaging. A random forest combines many decision trees so that their individual errors have less effect on the final prediction.
Combining predictions by voting and averaging
For classification, each tree predicts a class. The forest uses majority voting:
| Tree | Prediction |
|---|---|
| 1 | benign |
| 2 | malignant |
| 3 | benign |
The forest predicts benign because it received two of three votes. With many trees, the vote can be viewed as the class with the highest average indicator value.
For regression, each tree predicts a number. The forest averages those numbers. If three trees predict 10, 12, and 14, the forest predicts 12.
from sklearn.ensemble import RandomForestClassifier
forest = RandomForestClassifier(n_estimators=200, random_state=0)
forest.fit(X_train, y_train)
predictions = forest.predict(X_test)Averaging mainly reduces variance, which is the tendency of a model to change greatly when its training data changes.
Random feature subsets decorrelate the trees
Bagging gives each tree a different bootstrap sample, created by sampling training rows with replacement. However, trees can still become similar when one strong feature is available. Similar trees make similar mistakes, reducing the benefit of averaging.
At each split, a random forest therefore lets a tree inspect only a random subset of features. Different trees may choose different useful splits. This decorrelates the trees, meaning their errors are less alike.
The complete random forest algorithm
For each tree, the algorithm samples rows, grows a tree while selecting random features at each split, and stores the fitted tree. It then combines all tree predictions by voting or averaging.
Out-of-bag error
A bootstrap sample contains repeated rows, so some training rows are omitted from each tree. These omitted rows are that tree’s out-of-bag, or OOB, examples. The forest can predict each row using only trees that did not train on it.
The resulting OOB score estimates generalization performance without a separate validation set.
from sklearn.ensemble import RandomForestClassifier
forest = RandomForestClassifier(
n_estimators=300,
oob_score=True,
random_state=0
)
forest.fit(X_train, y_train)
print(forest.oob_score_)Exercise
Why does a forest use random feature subsets as well as bootstrap samples?
Show answer
They make the trees less correlated, so averaging their predictions reduces variance more effectively.