Random Forest
Random Forest is an ensemble learning algorithm that aggregates predictions across many decision trees trained independently to improve generalization and stability. It mitigates single-tree overfitting through two sources of randomness: bootstrap sampling of training instances (bagging) and random feature subsampling at every split, which decorrelates trees and lowers ensemble variance.
Study Card: Random Forest
Direct Answer
Random Forest is an ensemble algorithm that combines many decision trees (typically deep, low-bias / high-variance trees) via majority voting (classification) or averaging (regression). It introduces two complementary forms of randomness:
- Bootstrap Aggregating (Bagging): Each tree trains on a bootstrap resample of size drawn with replacement from the training data.
- Feature Subsampling: At each split, a tree evaluates only a random subset of features (typically for classification or for regression).
Mathematically, if identically distributed trees each have variance and pairwise correlation , the ensemble average has variance:
Increasing eliminates the second term, while feature subsampling lowers (preventing strong predictors from making every tree look alike), substantially reducing overall prediction variance without adding much bias.
Key Terms
- Ensemble Learning: Combining multiple base models (for Random Forest, typically deep decision trees) to achieve stronger generalization than any single model.
- Bagging (Bootstrap Aggregating): Training models on random samples drawn with replacement from the original dataset.
- Feature Randomness: Restricting split selection at every tree node to a fresh random feature subset to decorrelate trees.
- Decision Tree: Hierarchical axis-aligned partitioning model that splits feature space via impurity reduction (Gini, entropy, or MSE).
- Out-of-Bag (OOB) Score: Validation estimate computed by evaluating each sample using only the trees whose bootstrap draw excluded it (~36.8% of trees per sample).
Example
Suppose you predict customer churn using demographics and product usage. A single unpruned decision tree easily memorizes quirks in the training set. A Random Forest instead trains 100 trees on distinct bootstrap samples while forcing each split to consider only a random subset of features—so dominant features do not monopolize the root of every tree. Aggregating predictions across these diverse trees yields higher accuracy and stability, and the OOB score estimates generalization without needing a separate validation split.
Code Implementation
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.datasets import make_classification
from sklearn.metrics import accuracy_score
# Generate synthetic classification data
X, y = make_classification(n_samples=1000, n_features=10, n_informative=5, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Train Random Forest Classifier with OOB evaluation
rf_classifier = RandomForestClassifier(
n_estimators=100,
max_depth=5,
random_state=42,
oob_score=True,
)
rf_classifier.fit(X_train, y_train)
# Evaluate on test set and OOB samples
y_pred = rf_classifier.predict(X_test)
print(f"Test Accuracy: {accuracy_score(y_test, y_pred):.4f}")
print(f"OOB Score: {rf_classifier.oob_score_:.4f}")
print(f"Feature Importances:\n{rf_classifier.feature_importances_}")
Related Concepts
- Decision Trees: Understand impurity criteria (Gini vs. entropy vs. MSE) and why deep unpruned trees exhibit high variance.
- Bagging vs. Boosting: Bagging trains trees independently in parallel to suppress variance; boosting (GBM, XGBoost, LightGBM) trains trees sequentially to reduce bias.
- Bias-Variance Tradeoff: Deeper trees reduce bias; more trees (
n_estimators) and smallermax_featuresreduce variance via lower correlation . - Hyperparameter Tuning: Tuning
n_estimators,max_depth,min_samples_leaf, andmax_featuresbalances generalization against memory/compute cost. - Feature Importance: Understand the limitations of impurity-based importance (biased toward continuous/high-cardinality features) compared to permutation importance or SHAP.