Chapter 27 of 42 · ~24 min read & lab+65 XP
Chapter 27 · Machine Learning

Decision Trees (CART): Gini, Entropy, Variance Reduction & Pruning

Axis-aligned recursive partitioning, Gini vs. Entropy splits, why trees ignore monotonic scaling, why they cannot extrapolate, and Cost-Complexity Pruning.

What Is It?

Decision Trees recursively split data into purer subsets using simple if-else threshold questions chosen by Gini Impurity, Entropy, or Variance Reduction.

Why Is It Required?

Trees naturally model non-linear interactions, require zero feature scaling, are human-readable, and serve as the building block of Random Forests and XGBoost.

Everyday Analogy: A game of 20 Questions where every yes/no question splits the remaining possibilities as cleanly as possible.
Why ML Engineers & Data Scientists Actually Need This

Decision Trees are the atomic Lego brick of Random Forests, XGBoost, LightGBM, and CatBoost!

ML / AI Engineer

You rarely ship a single deep tree in production — you ensemble hundreds of them. Mastering how CART chooses splits, handles missing values, and prunes leaves is mandatory to debug XGBoost and LightGBM.

Data Scientist

Trees handle non-linear feature interactions automatically without scaling, making shallow trees (depth 3–4) gold-standard interpretable rules for finance, credit, and clinical policy.

Interview & Debug Edge

Classic interview trio: 'Gini vs. Entropy — when do they differ? Why can't trees extrapolate? And why doesn't StandardScaler change a tree's splits?'

Step 0 · Test Your Gut Before Any Math!

You train a Decision Tree Regressor on house prices ranging from $100k to $900k (1,000–4,000 sqft). At test time, a 10,000 sqft mansion arrives. What will the tree predict?

What You Will Master in This Chapter
  • Compute Gini Impurity, Entropy, and MSE Variance Reduction for candidate CART splits
  • Explain why Decision Trees are invariant to monotonic feature scaling (StandardScaler not needed)
  • Diagnose why single trees are high-variance learners and why they cannot extrapolate beyond training target bounds
  • Control overfitting with max_depth, min_samples_leaf, and Cost-Complexity Pruning (ccp_alpha)
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 3
G(t)Say aloud:“Gini Impurity”
Plain-English Meaning
Probability of misclassifying a random draw from node t
Everyday Example
1 − Σ p_k² (max 0.50 for binary)
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

A Decision Tree plays a game of 20 Questions with your data. At every node, it greedily asks the single yes/no question (feature ≤ threshold) that makes the two child buckets as pure (all one class, or lowest target variance) as possible!

1. Recursive Axis-Aligned Splitting & Scale Invariance

Everyday Story First (Zero Math Yet!)

Because a tree only asks rank-order questions (Income ≤ $80,000), applying any strictly increasing transform (log(Income), StandardScaler, Income × 100) keeps the exact same sorted order of rows — producing the exact same tree!

CART Tree Rules ↔ Axis-Aligned Rectangles in Feature Spacex₁ ≤ 4.0 ?Leaf: Class Ax₂ ≤ 2.5 ?Class BClass ARegion 1 (A)Region 2 (A)Region 3 (B)
CART Decision Trees partition feature space into axis-aligned rectangles — invariant to monotonic scaling, but requiring staircase splits for diagonal boundaries.

Classification vs. Regression Split Criteria

  • Classification (Gini Impurity): G=1−∑k=1Kpk2G = 1 - \sum_{k=1}^K p_k^2. Fast (no logarithms) — default in scikit-learn.
  • Classification (Entropy / Information Gain): H=−∑k=1Kpklog⁡2pkH = -\sum_{k=1}^K p_k \log_2 p_k.
  • Regression (Variance Reduction): Pick the split minimizing weighted child MSE: nLnVar(yL)+nRnVar(yR)\frac{n_L}{n}\text{Var}(y_L) + \frac{n_R}{n}\text{Var}(y_R).
Interactive Mini-Lab • CART Split Finder

Slide Split Threshold x ≤ 3.5 to Maximize Gini Gain

Weighted Gini: 0.200 (Gain: +0.300)
x=1
y=0
x=2
y=0
x=3
y=0
x=4
y=1
x=5
y=0
x=6
y=1
x=7
y=1
x=8
y=1
Left (3 rows): Gini = 0.000Right (5 rows): Gini = 0.320

2. Gini vs. Entropy & Why Greedy Splits Are Local

Everyday Story First (Zero Math Yet!)

Interviewers love asking whether Gini or Entropy is better. Plot both curves side-by-side (with Entropy scaled by ½) and you'll see they are almost twins — agreeing on ~98% of splits!

Impurity Curves vs. Class Probability p: Gini vs. Scaled Entropyp = 0.5 (Max Impurity)0.0 (Pure)1.0 (Pure)-- Gini: 1 − Σ p_k²Fast (no log!), sklearn default— Entropy: −Σ p_k log₂(p_k)Slightly more balanced treesBoth agree on ~98% of splits!
Gini Impurity (2p(1−p)) and scaled Entropy (−p log₂ p − (1−p) log₂(1−p)) share the exact same bell shape — both peak at p = 0.50 and hit 0 at pure leaves.

Practical Differences

  • Gini is slightly faster to compute and tends to isolate the most frequent class in its own branch.
  • Entropy tends to produce slightly more balanced trees.
  • Greedy limitation: Finding the globally optimal tree is NP-Complete, so CART uses greedy top-down splitting — meaning small perturbations in training rows can flip the root split and yield a totally different tree (High Variance!).

3. Pre-Pruning vs. Cost-Complexity Post-Pruning

Everyday Story First (Zero Math Yet!)

Left unconstrained, a CART tree keeps splitting until every leaf has 1 row (100% training accuracy, terrible test accuracy!). You stop memorization either before growing (pre-pruning) or by trimming back weak branches after growing (ccp_alpha).

Pruning & Tree Depth: Controlling Variance Before a Tree Memorizes NoiseOptimal Depth (Sweet Spot)Key Pruning Controls:• max_depth (e.g. 4–8)• min_samples_leaf (e.g. 10)• ccp_alpha (Cost-Complexity)Cost: R(T) + α · |Leaves|
Unpruned trees grow until every leaf has 1 row (0% train error, huge variance). Pre-pruning (max_depth, min_samples_leaf) and Cost-Complexity Pruning (ccp_alpha) find the sweet spot.

Weakest-Link Cost-Complexity Pruning

Rα(T)=R(T)+α⋅∣Leaves(T)∣R_\alpha(T) = R(T) + \alpha \cdot |\text{Leaves}(T)| As α\alpha increases, subtrees that don't reduce impurity enough to justify their leaf count are pruned away — pick α\alpha via cross-validation!

“Wait, I'm Confused...” · Teacher Office Hours Q&A

The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.

Because every CART split is perpendicular to a single axis (x₁ ≤ t or x₂ ≤ t), it has to approximate a clean 45° diagonal line using dozens of tiny jagged staircase steps!

Interactive Visual Lab
Lab Challenge: In the CART Depth Builder below, tune max_depth and min_samples_leaf until Validation Error drops into the green Sweet Spot (< 14%)!
Flagship Deep Lab • CART Pruning & Generalization

Tune max_depth & min_samples_leaf to Find the Generalization Sweet Spot

Sweet Spot!
Effective Leaves
5
Train Error
12.9%
Validation Error
10.2%
Intuition Takeaway: CART greedily partitions space with axis-aligned splits (invariant to scaling, unable to extrapolate) — prune via max_depth / ccp_alpha, or tame its high variance with Ensembles in Chapters 14 & 15!
Where This Powers Real ML, Deep Learning & Generative AI

Credit Policy & Rule Extraction

Shallow depth-3 trees give regulators auditable if/else approval logic.

Base Learners for Ensembles

Deep unpruned trees power Random Forests; shallow depth-4–6 trees power XGBoost/LightGBM.

Production NumPy & PyTorch Code Patterns
from sklearn.tree import DecisionTreeClassifier

# Pre-pruned + Cost-Complexity pruned CART tree
tree = DecisionTreeClassifier(
    criterion="gini",
    max_depth=5,
    min_samples_leaf=10,
    ccp_alpha=0.005,
    random_state=42,
)
tree.fit(X_train, y_train)
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Using a Decision Tree / XGBoost directly on raw trending time-series targets (e.g., growing revenue).
Best Practice: Trees cannot extrapolate beyond historical max(y)! Predict differences/ratios (Δy_t) or detrend with a linear model first.
Trap #2: StandardScaling features expecting a Decision Tree's accuracy to improve.
Best Practice: Monotonic transforms preserve feature rank order, leaving CART splits 100% unchanged.
Trap #3: Shipping an unpruned tree (max_depth=None).
Best Practice: Unpruned trees memorize noise with 1-sample leaves; always prune or ensemble!
Chapter Mastery Check (+65 XP)
Score: 0 / 5
1What is the Gini Impurity of a 50/50 binary node?
2What happens when a Decision Tree Regressor sees an input far above its training range?
3Which hyperparameter controls post-pruning in scikit-learn's DecisionTreeClassifier?
4Why is a single deep Decision Tree considered a High-Variance model?
5What split criterion does a CART Regression Tree minimize?

Apply What You Learned — Solve Matching Coding Problems