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.
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 ().
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 and midpoint between sorted values, partition samples into left () and right () buckets.
2. Maximize Impurity Drop: Pick the 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 ().
Interactive Sandbox: Impurity Reduction & Tree Depth
Adjust Max Depth (1 to 4) or drag the Root Split Threshold () 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.
Mathematical Formulation: Gini Impurity & Gain
A node containing 50 percent Class 0 and 50 percent Class 1 hits maximum binary Gini impurity . A pure node hits . Minimizing weighted child Gini avoids computing logarithms, making it faster than Shannon Entropy while producing nearly identical splits.
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.
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.
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?
max_depth, min_samples_leaf, or cost-complexity pruning (ccp_alpha) to prevent memorization.Computational Complexity: Sorting & Depth Bounds
Evaluating all thresholds across features and sorted rows takes per level, yielding or with pre-sorted indices.
Inference is exceptionally fast: routing a query sample from root to leaf evaluates at most scalar comparisons in time.
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).
Production Code: Gini Split & Pruned Classifier
Compute Gini gain across candidate splits in NumPy and constrain tree overfitting in scikit-learn.
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}")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.
DecisionTreeClassifier before evaluating validation performance.