Decision trees
Learning by asking the most informative question first
Trees are the most human-readable model family and the building block of the ensembles that still win most tabular competitions (3.9 Ensembles: bagging, random forests and gradient boosting). Learning them teaches you impurity measures that reuse entropy (1.9 Information theory: entropy, cross-entropy and KL divergence), shows the bias–variance trade-off (3.5 Evaluating models: metrics, validation and the bias–variance trade-off) in its rawest form, and gives you a mental model for "routing" that returns in mixture-of-experts layers (7.11 Mixture of Experts) and agent workflows (10.5 Agentic workflow patterns).
You'll be able to
- Compute Gini impurity, entropy and information gain for a candidate split by hand
- Explain how CART grows a classification or regression tree greedily and why the result is piecewise constant
- Control overfitting with pre-pruning hyperparameters and cost-complexity pruning
- Diagnose the strengths (interpretability, no scaling) and weaknesses (instability, axis-aligned boundaries) of a single tree
Key ideas
- A tree partitions feature space into axis-aligned rectangles and predicts a constant per leaf: flexible, interpretable, scale-invariant.
- Splits are chosen greedily to maximize impurity decrease; Gini = 1 − Σp², entropy = −Σp log₂p, information gain = parent impurity − weighted child impurity.
- Regression trees minimize within-leaf squared error and predict the leaf mean.
Show 4 more key ideas
- A fully grown tree memorizes noise; control variance with max_depth/min_samples_leaf or cost-complexity pruning chosen by cross-validation.
- Trees handle missing values natively (surrogates or learned default direction) and need no feature scaling.
- Single trees are unstable (high variance) and draw staircase boundaries — the motivation for ensembles.
- Impurity-based feature importance is biased toward high-cardinality features; prefer permutation importance or SHAP.
Suggested path through this lesson
A model made of questions
A decision tree predicts by asking a sequence of yes/no questions about the features: is age < 30? is income > 50k? Each internal node tests one feature against a threshold, each branch is an answer, and each leaf holds a prediction (a class or a number). Geometrically a tree carves the feature space into axis-aligned rectangles, one per leaf, and predicts a constant inside each rectangle. That makes trees piecewise-constant models: flexible (enough rectangles approximate anything), interpretable (every prediction is a readable rule), and completely indifferent to feature scaling (a monotone transform of a feature changes no split).
Intuition. Playing "20 questions", you ask the question whose answer tells you the most. Tree learning formalizes "tells you the most" with impurity.
Measuring impurity
For a node containing samples with class proportions , three impurity measures are standard:
All three are zero for a pure node and maximal for a uniform node. Gini is the probability that two samples drawn from the node disagree in class; entropy is the expected surprise in bits (1.9 Information theory: entropy, cross-entropy and KL divergence). In practice Gini and entropy give almost identical trees; Gini avoids the logarithm and is scikit-learn's default.
A split sends the samples of a node into children with sizes . Its quality is the information gain (impurity decrease):
Worked example
A node holds 10 samples: 6 "yes" and 4 "no". Its entropy is
Split A sends 4 samples left (4 yes, 0 no) and 6 right (2 yes, 4 no). The left child is pure (); the right child has . The weighted child entropy is , so bits.
Split B sends 5 left (3 yes, 2 no) and 5 right (3 yes, 2 no). Both children have the parent's proportions, so each and : the question told us nothing.
With Gini instead: parent ; Split A children and , weighted , decrease . Same ranking.
Math check. Information gain is never negative, because entropy is concave and the weighted child entropy is an average of entropies of distributions whose mixture is the parent (Jensen's inequality). A useless split gives exactly zero.
Growing a tree: CART
The classic algorithm (CART; ID3 and C4.5 are relatives) is greedy, top-down recursive partitioning:
- For every feature, and for every candidate threshold (for a numeric feature: midpoints between consecutive sorted distinct values), compute the impurity decrease of the split.
- Take the best split, create two children, and recurse into each child.
- Stop when a node is pure, too small, or a depth limit is hit; the leaf predicts the majority class (classification) or the mean target (regression).
For regression trees the impurity is the within-node sum of squared errors, so a split is chosen to minimize
and the prediction inside each leaf is the leaf mean — exactly the constant that minimizes squared error. Evaluating all thresholds of one feature at a node costs after sorting, so one level costs roughly for features. Greedy means the tree never revisits a split: the globally optimal tree is NP-hard to find, and the greedy one is usually good enough once we ensemble.
Stopping and pruning
A tree grown until every leaf is pure has zero training error and memorizes noise: it is the archetypal high-variance, low-bias model (3.5 Evaluating models: metrics, validation and the bias–variance trade-off). Two remedies:
- Pre-pruning (early stopping):
max_depth,min_samples_leaf,min_samples_split,min_impurity_decrease,max_leaf_nodes. Cheap and effective; tune by cross-validation. - Post-pruning (cost-complexity pruning): grow a full tree , then minimize where is the training error and the number of leaves. Increasing collapses the weakest subtrees one by one; pick by cross-validation (
ccp_alphain scikit-learn).
Categorical features and missing values
Numeric features split on a threshold. Categorical features can be one-hot encoded (each dummy becomes a binary split), or handled natively: C4.5 makes a multi-way split, LightGBM searches optimal category groupings, CatBoost uses ordered target statistics (3.9 Ensembles: bagging, random forests and gradient boosting). Missing values are handled gracefully by trees in two ways: surrogate splits (CART finds a backup feature that mimics the chosen split) or a learned default direction (XGBoost/LightGBM send missing values to whichever child reduces loss more). Because trees only compare values to thresholds, they are invariant to monotone transforms: no standardization, no log-transforms needed.
Interpretability, instability and the shape of the boundary
Every path from root to leaf is a rule you can read aloud, which is why trees are popular in medicine and credit scoring. Scikit-learn's default feature importance (total impurity decrease attributed to a feature, "MDI") is biased toward high-cardinality and continuous features; permutation importance and SHAP values (3.13 Feature engineering, data quality and data-centric ML) are more trustworthy.
The price of flexibility is instability: changing a handful of training points can change the root split and therefore the whole tree — high variance in the bias–variance sense. And because splits are axis-aligned, a tree represents a diagonal boundary only as a staircase of many splits, whereas logistic regression (3.3 Logistic regression and softmax classification) or an SVM (3.10 Support vector machines and kernels) draws it with one line. Both weaknesses are exactly what bagging and boosting fix next.
Where this shows up later
- Averaging many trees kills their variance (random forests) and adding them sequentially fixes their bias (gradient boosting) — 3.9 Ensembles: bagging, random forests and gradient boosting.
- Permutation importance and SHAP for trees — 3.13 Feature engineering, data quality and data-centric ML; the end-to-end tabular project uses GBDTs built from these trees — 3.14 Project: end-to-end tabular ML with scikit-learn.
- Compare the staircase boundary with the smooth boundaries a neural network learns — 4.1 From perceptron to MLP; universal approximation; routing inputs to experts in MoE layers is a learned, soft "split" — 7.11 Mixture of Experts; routing patterns in agent systems are if/else at the LLM level — 10.5 Agentic workflow patterns.
Common pitfalls (4)
- Standardizing or log-transforming features before a tree: it changes nothing (monotone transforms preserve splits) and wastes effort.
- Reading feature_importances_ as causal or as 'the most useful features' — it is biased and ignores correlated substitutes.
- Growing an unpruned tree and reporting training accuracy (often 100%) as if it meant anything.
- One-hot encoding a 1,000-category feature for a tree: hundreds of near-useless binary splits; use native categorical handling or target encoding.
Recap: all 7 key points
- A tree partitions feature space into axis-aligned rectangles and predicts a constant per leaf: flexible, interpretable, scale-invariant.
- Splits are chosen greedily to maximize impurity decrease; Gini = 1 − Σp², entropy = −Σp log₂p, information gain = parent impurity − weighted child impurity.
- Regression trees minimize within-leaf squared error and predict the leaf mean.
- A fully grown tree memorizes noise; control variance with max_depth/min_samples_leaf or cost-complexity pruning chosen by cross-validation.
- Trees handle missing values natively (surrogates or learned default direction) and need no feature scaling.
- Single trees are unstable (high variance) and draw staircase boundaries — the motivation for ensembles.
- Impurity-based feature importance is biased toward high-cardinality features; prefer permutation importance or SHAP.
Watch
Gini-based splitting with a worked example; watch first.
Read
Exercises
- By hand: pick the best split
A node has 12 samples (7 positive, 5 negative). Candidate split X sends (5 pos, 0 neg) left and (2 pos, 5 neg) right; split Y sends (4 pos, 3 neg) left and (3 pos, 2 neg) right. Compute the information gain (bits) and the Gini decrease for both. Expected: X wins clearly under both criteria.
- Overfit, then prune
Train
DecisionTreeClassifieron the breast-cancer dataset with no limits; report train vs 5-fold CV accuracy. Then sweepmax_depthfrom 1 to 15 and plot both curves. Finally usecost_complexity_pruning_pathand chooseccp_alphaby CV. Expected: training accuracy 100% but CV peaks at a modest depth; pruning matches or beats the best depth. - Staircase vs line
Generate 2-D data separated by the diagonal line plus noise. Fit logistic regression and a depth-8 tree; plot both decision boundaries. Then rotate the data by 45° and refit. Expected: the tree needs many splits for the diagonal and becomes much simpler after rotation; logistic regression is unaffected.
Quiz
Flashcards
These cards are now in your spaced-repetition queue. Review all due cards →