Deriving Decision Trees (ML #6)
A churn model you shipped last quarter reports 100% training accuracy and 77.6% test accuracy on live traffic. Nothing in the training curves looks wrong — a perfectly clean tree, no warnings. Someone asks what it actually learned, and the answer is a chain of thresholds, one of which is account_id <= 1493. That number is not a finding. It is a memorised row ID, and the model will cheerfully tell you a brand-new customer with ID 4001 can never churn, because 4001 sits on the wrong side of a line that means nothing.
None of that is a bug in the library. It is the greedy splitting rule doing exactly what you asked of it.
A decision tree is the only model in this course whose entire hypothesis is a chain of if statements, yet nobody derives where the if comes from. That derivation is short, and it settles most practical questions: why entropy and Gini agree far more often than the algebra suggests, why greedy splitting is a bet rather than a theorem, and why trees need no feature scaling while k-NN dies without it.
This chapter derives impurity from expected surprise, derives the reduction-in-impurity rule, works a split out by hand, shows a dataset where greedy splitting is strictly worse than an alternative, and builds CART from scratch for regression.
Why an impurity function exists at all
Take a node holding \(n\) points. A candidate split \(S\) sends \(n_L\) left and \(n_R\) right, \(n_L + n_R = n\). After the split each child predicts a constant, so the error the children can ever make depends only on how mixed each one is — that is impurity, and we need a number \(\text{imp}(\cdot)\) that rises as the label distribution flattens and hits 0 on a pure node.
Children of different sizes are not comparable on impurity alone: 900 mixed points and 4 mixed points should not count equally. A child’s contribution must be its share of the parent’s data times its impurity:
\[ \text{imp}_{\text{split}}(S) = \frac{n_L}{n}\,\text{imp}(L) + \frac{n_R}{n}\,\text{imp}(R) \]
Now the split rule is forced. Any measure of “how much did splitting reduce our uncertainty about the label” that is additive over children must be parent impurity minus weighted child impurity:
\[ \text{IG}(S) = \text{imp}(P) - \frac{n_L}{n}\,\text{imp}(L) - \frac{n_R}{n}\,\text{imp}(R) \]
IG is the information gain. It is non-negative by an averaging argument — a weighted average of values in \([0, \text{imp}_{\max}]\) cannot exceed \(\text{imp}_{\max}\) — it is exactly 0 when the split separates nothing, and choosing \(\arg\max_S \text{IG}(S)\) makes impurity fall monotonically as you descend. That is the entire justification for greediness: not “greedy is good practice”, but “impurity can only go down, so every leaf is at least as pure as the root.”
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=4pt, minimum width=2.2cm, minimum height=0.72cm, align=center, font=\rmfamily\small},
a/.style={->, thick}]
\node[b, fill=orange!16] (p) at (0,2.6) {parent: 8 pts, 3 zeros / 5 ones\\$H = 0.9544$ bits};
\node[b, fill=blue!10] (l) at (-2.6,0.7) {left: 6 pts\\$H = 1.0000$};
\node[b, fill=blue!10] (r) at (2.6,0.7) {right: 2 pts\\$H = 0.0000$};
\node[b] (w) at (0,-0.6) {weighted child impurity\\$\tfrac{6}{8}(1.0000) + \tfrac{2}{8}(0) = 0.7500$};
\node[b, fill=green!12] (g) at (0,-2.3) {gain $= 0.9544 - 0.7500 = 0.2044$ bits};
\draw[a] (p.south) -- (l.north); \draw[a] (p.south) -- (r.north);
\draw[a] (l.south) -- (w.north); \draw[a] (r.south) -- (w.north);
\draw[a] (w.south) -- (g.north);
\node[font=\rmfamily\scriptsize, text=black!60, align=left] at (4.7,1.4) {a split is scored by how much\\ impurity it removes, never by\\ how many points it moves};
\end{tikzpicture}
Entropy: impurity as expected surprise
What should \(\text{imp}\) measure? Make it the expected surprise of drawing one label at random from the node. Class \(c\) has proportion \(p_c\), so drawing it costs \(\log(1/p_c)\) and the expected cost is \(\sum_c p_c\log(1/p_c)\). Flipping the sign so “uncertain” reads as “large” gives Shannon entropy:
\[ H(p_1, \dots, p_K) = -\sum_{c=1}^{K} p_c \log_2 p_c \]
Three properties fall out of the derivation rather than being asserted. \(H = 0\) iff some \(p_c = 1\), so pure nodes are free — and \(\log_2 0 = -\infty\), which is why code must skip zero terms. \(H = \log_2 K\) at the uniform distribution, and the ceiling moves with \(K\): a 2-class node caps at 1.0000 bits, a 3-class node at 1.5850, a 10-class node at 3.3219. That is why impurity cannot be a plain error rate. And the log base is only the unit: \(\log_2\) gives bits, \(\log_e\) nats, \(\log_{10}\) digits, and the base changes the number you report but never the ranking of splits.
import numpy as np
def entropy(y): # y: 1-D array of labels
if len(y) == 0: return 0.0
_, c = np.unique(y, return_counts=True)
p = c / len(y); p = p[p > 0] # skip p = 0: log2(0) is -inf
return float(-(p * np.log2(p)).sum())
def gini(y):
if len(y) == 0: return 0.0
_, c = np.unique(y, return_counts=True)
return float(1 - ((c / len(y)) ** 2).sum())
for k in (2, 3, 10): # uniform K-class node
print(k, round(entropy(np.zeros(k, int)), 4), round(gini(np.zeros(k, int)), 4))
# 2 1.0 0.5
# 3 1.585 0.6667
# 10 3.3219 0.9
The second number is Gini impurity, and it deserves its own derivation instead of being handed to you as an alternative.
Gini, and the relationship that is not what textbooks say
For one draw, \(p_c^2\) is the probability of drawing class \(c\) twice with replacement. So \(1 - \sum_c p_c^2\) is exactly the probability that two independent draws from this node disagree:
\[ G(p_1, \dots, p_K) = P(y^{(1)} \neq y^{(2)}) = 1 - \sum_{c=1}^{K} p_c^2 \]
Same goal as entropy — 0 when pure, maximal when uniform — different lens: \(G\) counts disagreements, \(H\) averages log-probabilities.
The claim you meet everywhere is “\(G\) approximates \(H\) linearly, roughly \(G \approx \frac{2}{\ln 2}H\)”. That is false. \(\frac{2}{\ln 2} = 2.8854\), so at a balanced binary node it predicts \(G = 2.8854\) where the truth is \(0.5\) — off by a factor of 5.77. The real relationship is cleaner, and here it is measured:
| \(p\) | \(H\) (bits) | \(G\) | \(G/H\) |
|---|---|---|---|
| 0.500 | 1.0000 | 0.5000 | 0.5000 |
| 0.400 | 0.9710 | 0.4800 | 0.4944 |
| 0.300 | 0.8813 | 0.4200 | 0.4766 |
| 0.200 | 0.7219 | 0.3200 | 0.4433 |
| 0.100 | 0.4690 | 0.1800 | 0.3838 |
| 0.050 | 0.2864 | 0.0950 | 0.3317 |
| 0.010 | 0.0808 | 0.0198 | 0.2451 |
| 0.001 | 0.0114 | 0.0020 | 0.1751 |
Two separate facts. \(G \le H/2\) always, with equality only at balance: over a grid of 200,001 values of \(p \in (0, 0.5]\), H([p,1-p]) - 2*gini([p,1-p]) was never negative and hit 0 only at \(p = 0.5\). That is structural — both measures have zero first derivative at \(p = \tfrac12\) (\(H' = \log_2\frac{1-p}{p}\), \(G' = 2(1-2p)\)), so both are quadratic there, and with \(H(\tfrac12) = 1\), \(G(\tfrac12) = 0.5\) the ratio converges to exactly \(\tfrac12\); their curvatures differ (\(H'' = -5.7708\) against \(G'' = -4\)), so it dips below as you move away. Near purity the asymptotics are different functions entirely: \(G = 2p(1-p) \approx 2p\) while \(H \approx p\log_2(1/p) + \frac{p}{\ln 2}\), so at \(p = 0.001\) entropy charges \(1.141\times10^{-2}\) against Gini’s \(1.998\times10^{-3}\) — nearly six times as much for the same node. Gini is the milder penalty near purity, and that is the whole behavioural difference.
Do they actually pick different splits?
Enumerating every candidate threshold on every feature and comparing the two argmaxes over 100 random problems per regime:
| regime | same feature chosen | same feature and threshold |
|---|---|---|
| strong 2-class, \(d{=}4\), \(n \in [40,100]\) | 97% | 71% |
| XOR, \(d{=}2\), \(n{=}200\) | 92% | 80% |
| imbalanced, ~12% positives, \(d{=}2\) | 98% | 60% |
| near-chance labels, \(d{=}3\) | 87% | 79% |
| 3-class, \(d{=}4\) | 89% | 66% |
The first column is the headline: in 87–98% of problems the two criteria disagree about where to cut, not what to cut on, because the feature ranking is nearly identical. The second column, 60–80%, is the honest number for exact thresholds, and it lines up with the algebra above — thresholds differ most in the near-pure regime, exactly where \(G/H\) drops to 0.18–0.33. So Gini is a speed choice, not a modelling choice: it evaluates no logarithm, and on a 3,000-row, 2-feature classification problem an unpruned fit takes 6.4 ms with criterion="gini" against 8.2 ms with criterion="entropy". That is why CART defaults to Gini. Entropy stays the theoretically motivated choice and the one ID3 used, and on imbalanced data the two criteria can pick different features too — change it as a logged hyperparameter, not a silent default.
Information gain, worked by hand
Four points, two classes, two features — small enough to do completely. The parent has 3 + and 1 − at \((x_1, x_2) = (1,1), (2,2), (3,1), (4,3)\), so \(p = (0.75, 0.25)\) and
\[ H(P) = -\tfrac34\log_2\tfrac34 - \tfrac14\log_2\tfrac14 = 0.8113 \text{ bits}, \qquad G(P) = 1 - \tfrac{9}{16} - \tfrac{1}{16} = 0.375 \]
\(H(2/3, 1/3) = 0.9183\) is the only awkward constant and it appears twice:
| split | \(n_L\) | \(n_R\) | \(H(L)\) | \(H(R)\) | weighted child \(H\) | IG (bits) | Gini gain |
|---|---|---|---|---|---|---|---|
| \(x_1 \le 2\) | 2 | 2 | 0.0000 | 1.0000 | 0.5000 | 0.3113 | 0.1250 |
| \(x_1 \le 3\) | 3 | 1 | 0.9183 | 0.0000 | 0.6887 | 0.1226 | 0.0417 |
| \(x_2 \le 1\) | 2 | 2 | 1.0000 | 0.0000 | 0.5000 | 0.3113 | 0.1250 |
| \(x_2 \le 2\) | 3 | 1 | 0.9183 | 0.0000 | 0.6887 | 0.1226 | 0.0417 |
Notice what happened: Gini cannot tell the two winners apart. \(x_1 \le 2\) and \(x_2 \le 1\) produce identical child class distributions, so they score identically under any impurity depending only on the class distribution — which is both of them. Whatever tie-break you use picks arbitrarily, and the two choices give different trees. Entropy breaks the tie only because it is not the sole function of a distribution that measures uncertainty; it happens to be the one whose ranking is monotone in surprise.
def info_gain(X, y, j, t, imp): # reduction in impurity from splitting j at t
m = X[:, j] <= t
return imp(y) - m.mean() * imp(y[m]) - (~m).mean() * imp(y[~m])
X = np.array([[1, 1], [2, 2], [3, 1], [4, 3]], float)
y = np.array([1, 1, 0, 1])
for j, t in [(0, 2), (0, 3), (1, 1), (1, 2)]:
print(f"x{j+1}<={t} entropy {info_gain(X, y, j, t, entropy):.4f} gini {info_gain(X, y, j, t, gini):.4f}")
# x1<=2 entropy 0.3113 gini 0.1250
# x1<=3 entropy 0.1226 gini 0.0417
# x2<=1 entropy 0.3113 gini 0.1250
# x2<=2 entropy 0.1226 gini 0.0417
Greedy splitting is a bet, not a theorem
Entropy breaking a tie is the least interesting failure of greediness. The serious one: maximising gain at the root can force a strictly worse tree, because the first split commits you to a partition and the best partition is not the one with the highest root gain. Eight points, and no ties anywhere in the table below.
P = np.array([(0,4),(3,3),(3,4),(3,5),(4,0),(5,1),(5,4),(5,5)], float)
z = np.array([1,0,1,1,0,1,0,1])
def leaf_err(y): # training 0-1 error of the best constant predictor
_, c = np.unique(y, return_counts=True); return len(y) - c.max()
def tree_err(X, y, depth): # best training error with at most `depth` levels
err = leaf_err(y)
if depth == 0: return err
for j in range(X.shape[1]):
for t in np.unique(X[:, j])[:-1]:
m = X[:, j] <= t
err = min(err, tree_err(X[m], y[m], depth-1) + tree_err(X[~m], y[~m], depth-1))
return err
cands = []
for j in range(2):
for t in np.unique(P[:, j])[:-1]:
m = P[:, j] <= t
cands.append((entropy(z) - m.mean()*entropy(z[m]) - (~m).mean()*entropy(z[~m]),
j, float(t), tree_err(P[m], z[m], 1) + tree_err(P[~m], z[~m], 1)))
cands.sort(key=lambda r: -r[0])
for ig, j, t, e in cands:
print(f"x{j+1} <= {t:g}: IG {ig:.4f} bits, best <=2-level train errors {e}")
print(f"greedy takes x{cands[0][1]+1}<={cands[0][2]:g} -> {cands[0][3]} errors; "
f"best possible 2-level tree -> {min(e for *_, e in cands)} errors")
Greedy takes \(x_2 \le 4\) — the unique maximum, no tie to complain about — and ends with 2 training errors. Cutting at \(x_2 \le 3\) instead, only 0.0456 bits “worse” by the criterion, yields a tree with 1. Greedy gave up 0.046 bits and bought itself one extra misclassification.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=4pt, minimum width=2.2cm, minimum height=0.72cm, align=center, font=\rmfamily\small},
a/.style={->, thick}]
\begin{scope}[x=0.5cm, y=0.45cm]
\fill[blue!10] (-0.6,-0.4) rectangle (3.2,3.0); \fill[green!12] (-0.6,2.4) rectangle (3.2,3.0);
\foreach \x/\y/\l in {0/4/1, 3/3/0, 3/4/1, 3/5/1, 4/0/0, 5/1/1, 5/4/0, 5/5/1}
\ifnum\l=1 \fill[blue!80!black] (\x,\y) circle (2.6pt);
\else \draw[orange!85!black, thick, fill=white] (\x,\y) circle (2.6pt); \fi
\draw[orange!85!black, very thick] (-0.6,2.4) -- (3.2,2.4);
\node[font=\rmfamily\scriptsize, text=orange!75!black] at (1.3,-0.8) {greedy: $x_2 \le 4$, IG $0.2044$};
\node[font=\rmfamily\scriptsize] at (1.3,3.4) {2 training errors};
\end{scope}
\begin{scope}[shift={(4.4,0)}, x=0.5cm, y=0.45cm]
\fill[blue!10] (-0.6,-0.4) rectangle (3.2,1.8); \fill[green!12] (-0.6,1.8) rectangle (3.2,3.0);
\foreach \x/\y/\l in {0/4/1, 3/3/0, 3/4/1, 3/5/1, 4/0/0, 5/1/1, 5/4/0, 5/5/1}
\ifnum\l=1 \fill[blue!80!black] (\x,\y) circle (2.6pt);
\else \draw[orange!85!black, thick, fill=white] (\x,\y) circle (2.6pt); \fi
\draw[green!45!black, very thick] (-0.6,1.8) -- (3.2,1.8);
\node[font=\rmfamily\scriptsize, text=green!40!black] at (1.3,-0.8) {better: $x_2 \le 3$, IG $0.1589$};
\node[font=\rmfamily\scriptsize] at (1.3,3.4) {1 training error};
\end{scope}
\node[font=\rmfamily\scriptsize, text=black!60, align=center] at (2.0,-1.9) {filled $=$ class 1 \quad open $=$ class 0};
\end{tikzpicture}
The mechanism is visible in the picture. Greedy’s \(x_2 \le 4\) isolates two clean points and leaves a 6-point child that is exactly balanced — \(H = 1.0\), the maximum possible for a binary node. Impurity at the root is a one-node statistic, and it happily buys a good parent number with a bad child. The \(x_2 \le 3\) cut scores a worse root but hands both children an axis-aligned separation, so the second level is free.
Why does CART accept this? Because the globally optimal tree is combinatorial: 8 points already admit \(\frac{2^8-2}{2} = 127\) distinct two-way root partitions before you recurse, and \(n\) grows to thousands. Greedy makes \(O(\log n)\) decisions; exact search is exponential and nobody deploys it. Greedy is not an approximation bug — it is the price of one irreversible decision per node.
Thresholds, stopping, and overfitting
Continuous features have no finite candidate set, so CART does not enumerate thresholds. It sorts the column once and tests only midpoints between adjacent values — \(n-1\) candidates, with provably no loss: any threshold inside the gap \((x^{(i)}, x^{(i+1)})\) induces the same partition as the midpoint, so the \(n-1\) midpoints represent all distinct partitions.
Regression swaps the impurity function and nothing else changes. With squared error the optimal constant for a node is \(\bar y\), so impurity is \(\sum_i (y_i - \bar y)^2\) and maximising IG means minimising weighted child variance — the same formula with variance in place of entropy:
\[ \text{IG}(S) = \text{Var}(P) - \frac{n_L}{n}\text{Var}(L) - \frac{n_R}{n}\text{Var}(R) \]
class CART: # regression: squared-error impurity == variance
def fit(self, X, y, max_depth=3):
self.root_ = self._build(X, y, 0, max_depth); return self
def _build(self, X, y, d, md):
node = {"pred": float(y.mean())} # leaf value = mean of y in node
if d >= md or y.var() == 0: return node
best = (np.inf, None)
for j in range(X.shape[1]):
v = np.unique(X[:, j])
for t in (v[:-1] + v[1:]) / 2: # midpoints between adjacent values
m = X[:, j] <= t
imp = m.mean()*y[m].var() + (~m).mean()*y[~m].var()
if imp < best[0]: best = (imp, (j, float(t), m))
if best[1] is None: return node
j, t, m = best[1]; node.update(j=j, t=t)
node["L"] = self._build(X[m], y[m], d+1, md); node["R"] = self._build(X[~m], y[~m], d+1, md)
return node
def predict(self, X):
out = np.empty(len(X))
for i, x in enumerate(X): # axis-aligned walk down the tree
nd = self.root_
while "j" in nd: nd = nd["L"] if x[nd["j"]] <= nd["t"] else nd["R"]
out[i] = nd["pred"]
return out
X = np.arange(8, dtype=float)[:, None]
y = np.array([1., 1., 1., 1., 10., 10., 10., 10.])
tree = CART().fit(X, y, max_depth=1)
print(tree.predict(X).ravel(), tree.root_["t"]) # [ 1. 1. 1. 1. 10. 10. 10. 10.] 3.5
print(tree.root_["L"]["pred"], tree.root_["R"]["pred"], round(float(y.var()), 2)) # 1.0 10.0 20.25
Parent variance 20.25 collapses to a weighted child variance of exactly 0.0 — MSE 0 on all eight points from one split.
Stopping criteria are one idea: refuse a split that isn’t worth its variance. min_samples_leaf sets a floor on leaf size, max_depth caps commitment, a pure node (y.var() == 0 above, H == 0 for classification) needs no further test, min_impurity_decrease rejects near-zero gains. Scoring costs \(O(dn)\) per node after a one-off \(O(dn\log n)\) sort, so a depth-\(T\) tree fits in \(O(n d \log n)\). Measured, 4 features, depth 1: 1,000 rows in 0.7 ms, 10,000 in 4.7, 100,000 in 81.8, 400,000 in 397.1 — the cost per \((n\log_2 n)\) stays between 35 and 70 (×10⁻⁶ ms) across that 400× range.
Overfitting for trees is a cliff, not a subtle effect. Same learning problem, depth swept:
max_depth |
leaf nodes | train acc | test acc |
|---|---|---|---|
| 1 | 2 | 0.8000 | 0.7700 |
| 2 | 4 | 0.8243 | 0.7889 |
| 4 | 15 | 0.8514 | 0.8156 |
| 6 | 48 | 0.8686 | 0.7944 |
| 9 | 133 | 0.9062 | 0.7944 |
None (until pure) |
355 | 1.0000 | 0.7756 |
Unrestricted, the tree hits 100% training accuracy with 355 leaves and ends up worse than the 2-leaf stump. Each leaf now averages a handful of points — the account_id <= 1493 split from the opening, mechanised. Chapter 13 decomposes why: variance grows with leaf count until it outruns the bias it removes.
Why trees need no scaling and shrug off noise
Both properties fall out of the axis-aligned structure, and both are why trees survive real data where Chapter 1’s least squares and Chapter 5’s k-NN do not.
Scale invariance. A split is a comparison \(x_j \le t\); multiplying \(x_j\) by \(10^6\) multiplies \(t\) by \(10^6\) and changes nothing about which points go left. Rescale columns by wildly different factors and the tree is bit-identical:
rng = np.random.default_rng(0)
X = rng.normal(size=(400, 4))
y = 10*np.sin(np.pi*X[:,0]*X[:,1]) + 20*(X[:,2]-0.5)**2 + 10*X[:,3] + 15
scales = np.array([1e-3, 1e6, 1.0, 4e4]) # wildly different units per column
A, B = CART().fit(X, y, max_depth=4), CART().fit(X * scales, y, max_depth=4)
print(np.array_equal(A.predict(X), B.predict(X * scales))) # True
k-NN’s distance, by contrast, is a sum of per-feature squares, so a dollar-denominated feature contributes \(10^{12}\) times what a year-denominated one does. Trees need nothing.
Noise immunity. A pure-noise column can win a split — with 202 candidate features one of them will occasionally produce a pure-looking child by luck — but the damage is bounded, because every leaf value averages many points and the lucky splits are not consistent across nodes. Same 2,100-row problem, columns that are definitionally random:
| extra pure-noise dims | depth-6 tree test acc | 5-NN test acc |
|---|---|---|
| 0 | 0.794 | 0.813 |
| 10 | 0.800 | 0.754 |
| 50 | 0.788 | 0.624 |
| 200 | 0.789 | 0.596 |
| 500 | 0.806 | 0.583 |
The tree’s test accuracy moves inside a 0.018 band across a 500× increase in input width; k-NN loses 23 points and heads for chance — the distance-concentration collapse Chapter 5 derived. That is the most practically important structural difference between the two, and the reason a tree is a sane default on tabular data before you have done feature selection. The catch: “immune to noise features” is not “immune to noise labels”. A mislabeled row still attracts splits, because isolating it genuinely lowers training impurity — on ID-like columns that is the account_id failure again, so drop the column rather than add depth.
Pitfalls
- Trusting the Gini/entropy approximation. \(G \approx \frac{2}{\ln 2}H\) is off by a factor of 5.77 at a balanced node. The measured facts: \(G \le H/2\) with equality only at balance, and \(G/H = 0.175\) at \(p = 0.001\). Report what you measured, not the slide’s constant.
- Skipping standardization “because trees don’t need it.” True for the split rule — a rescaled tree is bit-identical. False downstream: permutation importance, partial dependence, and distance-based diagnostics all read the original units.
- Leaving
max_depth=None. 355 leaves, 100% train accuracy, 0.7756 test — worse than a 2-leaf stump. Setmax_depthormin_samples_leafand cross-validate it (Chapter 13). - Reading impurity decrease as importance. It is a training-set statistic, biased toward high-cardinality features. Chapter 7 gives the permutation-based alternative and quantifies the bias.
- Expecting depth to fix a bad feature set. Trees shrug off noise dimensions, not noise labels; at depth 9 a mislabeled row gets its own leaf with a memorised value.
- Using a tree where order matters. Axis-aligned splits are a hard bias: a threshold on
agecannot express a diagonal, and the diagonal-orbitant problem needs roughly six levels of staircase. Forests (Chapter 7) average the staircases away; one tree cannot.
Show that IG is always non-negative, and explain why a pure node makes every candidate split score exactly 0. Verify numerically that \(G \le H/2\) with equality only at \(p = \tfrac12\), and say what \(G/H\) does as \(p \to 0\) and why the two asymptotics differ. In the 8-point set, trace why the greedy split \(x_2 \le 4\) leaves a 6-point child with \(H = 1.0\) while \(x_2 \le 3\) does not. Finally: your unpruned tree has 355 leaves and 100% training accuracy — decompose why its test accuracy is lower than the 2-leaf stump’s, and name two structural changes that would help.
ASolution
IG subtracts a weighted average of child impurities from the parent impurity, and both children lie in \([0, \text{imp}_{\max}]\), so the weighted average does too and IG \(\ge 0\). A pure node has one \(p_c = 1\), giving \(H = 0\) and \(G = 0\); every threshold distributes that single class among the children in some proportion, so both child impurities are 0 too and IG \(= 0\) exactly — no threshold can improve on certainty. On \(G \le H/2\): a grid of 200,001 points in \(p \in (0, \tfrac12]\) found \(H - 2G\) negative at none of them, minimum exactly 0 only at \(p = \tfrac12\), which follows from both measures having zero first derivative there (\(H' = \log_2\frac{1-p}{p}\), \(G' = 2(1-2p)\)) so both are quadratic, with \(H(\tfrac12) = 1\) and \(G(\tfrac12) = 0.5\). As \(p \to 0\) the ratio falls to 0.175 because the asymptotics are different functions: \(G = 2p(1-p) \approx 2p\) while \(H \approx p\log_2(1/p) + p/\ln 2\), so entropy keeps charging \(p\log(1/p)\) for a near-pure node while Gini charges only \(2p\). On the greedy failure: \(x_2 \le 4\) puts six points left, exactly 3 + and 3 −, so \(H = 1.0\) — the binary maximum — while the two right-hand points are pure; the root still scores 0.2044 because the parent’s 0.9544 is being averaged against a zero. \(x_2 \le 3\) scores a worse 0.1588 but gives a 3-point left child (2 −, 1 +) and a 5-point right child (4 +, 1 −), each linearly separable in \(x_1\), so the second level finishes with one error instead of two. Impurity cannot see past one node. On the 355-leaf tree: test MSE \(= \text{bias}^2 + \text{variance} + \text{noise}\) and each extra leaf fits a mean to fewer points, so leaf variance grows roughly as \(1/n_{\text{leaf}}\); past depth 4 that term outgrows the squared bias it removes. Cap max_depth or set min_samples_leaf and cross-validate (Chapter 13), and reduce max_features so no single lucky split can dominate a node.
Next: Deriving Random Forests (ML #7) — averaging hundreds of trees, and the variance decomposition that says exactly how much decorrelation is worth.