Random Forests — Bagging & Bias-Variance Tradeoff
Lesson opener
In one line: How random forests combine many trees to reduce variance.
Why it matters: Averaging many diverse trees reduces overfitting without losing too much flexibility.
Before this lesson: Decision trees / Applied ML statistics
Before you start
| Resource | Link |
|---|---|
| Previous | Scikit-learn implementation |
| Next | Support Vector Machines |
| Prerequisites | Decision trees, Applied ML statistics |
| Time | ~50 minutes |
What you will learn
- How random forests combine many trees to reduce variance
- What bagging (bootstrap aggregating) does step by step
- Bias-variance tradeoff from Applied ML statistics — applied to ensembles
- When a random forest beats a single tree for Indian churn models
Why one tree is not enough
A single decision tree is like asking one analyst for the answer — sharp opinions, sensitive to which customers appeared in training. A random forest trains hundreds of trees on different random samples and feature subsets, then votes on the final prediction.
WHY Averaging many diverse trees reduces overfitting without losing too much flexibility.
WHEN Tabular data (customer features, transaction history) where you want strong accuracy with modest tuning.
Indian workplace example: A Pune NBFC scores loan default risk. One deep tree memorises five noisy defaulters. A forest of 200 shallow trees smooths out noise and generalises across branches.
Bagging — bootstrap aggregating
Bagging builds each tree on a bootstrap sample — random draw of rows with replacement (same row can appear twice).
Full data (300 customers)
↓ bootstrap sample 1 → Tree 1
↓ bootstrap sample 2 → Tree 2
...
↓ bootstrap sample 200 → Tree 200
↓ majority vote (classification) or average (regression)
Final predictionWHY Each tree sees slightly different data — errors cancel when averaged.
WHEN Base model has high variance (overfits) — exactly the single-tree problem.
Random part: at each split, only a random subset of features is considered (e.g. √p features). Trees become decorrelated — they don't all split on support_tickets first.
Bias-variance — forest view
From Applied ML statistics:
| High bias | High variance | |
|---|---|---|
| Symptom | Underfit — too simple | Overfit — chases noise |
| Single shallow tree | ✓ | |
| Single deep tree | ✓ | |
| Random forest | Low–moderate | Reduced via averaging |
- Bias — error from being too simple (forest of shallow trees still flexible)
- Variance — error from sensitivity to training sample (bagging lowers this)
WHY Forests target the sweet spot: more accurate than one tree, less overfit than one deep tree.
WHEN Review train vs test gap — forest should narrow the gap vs unlimited depth tree.
sklearn — churn random forest
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
df = pd.read_csv("data/customers.csv")
X = pd.get_dummies(
df[["tenure_months", "monthly_spend", "support_tickets", "segment"]],
drop_first=True,
)
y = df["churned"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y
)
single = DecisionTreeClassifier(max_depth=None, random_state=42)
forest = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=42)
for name, model in [("Single tree", single), ("Random forest", forest)]:
model.fit(X_train, y_train)
print(f"{name}: train={accuracy_score(y_train, model.predict(X_train)):.3f}, "
f"test={accuracy_score(y_test, model.predict(X_test)):.3f}")Breaking it down:
n_estimators=100— number of trees in the forestmax_depth=5— cap each tree (still tune this)feature_importances_— which columns mattered most (post-fit)
importance = pd.Series(forest.feature_importances_, index=X.columns)
print(importance.sort_values(ascending=False).head())Use this when: logistic regression is too linear and one tree is too unstable.
Key hyperparameters
Hyperparameters are settings you choose (not learned from data) — e.g. max_depth. The split thresholds each tree learns are parameters. Full definition vs learned parameters: Cross-validation & GridSearch.
| Parameter | Typical start | Effect |
|---|---|---|
n_estimators | 100–300 | More trees → stabler, slower |
max_depth | 5–15 | Deeper trees → more variance per tree |
min_samples_leaf | 5–20 | Smoother leaves |
max_features | 'sqrt' | Decorrelates trees (default for classification) |
WHY Defaults are reasonable; tune max_depth and n_estimators first.
WHEN Kaggle-style accuracy chase — use GridSearchCV instead of guessing.
Forests vs other models
| Model | Strength | Weakness |
|---|---|---|
| Logistic regression | Fast, interpretable | Linear boundaries |
| Single tree | Rules on a slide | Overfits easily |
| Random forest | Strong on tabular data | Harder to explain than one tree |
| Deep learning | Images, text, huge data | Overkill for 300-row CSV (DL capstone) |
Essential commands
| Command / action | What it does |
|---|---|
RandomForestClassifier(n_estimators=100) | Bagged ensemble |
model.feature_importances_ | Relative feature contribution |
| Compare single tree vs forest test score | Validate ensemble gain |
random_state=42 | Reproducible forest |
Practice
Do this now: Train single tree (unlimited depth) and random forest (n_estimators=100, max_depth=5) on churn. Report train/test accuracy for both. List top 3 feature importances and one sentence linking results to bias-variance from stat4.
Checklist
- [ ] I can explain bagging as bootstrap samples + vote
- [ ] I connected forests to bias-variance from stat4
- [ ] Random forest beats or matches single tree on test accuracy
- [ ] I inspected
feature_importances_for business insight - [ ] Next: Support Vector Machines