Rana Maninder Singh
Lesson 2 of 7ML Advanced

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


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 prediction

WHY 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 biasHigh variance
SymptomUnderfit — too simpleOverfit — chases noise
Single shallow tree✓
Single deep tree✓
Random forestLow–moderateReduced via averaging

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:

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.

ParameterTypical startEffect
n_estimators100–300More trees → stabler, slower
max_depth5–15Deeper trees → more variance per tree
min_samples_leaf5–20Smoother 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

ModelStrengthWeakness
Logistic regressionFast, interpretableLinear boundaries
Single treeRules on a slideOverfits easily
Random forestStrong on tabular dataHarder to explain than one tree
Deep learningImages, text, huge dataOverkill for 300-row CSV (DL capstone)

Essential commands

Command / actionWhat it does
RandomForestClassifier(n_estimators=100)Bagged ensemble
model.feature_importances_Relative feature contribution
Compare single tree vs forest test scoreValidate ensemble gain
random_state=42Reproducible 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