Curriculum02. Supervised LearningLesson 4 of 7

Decision Trees

Recursive axis-aligned partitioning and Gini impurity reduction.

22 min readIntermediateModule 02
01 // CORE INTUITION

Core Intuition: Optimal 20 Questions

Playing 20 Questions rewards asking broad splitting questions first ("Does it breathe?") before narrow ones ("Does it have stripes?").

A decision tree automates this game numerically. At every step, it scans all features and candidate cutoffs, picking the single yes/no split that purifies the resulting subgroups as cleanly as possible.

Takeaway:Decision trees build a hierarchy of greedy yes/no feature splits that isolate pure class regions.
02 // THE PROBLEM IT SOLVES

The Problem It Solves: Non-Linear Rules Without Scaling

Linear and logistic models draw a single flat hyperplane across feature space. When decision boundaries wrap around pockets, combine non-linear thresholds, or mix wildly different unit scales, linear models underfit.

Decision trees capture non-linear interactions naturally and ignore monotonic feature scaling because splits depend strictly on sorted rank order (xj≤θx_j \le \theta).

Takeaway:Use decision trees to model non-linear threshold interactions without needing feature standardization.
03 // STEP-BY-STEP MECHANISM

Step-by-Step Mechanism: Greedy Recursive Partitioning

CART (Classification and Regression Trees) grows a binary tree top-down:

1. Scan Candidate Splits: For every feature jj and midpoint θ\theta between sorted values, partition samples into left (xj≤θx_j \le \theta) and right (xj>θx_j > \theta) buckets.

2. Maximize Impurity Drop: Pick the (j∗,θ∗)(j^*, \theta^*) pair yielding the lowest weighted child impurity.

3. Recurse Until Stopping: Repeat on each child until reaching max_depth, min_samples_leaf, or a pure leaf (Gini=0\text{Gini} = 0).

Takeaway:Each internal node greedily chooses the axis-aligned threshold minimizing weighted child impurity.
04 // INTERACTIVE SANDBOX

Interactive Sandbox: Impurity Reduction & Tree Depth

Adjust Max Depth (1 to 4) or drag the Root Split Threshold (x1x_1) in the visualizer.

Watch how increasing depth subdivides the 2D coordinate plane into finer rectangular leaves, driving training Gini impurity down toward 0.000 while risking isolated noisy pockets.

CART Axis-Aligned Partitioning Engine
LEAVES: 3WEIGHTED GINI: 0.000TRAIN ACC: 100%
MAX TREE DEPTH2
Feature x₁Feature x₂
Class 0
Class 1
Root split
Child splits
Takeaway:Deeper trees carve smaller rectangular cells, lowering training impurity while increasing sensitivity to individual outliers.
05 // MATHEMATICAL FORMULATION

Mathematical Formulation: Gini Impurity & Gain

A node containing 50 percent Class 0 and 50 percent Class 1 hits maximum binary Gini impurity 1−(0.52+0.52)=0.51 - (0.5^2 + 0.5^2) = 0.5. A pure node hits 1−12=01 - 1^2 = 0. Minimizing weighted child Gini avoids computing logarithms, making it faster than Shannon Entropy while producing nearly identical splits.

PRIMARY OBJECTIVE FORMULATION
Variable & Symbol Definitions
IG(S)I_G(S)Gini impurity of node SS, equal to 00 when all samples share one class
pkp_kFraction of samples in node SS belonging to class kk
SL,SRS_L, S_RLeft and right child subsets created by threshold xj≤θx_j \le \theta
ΔIG\Delta I_GWeighted impurity reduction maximized by CART split selection
Takeaway:CART picks splits maximizing ΔIG\Delta I_G, driving child class distributions toward pure 0.00.0 Gini leaves.
06 // KEY ASSUMPTIONS

Key Assumptions: Axis-Aligned Geometry & Local Greed

Decision trees are non-parametric, assuming no Gaussian noise or linear trend, yet impose three structural biases:

1. Orthogonal Cuts: Splits test one feature at a time, so diagonal boundaries require a staircase of many steps.

2. Greedy Myopia: Top splits never backtrack; a suboptimal root split cannot be undone deeper down.

3. Constant Extrapolation: Outside training bounds, regression trees predict flat leaf averages and cannot extrapolate trends.

Takeaway:Trees excel at rectangular rules but approximate diagonal boundaries poorly and cannot extrapolate beyond training ranges.
07 // COMMON PITFALLS

Common Pitfalls: Unpruned Overfitting & Instability

Left unconstrained (max_depth=None), a decision tree splits until every leaf holds a single sample, memorizing training noise with 100 percent training accuracy and poor validation error.

Trees also exhibit high variance: removing just a few training samples near the root can flip the top split feature and reshape the entire tree below it.

Algorithmic Checkpoint

A parent node holds 40 Class A and 40 Class B samples. A candidate split sends 20 Class A and 20 Class B to the left child, and 20 Class A and 20 Class B to the right child. What is the Gini gain?

Takeaway:Constrain tree growth with max_depth, min_samples_leaf, or cost-complexity pruning (ccp_alpha) to prevent memorization.
08 // COMPLEXITY

Computational Complexity: Sorting & Depth Bounds

Evaluating all thresholds across dd features and mm sorted rows takes O(m⋅dlog⁡m)O(m \cdot d \log m) per level, yielding O(m⋅d⋅log⁡m⋅depth)O(m \cdot d \cdot \log m \cdot \text{depth}) or O(m⋅d⋅depth)O(m \cdot d \cdot \text{depth}) with pre-sorted indices.

Inference is exceptionally fast: routing a query sample from root to leaf evaluates at most DD scalar comparisons in O(depth)O(\text{depth}) time.

Takeaway:Decision trees train in O(m⋅d⋅depth)O(m \cdot d \cdot \text{depth}) with pre-sorted features and predict in O(depth)O(\text{depth}) time.
09 // REAL-WORLD USE

Real-World Use: Auditability & Ensemble Building Blocks

Shallow decision trees (max_depth 3 to 5) are deployed directly in clinical decision checklists and loan underwriting policies because every path converts straight into human-readable if-else rules.

In high-accuracy tabular pipelines, single trees serve as the fundamental building blocks inside Random Forests and Gradient Boosted Trees (XGBoost, LightGBM).

Takeaway:Shallow trees provide transparent rulebooks; ensembles of trees dominate structured tabular benchmarks.
10 // PRODUCTION CODE

Production Code: Gini Split & Pruned Classifier

Compute Gini gain across candidate splits in NumPy and constrain tree overfitting in scikit-learn.

Production Implementation
import numpy as np

def gini(labels: np.ndarray) -> float:
    if len(labels) == 0:
        return 0.0
    _, counts = np.unique(labels, return_counts=True)
    probs = counts / len(labels)
    return float(1.0 - np.sum(probs ** 2))

x = np.array([1.0, 2.0, 3.0, 6.0, 7.0, 8.0])
y = np.array([0, 0, 0, 1, 1, 1])

parent_gini = gini(y)
best_thresh, best_gain = None, -1.0
for t in (x[:-1] + x[1:]) / 2.0:
    left, right = y[x <= t], y[x > t]
    gain = parent_gini - (len(left) / len(y)) * gini(left) - (len(right) / len(y)) * gini(right)
    if gain > best_gain:
        best_gain, best_thresh = gain, float(t)

print(f"Best split: x <= {best_thresh:.2f}, Gini gain = {best_gain:.3f}")
Implementation Walkthrough:

The NumPy loop evaluates every midpoint between consecutive sorted values and selects the threshold maximizing weighted Gini reduction. In scikit-learn, setting max_depth=3, min_samples_leaf=2, and ccp_alpha=0.01 prevents tiny terminal leaves from memorizing noise, while export_text prints the exact learned decision rules.

Takeaway:Always constrain leaf size and depth in DecisionTreeClassifier before evaluating validation performance.