Module contents
Lesson 14 of 24Core 110 min

Decision trees: CART from scratch

Build classification and regression trees with CART: greedy recursive partitions minimizing impurity (Gini, entropy, variance). Implement efficient split search by sorting once per feature, handling categorical and missing values, and cost-complexity pruning. Explain tree instability, the flaw bagging and boosting turn into a strength.

After this lesson you can

  • Implement CART for classification and regression with O(n log n) best-split search per feature.
  • Compare Gini, entropy and classification error as criteria and justify why the last is not used to grow trees.
  • Find an optimal categorical split by ordering levels by target mean.
  • Apply cost-complexity pruning and choose α by cross-validation.
  • Handle missing values with surrogate splits or a default direction.
  • Measure a tree's instability under data perturbations.

Before you start

Motivation: a model that asks instead of adding

All models in the module so far combine features by weighted sums or distances: linear and logistic regression compute w⊤x+b\vb{w}\T\vb{x} + b, k-nearest neighbors measure ∥x−xi∥\norm{\vb{x} - \vb{x}_i} and SVM uses inner products. Three consequences have already cost you: features must be standardized, interactions (x1x2x_1 x_2, a polynomial basis) built by hand, and categorical features encoded as numbers.

A decision tree does something else: it asks. “Is x3≤2.5x_3 \le 2.5?” If yes it asks a second question, perhaps about another feature; if no it asks another. At the end of the question chain is a leaf with a constant prediction. Its advantages follow:

  • Automatic interactions. The second question depends on the first answer, so the effect of x2x_2 may differ on each side of x1x_1. A linear model needs the x1x2x_1 x_2 term supplied; the tree discovers it.
  • Invariance to monotone transformations. A question xj≤tx_j \le t depends only on the order of xjx_j values. Replace xjx_j by log⁡xj\log x_j or its rank and the tree makes exactly the same data partitions. No scaling is needed, and an outlier in xjx_j pulls on nothing.
  • Mixed types, missing values and cheap prediction. Categoricals and missing values have their own treatments (seen here), and prediction costs tree depth.
  • The building block of leading tabular models. A single tree is rarely best, but averages of trees (random forests) and sums of trees (gradient boosting) are tabular benchmarks, as the module frontier shows.

Drawbacks are equally characteristic: prediction is piecewise constant (an oblique boundary becomes a staircase) and, above all, the tree is unstable: small data changes can change it greatly. This lesson builds CART (Classification And Regression Trees, Breiman, Friedman, Olshen and Stone, 1984) from scratch: partitions, impurity criteria, efficient split search, categoricals, pruning, missing values and instability, precisely the defect bagging and boosting turn into a strength in subsequent lessons.

The tree as a partition into rectangles

Every question cuts space with a hyperplane perpendicular to an axis, so each RmR_m is the intersection of half-spaces {xj≤t}\{x_j \le t\} or {xj>t}\{x_j > t\}: a rectangle (product of intervals, some unbounded). The MM leaf rectangles are disjoint and cover Rd\R^d: a tree partitions space into axis-aligned rectangles with a constant function in each. The tree structure from discrete mathematics describes the partition: each root-to-leaf path lists inequalities defining its rectangle. Read backwards, each path is a rule “if x3≤2.5x_3 \le 2.5 and x1>0.7x_1 > 0.7, then class 1”: a small tree is a set of readable rules, hence its place among interpretable models in the interpretability section.

Which constant goes in each leaf? Given a partition, the problem separates: empirical loss is a sum of terms, one per leaf, each depending only on its cmc_m. The best value minimizes mean loss of leaf examples, familiar from loss functions:

  • with squared loss, the leaf response mean yˉm\bar y_m;
  • with 0–1 loss, the leaf majority class;
  • with logistic or Brier loss, class-proportion vector p^m\hat{\vb{p}}_m (so a classification tree gives probabilities: leaf frequencies).

Learning a tree therefore means choosing a partition. Empirical tree risk with optimal constants is ∑m(nm/n) i(Rm)\sum_m (n_m/n)\, i(R_m), where nmn_m is the example count in leaf mm and ii measures how poorly its best constant performs. That number is leaf impurity and decides where to split.

InteractiveBuild the tree by hand
Data and partition (shading: majority class of each leaf)
The tree (click a leaf to select it)
n=14G 0.41n=76G 0.50x₁ ≤ 0.25n=90
Gini gain when splitting the selected leaf by x1≤tx_1 \le t
Enable “Show CART choice” to see the curve
  • class 0
  • class 1
  • your split (preview)
  • best CART split
Data
Split orientation
Leaves in your tree2
Weighted Gini ∑mnmnGm\sum_m \tfrac{n_m}{n} G_m0.483
Training error43.3 %
Greedy CART with same leaf count0.367 · error 26.7 %
Selected leafn = 76 (41 and 35) · G = 0.497
Your split: gain in leaf−
Greedy CART with 2 leaves has weighted Gini 0.367; yours is 0.483. Enable “Show CART choice” to see where it splits.
Each point is a two-class example from an explicit model: x1,x2x_1, x_2 uniform on [0,1][0, 1] and class 1 with probability 0.9 inside an L-shaped region (0.1 outside), fixed seed. Choose orientation and click within a leaf to split it. The readout gives weighted Gini for your tree and greedy CART with the same leaf count (best-first growth, as with max_leaf_nodes). Activate ‘Mostrar la elección de CART’ (show CART choice): the step curve gives each threshold’s gain along the selected leaf’s axis, and CART picks its maximum. Then try exclusive-or: what does the root curve look like?

Two things the figure shows. The gain curve is stepwise: it changes only when the threshold crosses a point, so with ntn_t points at a node there are at most nt−1n_t - 1 distinct splits per feature; CART evaluates them all and keeps the best. For exclusive-or the root curve is almost flat: no isolated split separates classes, although two levels nearly separate them. A hand-built four-leaf tree beats greedy CART with four leaves there. We return to this when discussing search.

Measuring node impurity

Let tt be a node with ntn_t examples and class proportions pk=nt,k/ntp_k = n_{t,k}/n_t, k=1,…,Kk = 1, \dots, K.

Gain is measured within the node. Reduction in total tree impurity ∑m(nm/n) i(Rm)\sum_m (n_m/n)\, i(R_m) when splitting tt is (nt/n) Δi(s,t)(n_t/n)\,\Delta i(s, t): an excellent split at a small node counts little. This is the quantity summed by scikit-learn impurity-reduction feature importance, whose bias you will study in the random forest lesson.

Each impurity is the risk of the best node constant under a specific loss, explaining which suits each task:

  • Error and 0–1 loss. The best constant is majority class and fails on fraction 1−max⁡kpk1 - \max_k p_k.
  • Gini and squared loss on one-hot. Predicting vector q\vb{q} for every node example gives mean Brier loss 1nt∑i∥eyi−q∥2\frac{1}{n_t}\sum_i \norm{\vb{e}_{y_i} - \vb{q}}^2, minimized at q=p\vb{q} = \vb{p} with value ∑kpk(1−pk)=G(t)\sum_k p_k(1 - p_k) = G(t): total variance of the one-hot vector. With two classes G=2p(1−p)G = 2p(1 - p) is twice the variance of a 0/1 label, so a two-class Gini tree chooses the same splits as a least-squares regression tree on y∈{0,1}y \in \{0, 1\}. The first lab cell checks it.
  • Entropy and log loss. Mean log loss of predicting q\vb{q} is −∑kpklog⁡2qk-\sum_k p_k \log_2 q_k, minimized at q=p\vb{q} = \vb{p} (Gibbs inequality) with value H(t)H(t). Entropy gain is then H(Y)−H(Y∣S)H(Y) - H(Y \given S) in the node, with SS the split side: conditional entropy subtracted from entropy, i.e. mutual information between label and answer. Hence information gain.
  • Variance and squared loss. The best constant is the mean and its mean loss is variance.

Why trees are not grown using error

The key is that parent proportions are the weighted average of children’s: pt=wLpL+wRpR\vb{p}_t = w_L \vb{p}_L + w_R \vb{p}_R with wL=nL/ntw_L = n_L/n_t, wR=nR/ntw_R = n_R/n_t. Gain is then the difference between a function at an average and the average of the function, Jensen’s inequality territory.

Proof

By concavity ϕ(pt)=ϕ(wLpL+wRpR)≥wLϕ(pL)+wRϕ(pR)\phi(\vb{p}_t) = \phi(w_L \vb{p}_L + w_R \vb{p}_R) \ge w_L\phi(\vb{p}_L) + w_R\phi(\vb{p}_R), which is Δi≥0\Delta i \ge 0. If ϕ\phi is strictly concave and pL≠pR\vb{p}_L \neq \vb{p}_R, with wL,wR∈(0,1)w_L, w_R \in (0, 1) the inequality is strict. If pL=pR\vb{p}_L = \vb{p}_R, also pt=pL\vb{p}_t = \vb{p}_L and all three terms agree.

∎

Gini is strictly concave (you will prove it in an exercise), as is entropy. Error is not: 1−max⁡kpk1 - \max_k p_k is concave (one minus a maximum of linear functions, which is convex) but linear in each simplex region where the majority class does not change. That produces its defect.

Proof

E(tL)=1−pL,k∗E(t_L) = 1 - p_{L,k^*} and E(tR)=1−pR,k∗E(t_R) = 1 - p_{R,k^*}, so wLE(tL)+wRE(tR)=1−(wLpL,k∗+wRpR,k∗)=1−pt,k∗=E(t)w_L E(t_L) + w_R E(t_R) = 1 - (w_L p_{L,k^*} + w_R p_{R,k^*}) = 1 - p_{t,k^*} = E(t).

∎

Example: a node with 70 positives and 30 negatives splits into (40,5)(40, 5) and (30,25)(30, 25). Both children remain majority positive, so error does not move: 0.300.30 before and 0.300.30 after. But the left child is nearly pure (89 % positive), and the nearly balanced right child can profitably split again. Gini gives gain 0.0580.058 and entropy 0.1080.108 bits. A tree grown by error would see zero gain on this and many neighboring splits: it would either stop or choose randomly.

The second defect appears in The Elements of Statistical Learning (section 9.2.3): a node with 400 of each class and two candidate splits, A with children (300,100)(300, 100) and (100,300)(100, 300), B with (200,400)(200, 400) and (200,0)(200, 0). Both leave 25 % error but B makes one child pure. Gini prefers B (0.1670.167 versus 0.1250.125), as does entropy (0.3110.311 versus 0.1890.189 bits). A pure child is a finished leaf; one at 75 % still needs work.

InteractiveGini, entropy and error
Node impurity versus positive fraction pp; points: children; chords: their weighted mean
00.10.20.30.40.500.250.50.751pLpRp del padre
  • error min⁡(p,1−p)\min(p, 1 - p)
  • Gini 2p(1−p)2p(1 - p)
  • entropy H(p)/2H(p)/2 (bits)
Example
40 de 70
5 de 30
Entropy scale
Parent (+, −)(70, 30)
Children (+, −)(40, 5) and (30, 25)
Parent pp0.700
pLp_L and pRp_R0.889 and 0.545
Weights wLw_L and wRw_R0.45 and 0.55
Error gain0.0000
Gini gain0.0584
Entropy gain (bits)0.1081
Both children have the same majority class as the parent: error does not change (gain 0), but Gini (0.058) and entropy (0.108 bits) detect that the left child is much purer.
Three binary-node impurities versus positive proportion pp (entropy divided by two so all equal 0.50.5 at p=1/2p = 1/2). Each child is a point on each curve and their weighted average is the hollow point on the chord at parent pp. The vertical bar between curve and chord is gain. Start with 70/30: the red error chord lies on its curve. Move counts until one child crosses p=1/2p = 1/2, then compare ESL splits A and B.

None of this makes error useless: it is what you ultimately minimize and what CART used to evaluate pruning. It cannot guide growth, a greedy search needing a signal rewarding purer nodes even before majority changes. Gini and entropy differ little in practice: on 232 of 300 random lab nodes they choose exactly the same split and, when not, entropy’s split achieves 94 % of best-split Gini gain on average. Gini is slightly cheaper (no logarithms) and scikit-learn’s default.

Finding the best split

At a node with ntn_t examples and dd features, how many splits must be examined? For feature jj, split xj≤tx_j \le t depends only on which examples lie on each side, changing only when tt crosses an observed value. Sort distinct values v1<v2<⋯<vrv_1 < v_2 < \dots < v_r of xjx_j at the node; the distinct splits are r−1≤nt−1r - 1 \le n_t - 1 separating viv_i from vi+1v_{i+1}. Representing them needs a convention: scikit-learn uses midpoint (vi+vi+1)/2(v_i + v_{i+1})/2, other implementations viv_i itself. Training data are unaffected, but a new point between viv_i and vi+1v_{i+1} is not.

Evaluating each threshold separately costs O(nt)\bigO(n_t) (count each side) and there are nt−1n_t - 1: O(nt2)\bigO(n_t^2) per feature. The observation reducing this to O(ntlog⁡nt)\bigO(n_t \log n_t) is that impurities depend on a few sufficient statistics per side, updated in O(1)\bigO(1) when an example crosses the threshold:

  • in classification, class counts (nL,1,…,nL,K)(n_{L,1}, \dots, n_{L,K}); right-side counts are node totals minus left;
  • in regression, (nL,SL,QL)(n_L, S_L, Q_L) with SL=∑LyiS_L = \sum_{L} y_i and QL=∑Lyi2Q_L = \sum_{L} y_i^2.

In regression gain is computed without revisiting data. For a node ∑i(yi−yˉ)2=Q−S2/n\sum_i (y_i - \bar y)^2 = Q - S^2/n, so the sum-of-squares reduction is:

ΔSSE=SSE−SSEL−SSER\Delta\mathrm{SSE} = \mathrm{SSE} - \mathrm{SSE}_L - \mathrm{SSE}_R
Parent sum of squares minus the two children’s.
1/4

Dividing by nn gives variance gain ΔV\Delta V from the definition. The last form shows what the criterion rewards: separating different means without leaving one side very small. The same holds for two-class Gini, twice the variance of a 0/1 label: ΔG=2 nLnRn2(pL−pR)2\Delta G = 2\,\frac{n_L n_R}{n^2}(p_L - p_R)^2.

InteractiveThe best-split sweep
Data sorted by xx, cursor and means on each side
−1.02.05.00246810t = 0.25
Reduction in sum of squares Δ(t)\Delta(t), drawn as the cursor moves
028.7
  • points and mean on left
  • points and mean on right
  • overall mean
  • best threshold so far
1 on the left
Data
Threshold tt (midpoint)0.25
nLn_L and SLS_L1 and 0.93
nRn_R and SR=S−SLS_R = S - S_L23 and 47.35
Gain Δ(t)\Delta(t)1.224
Best threshold0.25 (Δ = 1.22)
Additions: sweep / from scratch1 / 24
Step 1 of 23: the point crossing the cursor changes SLS_L, SRS_R, nLn_L and nRn_R with one addition. Play to the end.
24 points from an explicit model (xx uniform on [0,10][0, 10], yy a step plus normal noise of standard deviation 0.450.45, fixed seed), already sorted by xx. Each step moves one point right to left, changing only nLn_L, SLS_L, nRn_R and SRS_R, each with one sum. Below: sum-of-squares reduction at each threshold; the circle marks the best so far. Compare addition counts with recalculating every split from scratch. With ‘Solo ruido’ (noise only), does the sweep find a split anyway?

With step data the maximum falls at the jump. With ‘Solo ruido’ the curve also has a maximum and this sample’s is at an extreme: the best split leaves one point on the left and still reduces sum of squares by 17 %. This is impurity criteria’s preference for extreme splits, already analyzed by Breiman et al.: among many splits without signal, those isolating a few extreme points tend to give greatest apparent gain. Hence min_samples_leaf and pruning.

Cost of growing a tree

With the sweep, splitting a node costs O(d ntlog⁡nt)\bigO(d\, n_t \log n_t). Nodes at one depth partition the nn examples, so processing a whole level costs O(d nlog⁡n)\bigO(d\, n \log n). Total depends on tree shape:

  • Balanced, depth ≈log⁡2n\approx \log_2 n: O(d nlog⁡2n)\bigO(d\, n \log^2 n). This is divide-and-conquer recurrence T(n)=2T(n/2)+O(d nlog⁡n)T(n) = 2T(n/2) + \bigO(d\, n\log n).
  • Degenerate, if each split separates one example: depth n−1n - 1 and O(d n2log⁡n)\bigO(d\, n^2 \log n).
  • With presorting: sort each feature once at the root and pass each child its already sorted list (stable partition costs O(nt)\bigO(n_t)); each level costs O(d n)\bigO(d\,n) and the balanced tree O(d nlog⁡n)\bigO(d\, n\log n). Older scikit-learn versions offered presort; today each node sorts, while boosting libraries replace sorting with histograms of around 256 values.

Chapter 5 of Louppe’s thesis (2014) analyzes this in detail for trees and forests.

CodeThe sweep by hand
Implement best_split(x, y, criterion) for continuous feature x (array of shape (n,), possibly repeated values). criterion is 'gini' or 'entropy' (then y contains integers 0 to K − 1) or 'mse' (then y is real and impurity is variance). Return (t, ganancia): threshold t (midpoint between consecutive distinct x values) maximizing i(padre)−nLni(L)−nRni(R)i(\text{padre}) - \tfrac{n_L}{n} i(L) - \tfrac{n_R}{n} i(R) with x <= t on the left, and its gain. If all x values are equal, return (None, None). It must cost O(nlog⁡n)\bigO(n\log n): a test runs it with n=20 000n = 20\,000.
import numpy as np

def best_split(x, y, criterion):
  """Mejor corte x <= t de una variable continua por barrido ordenado."""
  x = np.asarray(x, dtype=float)
  y = np.asarray(y)
  # tu código: ordena, acumula los estadísticos de la izquierda, deduce los de la derecha,
  # descarta las posiciones en las que el siguiente valor es igual y toma el máximo
  return None, None
Shift+Enter to run

Greedy, and why not optimal

CART grows top-down: choose the root’s best split, distribute data and repeat for each child, never backtracking. This is a greedy strategy inside divide-and-conquer recursion, and does not guarantee the best tree of a given size. Nor is there hope for an efficient algorithm that does: Hyafil and Rivest (1976) proved building the binary decision tree identifying each object in a set with minimum expected questions is NP-complete, and natural variants such as finding the smallest tree correctly classifying data have similar hardness results.

The first figure’s exclusive-or is a minimal example of greedy loss. With infinite data any vertical split x1≤tx_1 \le t leaves exactly half of each class in each child (by symmetry), so every root split has zero gain; with finite data CART splits where noise gives slightly higher gain (in the figure x1≤0.65x_1 \le 0.65, gain 0.0330.033). But split x1≤1/2x_1 \le 1/2, useless alone, enables two x2≤1/2x_2 \le 1/2 splits separating classes. A split’s worth depends on subsequent splits, and greedy search does not look ahead. Breiman and coauthors’ practical answer was overgrow and then prune.

Categorical features

A categorical feature with LL levels (neighborhood, brand, postal code) has no order. A binary split sends a subset AA left, and there are 2L−1−12^{L-1} - 1 nontrivial partitions: 511 for 10 levels and over half a million for 20. Trying all quickly becomes infeasible as LL grows. For the two most important cases it is unnecessary.

This categorical split result reduces search from exponential to linear (plus sorting LL means) and makes the categorical an ordered feature within each node, with order recomputed from node data. The regression proof is the final guided exercise; its idea is that level-split gain is nAnBn(yˉA−yˉB)2\frac{n_A n_B}{n}(\bar y_A - \bar y_B)^2, from the earlier derivation, and in an optimal partition each level belongs to the group with closest mean. Two-class Gini has the same statement because Gini is twice 0/1 label variance. Entropy needs another argument supplied by Breiman et al.; The Elements of Statistical Learning (section 9.2.4) collects the result for Gini, entropy and squared loss.

InteractiveOrdering levels
Mean yy at each level (point area ∝ nkn_k); color: side of displayed partition
0.02.04.0A (14)B (30)C (8)D (22)E (16)F (26)
Partición mostrada (puesto 1): {A, C, E} frente a {B, D, F}, ganancia 0.6479 (ordenada)
All 31 binary partitions, ordered by decreasing gain; ring: follows mean order
00.65puesto 1 … 31
  • left in displayed partition
  • right
  • ordered partition (one of 5)
Objective
Partitions: all / ordered31 / 5
Best gain (per example)0.6479
Is the best ordered?yes
Rank of displayed partition1 of 31
Sort levels by their mean: B < F < D < A < E < C. The best of 31 partitions cuts this list at one point: testing 5 suffices.
Six levels A, … , F of a categorical feature with 14, 30, 8, 22, 16 and 26 examples. Drag the mean response for any level (initial values are arbitrary). Below, 31 binary partitions sorted by decreasing gain, computed exactly; rings mark the 5 that split the level list sorted by mean. Select a partition to color it above. Can an unringed partition win? Switch to ‘Binario (Gini)’, where each level has a positive proportion.

With three or more classes this fails: no level ordering guarantees optimum. The lab gives a concrete counterexample with 3 classes and 7 levels where the best split is not among those ordered by any of the three class proportions. Implementations then use exhaustive search for small LL or heuristics.

Encode or handle natively

If a library does not support categoricals (scikit-learn DecisionTreeClassifier does not), encode them; each encoding changes available tree splits:

  • One-hot: each column permits one split, “level ℓ\ell versus the rest.” Separating a group of kk levels from the rest costs kk chained splits, each on a node with less data; many levels dilute signal among nearly empty columns.
  • Arbitrary integer codes (0,1,…,L−10, 1, \dots, L-1): the tree can only split contiguous runs in a meaningless order.
  • Target-mean encoding: mimics Breiman’s ordering, but calculated once and leaking labels unless internal cross-validation is used.
  • Native support: LightGBM orders levels per node by gradient statistics and CatBoost uses ordered target statistics to avoid leakage; see the LightGBM and CatBoost lesson. scikit-learn HistGradientBoostingClassifier also supports categoricals.

In the lab with a 20-level categorical and equal depth 2, native splitting gives test mean squared error 0.812 versus 1.490 for one-hot and 1.739 for arbitrary codes. At sufficient depth encodings converge, at the cost of larger, more unstable trees. A warning about native support: with many levels the ordering uses yy itself to choose among many possible splits, overfitting; libraries require minimum examples per level or smooth means.

Stop or prune

A tree allowed to grow without limits ends with pure leaves: zero training error and a partition memorizing noise. There are two ways to control it.

Stopping rules. Do not split a node if maximum depth is reached (max_depth), it has too few examples (min_samples_split), a child would have fewer than min_samples_leaf, weighted gain is below min_impurity_decrease, or the tree already has max_leaf_nodes leaves. They are cheap but myopic: earlier exclusive-or and 70/30 splits have small or zero immediate gain yet open excellent splits below. A minimum-gain rule discards them.

Pruning. Grow a large tree Tmax⁡T_{\max}, then remove branches while considering the whole tree. This is CART’s proposal, most studied as cost-complexity pruning. A pruned subtree T⪯Tmax⁡T \preceq T_{\max} is obtained by collapsing internal nodes of Tmax⁡T_{\max} into leaves (retaining the root). Write T~\tilde T for its leaf set and R(T)=∑t∈T~R(t)R(T) = \sum_{t \in \tilde T} R(t) for its risk, with R(t)=ntn i(t)R(t) = \frac{n_t}{n}\, i(t). CART used classification error for ii; scikit-learn uses the same impurity as growth (Gini or entropy).

α\alpha is the price of a leaf: with α=0\alpha = 0 the full tree wins and large α\alpha leaves only the root. This seems to require a different optimization for each α\alpha, but no:

Proof

Since RαR_\alpha is a sum over leaves, the best pruned subtree hanging from node tt is computed bottom-up. Let Ct(α)C_t(\alpha) be its cost: at a leaf of Tmax⁡T_{\max}, Ct(α)=R(t)+αC_t(\alpha) = R(t) + \alpha; at an internal node Ct(α)=min⁡{R(t)+α, CtL(α)+CtR(α)}C_t(\alpha) = \min\{R(t) + \alpha,\ C_{t_L}(\alpha) + C_{t_R}(\alpha)\}, and to keep the smallest collapse tt on a tie. Each CtC_t is the minimum of finitely many lines in α\alpha (one per branch subtree), with slope equal to its leaf count.

Let Dt(α)=CtL(α)+CtR(α)−R(t)−αD_t(\alpha) = C_{t_L}(\alpha) + C_{t_R}(\alpha) - R(t) - \alpha be the advantage of collapsing. Its derivative (where it exists) is the number of leaves in the best subtrees of both children minus one, at least 11. So DtD_t is continuous and strictly increasing: the set of α\alpha for which tt collapses (Dt(α)≥0D_t(\alpha) \ge 0) is an interval [αt∗,∞)[\alpha^*_t, \infty). Once collapsed, a node stays collapsed for every larger α\alpha, so T(α)T(\alpha) are nested and change only at finitely many values. Near an αk\alpha_k, the branch of tt in TkT_k is fixed and Dt(α)=R(Tk,t)+α∣T~k,t∣−R(t)−αD_t(\alpha) = R(T_{k,t}) + \alpha|\tilde T_{k,t}| - R(t) - \alpha, vanishing at α=gk(t)\alpha = g_k(t): the first node collapsing as α\alpha increases minimizes gkg_k.

∎

The weakest link has a direct interpretation: R(t)−R(Tk,t)R(t) - R(T_{k,t}) is branch risk improvement over collapsing it, and ∣T~k,t∣−1|\tilde T_{k,t}| - 1 is the leaves it costs. gk(t)g_k(t) is improvement per leaf; prune the least productive branch first. The entire sequence is computed by one traversal per iteration, without solving anew for each α\alpha.

InteractiveThe pruning sequence
Partition of the optimal subtree for this α
Cost R(Tk)+α∣T~k∣R(T_k) + \alpha|\tilde T_k| of each subtree: a line with slope ∣T~k∣|\tilde T_k|
00.0130.0260.0390.052
Training and true error of the optimal subtree
0 %10 %20 %30 %40 %00.0130.0260.0390.052
  • optimal subtree and its line
  • lower envelope
  • true error
  • training
  • next weakest link
0.0025
Training sample
Subtree TkT_kk = 0 of 9
Optimal from αk\alpha_k0.0000
Leaves ∣T~∣|\tilde T|23
R(T)R(T) / Rα(T)R_\alpha(T)0.000 / 0.057
Training error0.0 %
True error (exact)21.6 %
Next weakest link: g(t)g(t)0.0061
While α<α1=0.0061\alpha < \alpha_1 = 0.0061 the full tree wins: 23 leaves, training error 0 % and true error 21.6 %. Increase α\alpha.
Full tree (Gini, unlimited depth) on 150 points from the first figure’s L model. In the cost panel, each line is cost R(Tk)+α∣T~k∣R(T_k) + \alpha|\tilde T_k| of a sequence subtree and the lower envelope is optimum for each α\alpha. Below are training and true errors of each subtree, computed exactly using known conditional probability; dotted line is Bayes error, 10 %. In the partition, the dashed branch is next to prune. Move α\alpha from 0 and change sample: where is minimum true error?

On the first sample the full tree has 23 leaves, zero training error and 21.6 % true error, over twice Bayes’. Along the sequence true error falls to 13.3 % with 6 leaves, exactly when the subtree reproduces the L and upper-left corner, then rises as pruning removes real structure (43.6 % with root alone). The other two samples give similar curves, minimum at 5 leaves (12.9 % and 12.2 %). The U shape is that of any validation curve, traversed here right to left in complexity.

Choosing α by cross-validation

True error in the figure is unknown in practice, so choose α\alpha by cross-validation. Breiman et al.’s original procedure: compute sequence α0<α1<…\alpha_0 < \alpha_1 < \dots on all data; in each fold grow a tree on its training data, prune at representative values αkαk+1\sqrt{\alpha_k\alpha_{k+1}} (geometric mean of each interval) and measure held-out error. Fold means yield a validation curve versus α\alpha; they also proposed the one-standard-error rule: the largest α\alpha (smallest tree) whose validation error is within one standard error of the minimum. In scikit-learn use cost_complexity_pruning_path for αk\alpha_k and cross-validate ccp_alpha, as in the lab.

Missing values

If an example lacks xjx_j and the node asks about xjx_j, where does it go? Before trees options were discard or impute (median and, better, a missingness indicator). Trees have their own solutions, missing values in trees:

Surrogate splits (CART). Choose the node’s main split s∗s^* using examples with xj∗x_{j^*} observed. Then for each other feature jj find split s~j\tilde s_j that best imitates s∗s^*: maximizes fraction p(s∗,s~j)p(s^*, \tilde s_j) of examples (with both features observed) sent to the same side. Since blind “send all to larger child” already gets fraction max⁡(pL,pR)\max(p_L, p_R) right, CART measures surrogate quality by predictive association

λ(s∗∣s~j)=min⁡(pL,pR)−(1−p(s∗,s~j))min⁡(pL,pR),\lambda(s^* \given \tilde s_j) = \frac{\min(p_L, p_R) - \big(1 - p(s^*, \tilde s_j)\big)}{\min(p_L, p_R)},

the fraction of blind-rule error eliminated by the surrogate. Store surrogates with λ>0\lambda > 0 in order. At prediction, if xj∗x_{j^*} is missing use the first available surrogate, or the blind rule if all are missing. R’s rpart does this.

Default direction. At every split try two versions, all missing left and all missing right, and keep the best; at prediction send missing values that way. This costs only two sweeps and needs no extra splits. It is XGBoost’s sparsity-aware search, seen in the XGBoost lesson, and scikit-learn’s since version 1.3; if a node had no training missing values, scikit-learn sends them to the larger child.

Fractional cases (C4.5). An example missing xjx_j travels both branches with weights proportional to observed frequencies; prediction combines leaves with those weights.

The first two exploit different information. Surrogates use feature correlations: if x1x_1 is missing but x2x_2 imitates it well, the example usually goes where it would have. Default direction uses information in missingness itself: if x1x_1 is missing mostly for positives, sending missing examples to the positive side works even if no other feature knows anything. The lab constructs one case of each kind, with a different method winning each.

Unstable trees

Fit a tree, change a few examples and refit: often the root asks about a different feature and everything below changes. This tree instability has a structural cause. Split selection is an arg max⁡\argmax over finitely many candidates, a discontinuous function of data: when gains are close, tiny perturbations change the winner. Error propagates: changing the root changes data seen by all lower nodes (The Elements of Statistical Learning, section 9.2.4, identifies this as a major tree problem and attributes variance to hierarchy). The result is a high-variance estimator in the bias–variance decomposition sense: low bias for a deep tree, high variation across training sets.

InteractiveUnstable trees
Boundaries of 12 trees overlaid on the mean vote; dashed: Bayes boundary x1+x2=1x_1 + x_2 = 1
12 árboles, profundidad 4
  • class 0 (mean vote)
  • class 1 (mean vote)
  • each tree boundary
  • root split
First trees (root split in color)
x₁ ≤ 0.73
x₁ ≤ 0.72
x₂ ≤ 0.35
x₁ ≤ 0.47
x₂ ≤ 0.35
x₂ ≤ 0.65
El desacuerdo es la fracción del cuadrado en la que dos árboles distintos predicen clases distintas, promediada sobre todos los pares. El color de fondo es la fracción de árboles que votan cada clase.
12
4
Perturbation
Root on x1x_1 / on x2x_29 / 3
Leaves per treefrom 9 to 13
Mean true error of one tree24.6 %
True error of the vote18.8 %
Mean disagreement between two trees22.7 %
The root splits on x1x_1 in 9 trees and x2x_2 in 3. Mean true error of one tree: 24.6 %; of the 12-tree vote: 18.8 % (Bayes: 10%).
120 fixed points from the diagonal model (class 1 with probability 0.9 if x1+x2>1x_1 + x_2 > 1 and 0.1 otherwise, fixed seed). Each tree is fitted to a bootstrap resample of these points, or the same points with 5 % removed. The main panel overlays tree boundaries transparently over the average vote, with dashed Bayes boundary; next to it, first trees with root split highlighted. Readouts show each tree’s exact true error and vote error. Increase BB and depth: how many distinct roots appear? What shape is the average?

The figure shows three things. Root jumps from x1x_1 to x2x_2 across resamples: in the diagonal model both features are equally informative and noise decides. Each tree draws a different staircase around the diagonal. The vote of many trees is smoother and closer to the diagonal, with lower true error than the average tree: initially (12 trees of depth 4), root splits on x1x_1 in 9 and x2x_2 in 3, two trees disagree on 22.7 % of the square on average, and true error drops from 24.6 % for an average tree to 18.8 % for the vote. Breiman (1996) used trees as an unstable procedure example introducing bagging, which averages trees fitted to bootstrap resamples to cancel that variance: the next lesson.

Another, less technical and more dangerous consequence: a single tree’s structure is not a stable explanation of the phenomenon. If two resamples give different roots at equal accuracy, reading “most important feature” into the first question makes no sense. This is a Rashomon effect (many different equally good models), covered in the interpretability section.

Context: ID3, C4.5 and optimal trees

CART was not the only lineage. ID3 (Quinlan, 1986) used discrete attributes, multiway splits (one per value), and information gain; that criterion favors attributes with many values, to the point a unique identifier has maximum gain. C4.5 (Quinlan, 1993) corrected this with gain ratio (gain divided by the partition’s own entropy), added thresholds for continuous features, fractional missing cases, and pruning based on a pessimistic error estimate. Current libraries (scikit-learn, XGBoost, LightGBM, CatBoost) descend from CART: binary splits, regression trees as boosting’s building block, and pruning or explicit regularization.

NP-completeness does not prevent searching for optimal trees on small problems. Bertsimas and Dunn (2017) formulate the optimal bounded-depth tree as mixed-integer programming, and GOSDT (Lin, Zhong, Hu, Rudin and Seltzer, 2020) minimizes error plus a per-leaf penalty using dynamic programming and bounds on binarized features. Cost grows rapidly with depth and threshold count, so these are used for shallow trees when interpretability is the goal. For prediction, the practical answer to variance is averaging many trees, not an optimal tree.

Vocabulary note: state-space search trees from classical AI share structure (nodes, branches, recursion), not purpose: there the tree is the space explored to find a path; here it is a model learned to predict.

Implementation from scratch

The plan: impurities and sweeps vectorized with NumPy, a tree with nodes stored in arrays (as scikit-learn does internally), categorical splits by sorting, weakest-link pruning and missing values. Compare each piece with brute force or scikit-learn.

[ ]Impurities and sorted sweepBrowser
import time
import numpy as np

def impurity(stats, n, criterion):
    """Impureza de uno o varios nodos a partir de sus estadísticos suficientes.
    stats: (..., K) recuentos por clase, o (..., 2) con (Σy, Σy²) si criterion == "mse"."""
    n = np.asarray(n, dtype=float)
    if criterion == "mse":
        return stats[..., 1] / n - (stats[..., 0] / n) ** 2
    p = stats / n[..., None]
    if criterion == "gini":
        return 1.0 - (p ** 2).sum(-1)
    if criterion == "entropy":
        return -(p * np.log2(np.where(p > 0, p, 1.0))).sum(-1)
    raise ValueError(criterion)

def suff_stats(y, criterion, K=None):
    """Una fila de estadísticos por ejemplo: one-hot (clasificación) o (y, y²) (regresión).
    La suma de las filas de un nodo son sus estadísticos suficientes."""
    if criterion == "mse":
        y = np.asarray(y, dtype=float)
        return np.column_stack([y, y * y])
    return np.eye(K)[y]

def sweep(x, Z, criterion, min_leaf=1):
    """Mejor corte x <= t de una variable continua: ordena una vez y acumula. Devuelve (t, ganancia)."""
    m = len(x)
    order = np.argsort(x, kind="stable")              # O(m log m)
    xs, Zs = x[order], Z[order]
    left = np.cumsum(Zs, axis=0)[:-1]                 # fila i: estadísticos de los i+1 menores
    total = Zs.sum(axis=0)
    right = total - left
    nL = np.arange(1, m)
    nR = m - nL
    valid = (xs[1:] > xs[:-1] + 1e-7) & (nL >= min_leaf) & (nR >= min_leaf)
    if not valid.any():
        return None, -np.inf
    hijos = (nL * impurity(left, nL, criterion) + nR * impurity(right, nR, criterion)) / m
    gain = np.where(valid, impurity(total, m, criterion) - hijos, -np.inf)
    i = int(np.argmax(gain))                          # el primero si hay empates
    return xs[i] / 2 + xs[i + 1] / 2, gain[i]

def brute_force(x, Z, criterion, min_leaf=1):
    """Lo mismo probando cada umbral por separado: O(m²)."""
    m, vals = len(x), np.unique(x)
    parent = impurity(Z.sum(0), m, criterion)
    best_t, best_g = None, -np.inf
    for a, b in zip(vals[:-1], vals[1:]):
        t = a / 2 + b / 2
        L = x <= t
        nl = L.sum()
        if nl < min_leaf or m - nl < min_leaf:
            continue
        g = parent - (nl * impurity(Z[L].sum(0), nl, criterion)
                      + (m - nl) * impurity(Z[~L].sum(0), m - nl, criterion)) / m
        if g > best_g:
            best_t, best_g = t, g
    return best_t, best_g

rng = np.random.default_rng(0)
x = np.round(rng.normal(size=400), 1)                 # valores repetidos a propósito
yc = (x + rng.normal(scale=0.8, size=400) > 0.3).astype(int)
yr = np.sin(2 * x) + rng.normal(scale=0.3, size=400)
for crit, y in [("gini", yc), ("entropy", yc), ("mse", yr)]:
    Z = suff_stats(y, crit, 2)
    (t1, g1), (t2, g2) = sweep(x, Z, crit, 5), brute_force(x, Z, crit, 5)
    print(f"{crit:8s} barrido: t = {t1:5.2f}, ganancia = {g1:.5f}   fuerza bruta: t = {t2:5.2f}, ganancia = {g2:.5f}")

# Gini binaria = 2 × varianza de las etiquetas 0/1: el mismo corte que la regresión por mínimos cuadrados
tg, gg = sweep(x, suff_stats(yc, "gini", 2), "gini")
tm, gm = sweep(x, suff_stats(yc, "mse"), "mse")
print(f"Gini sobre y: t = {tg:.2f}, ganancia {gg:.5f};  MSE sobre y en 0/1: t = {tm:.2f}, ganancia {gm:.5f} (× 2 = {2 * gm:.5f})")

xb = rng.normal(size=3000)
Zb = suff_stats((xb + rng.normal(size=3000) > 0).astype(int), "gini", 2)
t0 = time.perf_counter(); sweep(xb, Zb, "gini"); t_sw = time.perf_counter() - t0
t0 = time.perf_counter(); brute_force(xb, Zb, "gini"); t_bf = time.perf_counter() - t0
print(f"n = 3000: barrido {1e3 * t_sw:.1f} ms, fuerza bruta {1e3 * t_bf:.0f} ms (cociente {t_bf / t_sw:.0f})")

Sweep and brute force agree on threshold and gain for all three criteria, including repeated values (valid prevents separating examples with equal xx). Gini gain is exactly twice least-squares gain on the 0/1 label and threshold is the same. With 3000 examples the sweep is hundreds of times faster than brute force, even in the browser, and the ratio grows roughly like n/log⁡nn/\log n.

[ ]Gini or entropy?Browser
rng = np.random.default_rng(3)
iguales, perdida = 0, []
T = 300
for _ in range(T):                                    # nodos aleatorios: 80 ejemplos, 4 variables, clase logística
    X = rng.normal(size=(80, 4))
    y = (rng.random(80) < 1 / (1 + np.exp(-(X @ (2 * rng.normal(size=4)))))).astype(int)
    eleccion, g_gini = {}, {}
    for crit in ("gini", "entropy"):
        res = [sweep(X[:, j], suff_stats(y, crit, 2), crit) for j in range(4)]
        j = int(np.argmax([g for _, g in res]))
        eleccion[crit] = (j, res[j][0])
    iguales += eleccion["gini"] == eleccion["entropy"]
    if eleccion["gini"] != eleccion["entropy"]:       # ganancia de Gini del corte de la entropía frente al óptimo de Gini
        Zg = suff_stats(y, "gini", 2)
        j, t = eleccion["entropy"]
        L = X[:, j] <= t
        g_ent = impurity(Zg.sum(0), 80, "gini") - (L.sum() * impurity(Zg[L].sum(0), L.sum(), "gini")
                                                  + (~L).sum() * impurity(Zg[~L].sum(0), (~L).sum(), "gini")) / 80
        g_best = sweep(X[:, eleccion["gini"][0]], Zg, "gini")[1]
        perdida.append(1 - g_ent / g_best)
print(f"mismo corte (variable y umbral) en {iguales} de {T} nodos")
print(f"cuando difieren, el corte de la entropía consigue de media un {100 * (1 - np.mean(perdida)):.1f} % de la ganancia de Gini óptima "
      f"(el peor caso, {100 * (1 - np.max(perdida)):.1f} %)")

In 232 of 300 nodes both criteria choose the same feature and threshold. In the other 68, entropy’s split achieves 94.1 % of the best Gini gain on average and 76.6 % in the worst case: they see almost the same thing, and when they disagree choose splits of similar quality. Shape differs near pure nodes: slope of −plog⁡2p-p\log_2 p at p=0p = 0 is infinite and p(1−p)p(1 - p) has slope 1, so entropy penalizes small contamination of a nearly pure node more than Gini.

[ ]The tree with nodes in arraysBrowser
from sklearn.datasets import make_classification, make_friedman1
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor

class CART:
    """Árbol CART con los nodos en arrays (como sklearn.tree._tree.Tree).
    criterion: "gini", "entropy" o "mse". categorical: índices de columnas con códigos enteros 0..L-1."""

    def __init__(self, criterion="gini", max_depth=None, min_samples_leaf=1, min_samples_split=2, categorical=()):
        self.criterion, self.max_depth = criterion, max_depth
        self.min_samples_leaf, self.min_samples_split = min_samples_leaf, min_samples_split
        self.categorical = set(categorical)

    def fit(self, X, y):
        X = np.asarray(X, dtype=float)
        self.K = None if self.criterion == "mse" else int(np.max(y)) + 1
        self.L = int(max([X[:, j].max() for j in self.categorical], default=0)) + 1
        Z = suff_stats(y, self.criterion, self.K)
        self.feature, self.threshold, self.left, self.right = [], [], [], []
        self.left_levels, self.value, self.imp, self.n = [], [], [], []
        self.ties = 0                                   # nodos en los que dos variables empatan en ganancia
        self._grow(X, Z, np.arange(len(X)), 0)
        for a in ("feature", "threshold", "left", "right", "n", "left_levels"):
            setattr(self, a, np.array(getattr(self, a)))
        self.value, self.imp = np.array(self.value), np.array(self.imp)
        return self

    def _grow(self, X, Z, idx, depth):
        node, m = len(self.feature), len(idx)
        stats = Z[idx].sum(0)
        imp = float(impurity(stats, m, self.criterion))
        self.feature.append(-1); self.threshold.append(np.nan); self.left.append(-1); self.right.append(-1)
        self.left_levels.append(np.zeros(self.L, bool))
        self.value.append(stats / m); self.imp.append(imp); self.n.append(m)
        if ((self.max_depth is not None and depth >= self.max_depth) or m < self.min_samples_split
                or m < 2 * self.min_samples_leaf or imp <= 1e-12):
            return node                                   # hoja
        gains, rules = [], []
        for j in range(X.shape[1]):
            if j in self.categorical:
                rule, g = cat_split(X[idx, j].astype(int), Z[idx], self.L, self.criterion, self.min_samples_leaf)
            else:
                rule, g = sweep(X[idx, j], Z[idx], self.criterion, self.min_samples_leaf)
            gains.append(g); rules.append(rule)
        j = int(np.argmax(gains))
        if not np.isfinite(gains[j]):
            return node
        self.ties += int(np.sum(np.array(gains) >= gains[j] - 1e-12) > 1)
        self.feature[node] = j
        if j in self.categorical:
            self.left_levels[node] = rules[j]
            go = rules[j][X[idx, j].astype(int)]
        else:
            self.threshold[node] = rules[j]
            go = X[idx, j] <= rules[j]
        self.left[node] = self._grow(X, Z, idx[go], depth + 1)     # preorden: el hijo izquierdo primero
        self.right[node] = self._grow(X, Z, idx[~go], depth + 1)
        return node

    def apply(self, X):
        """Hoja de cada ejemplo: todos bajan a la vez, un nivel por iteración."""
        X = np.asarray(X, dtype=float)
        node = np.zeros(len(X), dtype=int)
        while True:
            act = np.flatnonzero(self.feature[node] >= 0)   # ejemplos que aún están en un nodo interno
            if act.size == 0:
                return node
            nd = node[act]
            f = self.feature[nd]
            v = X[act, f]
            cat = np.isin(f, list(self.categorical))
            go = np.where(cat, self.left_levels[nd, np.where(cat, v, 0).astype(int)], v <= self.threshold[nd])
            node[act] = np.where(go, self.left[nd], self.right[nd])

    def predict(self, X):
        v = self.value[self.apply(X)]
        return v[:, 0] if self.criterion == "mse" else v.argmax(1)

def cat_split(codes, Z, L, criterion, min_leaf=1):
    """Corte categórico de Breiman: ordena los niveles presentes por la media de y (regresión) o por la
    proporción de la clase 1 (binaria) y barre esa lista. Devuelve (máscara de niveles a la izquierda, ganancia)."""
    S = np.zeros((L, Z.shape[1])); np.add.at(S, codes, Z)
    n = np.bincount(codes, minlength=L)
    pres = np.flatnonzero(n > 0)
    if len(pres) < 2:
        return None, -np.inf
    key = S[pres, 0] / n[pres] if criterion == "mse" else S[pres, 1] / n[pres]
    lv = pres[np.argsort(key, kind="stable")]
    left, nl = np.cumsum(S[lv], 0)[:-1], np.cumsum(n[lv])[:-1]
    tot, m = S[lv].sum(0), n[lv].sum()
    gain = impurity(tot, m, criterion) - (nl * impurity(left, nl, criterion) + (m - nl) * impurity(tot - left, m - nl, criterion)) / m
    gain = np.where((nl >= min_leaf) & (m - nl >= min_leaf), gain, -np.inf)
    i = int(np.argmax(gain))
    mask = np.zeros(L, bool); mask[lv[: i + 1]] = True
    return mask, gain[i]

X, y = make_classification(n_samples=800, n_features=5, n_informative=3, n_redundant=1, flip_y=0.08, random_state=0)
X = X.astype(np.float32).astype(float)          # scikit-learn trabaja en float32: lo imitamos para comparar umbrales
Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.3, random_state=0)
for crit in ["gini", "entropy"]:
    for depth, leaf in [(5, 10), (None, 1)]:
        t0 = time.perf_counter()
        mio = CART(crit, max_depth=depth, min_samples_leaf=leaf).fit(Xtr, ytr)
        dt = time.perf_counter() - t0
        sk = DecisionTreeClassifier(criterion=crit, max_depth=depth, min_samples_leaf=leaf, random_state=0).fit(Xtr, ytr)
        igual = len(mio.feature) == sk.tree_.node_count and np.array_equal(np.where(mio.feature < 0, -2, mio.feature), sk.tree_.feature)
        print(f"{crit:7s} max_depth={str(depth):4s} min_leaf={leaf:2d}: nodos {len(mio.feature):3d} (sklearn {sk.tree_.node_count:3d}), "
              f"misma estructura: {igual!s:5s}, predicciones iguales {np.mean(mio.predict(Xte) == sk.predict(Xte)):.3f}, "
              f"nodos con empate {mio.ties:2d}, acierto {np.mean(mio.predict(Xte) == yte):.3f}")

sk0 = DecisionTreeClassifier(random_state=0).fit(Xtr, ytr)
sk1 = DecisionTreeClassifier(random_state=1).fit(Xtr, ytr)
print(f"sklearn sin límites, random_state 0 frente a 1: predicciones iguales {np.mean(sk0.predict(Xte) == sk1.predict(Xte)):.3f}")

Xr, yr = make_friedman1(n_samples=600, noise=1.0, random_state=0)
Xr = Xr.astype(np.float32).astype(float)
Xrtr, Xrte, yrtr, yrte = train_test_split(Xr, yr, test_size=0.3, random_state=0)
mio = CART("mse", max_depth=6, min_samples_leaf=5).fit(Xrtr, yrtr)
sk = DecisionTreeRegressor(max_depth=6, min_samples_leaf=5, random_state=0).fit(Xrtr, yrtr)
print(f"regresión max_depth=6 min_leaf=5: nodos {len(mio.feature)} (sklearn {sk.tree_.node_count}), "
      f"máx |diferencia de predicción| {np.max(np.abs(mio.predict(Xrte) - sk.predict(Xrte))):.1e}")

With max_depth=5 and min_samples_leaf=10, the from-scratch tree and scikit-learn tree have identical node-by-node structure and predictions on every test, for Gini and entropy; in regression maximum prediction difference is on the order of 10−1510^{-15}, pure rounding. Without limits, small nodes appear where two features tie exactly in gain (e.g. two examples of distinct classes separate equally well on any differing feature). There scikit-learn breaks ties with a random feature permutation depending on random_state, while our tree keeps the first. Evidence is the last line: scikit-learn itself with two different seeds does not predict identically everywhere. Two correct implementations need not yield the same full tree: fix threshold convention (midpoint), numeric type (scikit-learn converts X\mat{X} to float32, motivating the cell’s conversion) and tie-breaking.

[ ]Categorical splits by sortingBrowser
import itertools

def all_partitions(L):
    """Máscaras de las 2^(L-1) - 1 particiones binarias de L niveles (el nivel 0 siempre a la izquierda)."""
    M = np.array([[(m >> l) & 1 for l in range(L)] for m in range(1, 2 ** L - 1, 2)], dtype=float)
    return M

def best_partition(codes, Z, L, criterion):
    """Fuerza bruta vectorizada: la mejor ganancia entre todas las particiones de los niveles."""
    S = np.zeros((L, Z.shape[1])); np.add.at(S, codes, Z)
    n = np.bincount(codes, minlength=L).astype(float)
    M = all_partitions(L)
    left, nl = M @ S, M @ n
    tot, m = S.sum(0), n.sum()
    return np.max(impurity(tot, m, criterion) - (nl * impurity(left, nl, criterion)
                                                 + (m - nl) * impurity(tot - left, m - nl, criterion)) / m)

rng = np.random.default_rng(1)
L = 10
fallos = {"mse": 0, "gini": 0, "entropy": 0}
for _ in range(40):
    codes = rng.permutation(np.arange(300) % L)        # todos los niveles presentes
    efecto = rng.normal(size=L)
    y_reg = efecto[codes] + rng.normal(size=300)
    y_bin = (rng.random(300) < 1 / (1 + np.exp(-2 * efecto[codes]))).astype(int)
    for crit, y in [("mse", y_reg), ("gini", y_bin), ("entropy", y_bin)]:
        Z = suff_stats(y, crit, 2)
        fallos[crit] += int(cat_split(codes, Z, L, crit)[1] < best_partition(codes, Z, L, crit) - 1e-12)
print(f"{L} niveles: {2 ** (L - 1) - 1} particiones, {L - 1} ordenadas. Casos (de 40) en que el corte ordenado no es óptimo: {fallos}")

# con 3 clases ya no basta ordenar: un contraejemplo (recuentos por nivel y clase)
C = np.array([[0, 2, 0], [48, 0, 51], [14, 49, 66], [13, 21, 1], [82, 9, 3], [5, 0, 32], [6, 3, 19]], dtype=float)
codes3 = np.repeat(np.arange(7), C.sum(1).astype(int))
y3 = np.concatenate([np.repeat([0, 1, 2], c.astype(int)) for c in C])
optimo = best_partition(codes3, suff_stats(y3, "gini", 3), 7, "gini")
tot = C.sum(0)
mejor_ordenado = -np.inf
for k in range(3):                                     # ordenar por la proporción de cada una de las tres clases
    lv = np.argsort(C[:, k] / C.sum(1), kind="stable")
    for i in range(1, 7):
        sl = C[lv[:i]].sum(0)
        g = impurity(tot, tot.sum(), "gini") - (sl.sum() * impurity(sl, sl.sum(), "gini")
                                                + (tot - sl).sum() * impurity(tot - sl, (tot - sl).sum(), "gini")) / tot.sum()
        mejor_ordenado = max(mejor_ordenado, g)
print(f"3 clases, 7 niveles: ganancia óptima {optimo:.5f}, mejor corte ordenado por alguna clase {mejor_ordenado:.5f}")

# soporte nativo frente a one-hot y a códigos arbitrarios, con la misma profundidad
efecto20 = np.random.default_rng(99).normal(scale=1.5, size=20)   # efecto fijo de cada uno de los 20 niveles
def datos_cat(n, seed):
    r = np.random.default_rng(seed)
    barrio, x = r.integers(0, 20, size=n), r.uniform(size=n)
    return np.column_stack([barrio, x]), efecto20[barrio] + 2 * (x > 0.5) + r.normal(scale=0.5, size=n)

Xc, yc_tr = datos_cat(400, 1)
Xc_te, yc_te = datos_cat(4000, 2)
onehot = lambda A: np.column_stack([np.eye(20)[A[:, 0].astype(int)], A[:, 1]])
mse = lambda p: np.mean((p - yc_te) ** 2)
for depth in [2, 4, 6]:
    nat = CART("mse", max_depth=depth, min_samples_leaf=5, categorical=[0]).fit(Xc, yc_tr)
    oh = DecisionTreeRegressor(max_depth=depth, min_samples_leaf=5, random_state=0).fit(onehot(Xc), yc_tr)
    cod = DecisionTreeRegressor(max_depth=depth, min_samples_leaf=5, random_state=0).fit(Xc, yc_tr)
    print(f"profundidad {depth}: MSE de prueba  nativo {mse(nat.predict(Xc_te)):.3f}   one-hot {mse(oh.predict(onehot(Xc_te))):.3f}   "
          f"códigos 0..19 {mse(cod.predict(Xc_te)):.3f}")

In 40 random problems with 10 levels, ordered splitting always reaches the optimum among 511 partitions, in regression and binary classification with Gini and entropy, as the theorem says. The three-class counterexample shows more classes need more: the best partition has Gini gain 0.11251 and the best split across the three possible class-proportion orderings gets 0.11225. The difference is small and such cases are rare in random problems, but they exist. In the encoding comparison, native-split trees have lowest test error at all three depths; one-hot and arbitrary codes need greater depth to approach it, because each split separates only one level or a meaningless interval of codes.

[ ]Weakest-link pruningBrowser
def prune_path(tree):
    """Secuencia del eslabón más débil con R(t) = (n_t/n)·impureza(t), como cost_complexity_pruning_path."""
    R = tree.n / tree.n[0] * tree.imp
    parent = np.full(len(R), -1)
    for i in np.flatnonzero(tree.feature >= 0):
        parent[tree.left[i]] = parent[tree.right[i]] = i
    hoja = tree.feature < 0                    # hojas del subárbol actual
    interno = ~hoja                            # nodos internos del subárbol actual
    alphas, Rs, hojas = [0.0], [R[hoja].sum()], [int(hoja.sum())]
    while interno[0]:
        nleaf, Rb = np.zeros(len(R)), np.zeros(len(R))
        for l in np.flatnonzero(hoja):         # cada hoja suma su R y un 1 a todos sus antepasados
            a = parent[l]
            while a >= 0:
                nleaf[a] += 1; Rb[a] += R[l]; a = parent[a]
        g = np.full(len(R), np.inf)
        g[interno] = (R[interno] - Rb[interno]) / (nleaf[interno] - 1)
        t = int(np.argmin(g))                  # el eslabón más débil (el de menor índice si empatan)
        pila = [t]
        while pila:                            # colapsa la rama de t
            u = pila.pop(); interno[u] = hoja[u] = False
            if tree.feature[u] >= 0:
                pila += [tree.left[u], tree.right[u]]
        hoja[t] = True
        alphas.append(g[t]); Rs.append(R[hoja].sum()); hojas.append(int(hoja.sum()))
    return np.array(alphas), np.array(Rs), hojas

mio = CART("gini", max_depth=8).fit(Xtr, ytr)
sk = DecisionTreeClassifier(max_depth=8, random_state=0).fit(Xtr, ytr)
a_mio, R_mio, h_mio = prune_path(mio)
path = sk.cost_complexity_pruning_path(Xtr, ytr)
print(f"subárboles: {len(a_mio)} (sklearn {len(path.ccp_alphas)});  máx |Δα| = {np.max(np.abs(a_mio - path.ccp_alphas)):.1e};  "
      f"máx |ΔR| = {np.max(np.abs(R_mio - path.impurities)):.1e}")
print("hojas:", h_mio)
print("α:", np.round(a_mio, 4).tolist())

The sequence matches cost_complexity_pruning_path up to rounding: the same 41 α\alpha values and risk R(Tk)R(T_k) at each step. Notice the leaf list: early α\alpha values are small and close (branches contributing little are pruned); the last rise quickly as important splits are removed. Some steps remove several leaves at once: the weakest link may be a node with more than two leaves in its branch. scikit-learn collapses one node per iteration even on ties, so it may repeat an α\alpha.

[ ]Missing values: surrogates versus default directionBrowser
def sustituto(izq, x2):
    """Mejor corte de x2 que imita la dirección primaria izq (booleano). Devuelve (t, sentido, acuerdo, λ);
    sentido +1: x2 <= t va a la izquierda."""
    o = np.argsort(x2, kind="stable")
    xs, Ls = x2[o], izq[o].astype(float)
    m, nL = len(xs), Ls.sum()
    cum = np.cumsum(Ls)[:-1]                       # izquierdas primarias entre los i menores de x2
    i = np.arange(1, m)
    acuerdo_le = (cum + (m - i) - (nL - cum)) / m  # x2 <= t → izquierda
    acuerdo = np.where(xs[1:] > xs[:-1], np.maximum(acuerdo_le, 1 - acuerdo_le), -1)
    k = int(np.argmax(acuerdo))
    pmin = min(nL, m - nL) / m
    lam = (pmin - (1 - acuerdo[k])) / pmin         # medida de asociación predictiva de CART
    return xs[k] / 2 + xs[k + 1] / 2, (1 if acuerdo_le[k] >= 0.5 else -1), acuerdo[k], lam

def escenario(nombre, corr, p_falta_y1, p_falta_y0, seed):
    r = np.random.default_rng(seed)
    def datos(n):
        x1 = r.normal(size=n)
        x2 = corr * x1 + np.sqrt(1 - corr ** 2) * r.normal(size=n)
        y = (x1 + 0.3 * r.normal(size=n) > 0).astype(int)
        falta = r.random(n) < np.where(y == 1, p_falta_y1, p_falta_y0)
        return np.column_stack([np.where(falta, np.nan, x1), x2]), y, falta
    Xtr, ytr, ftr = datos(2000)
    Xte, yte, fte = datos(2000)
    obs = ~ftr
    Z = suff_stats(ytr, "gini", 2)
    t, _ = sweep(Xtr[obs, 0], Z[obs], "gini")       # corte primario con los observados
    izq = Xtr[obs, 0] <= t
    clase = {True: np.argmax(Z[obs][izq].sum(0)), False: np.argmax(Z[obs][~izq].sum(0))}
    acierto = lambda lado: np.mean(np.where(lado, clase[True], clase[False]) == yte[fte])
    # 1) sustituto sobre x2
    ts, sentido, acuerdo, lam = sustituto(izq, Xtr[obs, 1])
    lado_s = Xte[fte, 1] <= ts if sentido == 1 else Xte[fte, 1] > ts
    # 2) regla ciega: todos los faltantes al hijo con más ejemplos
    lado_m = np.full(fte.sum(), izq.mean() >= 0.5)
    # 3) dirección por defecto: la que más reduce la impureza con los faltantes de entrenamiento
    def coste(falt_izq):
        L = np.where(ftr, falt_izq, Xtr[:, 0] <= t)
        nl = L.sum()
        return nl * impurity(Z[L].sum(0), nl, "gini") + (len(L) - nl) * impurity(Z[~L].sum(0), len(L) - nl, "gini")
    def_izq = coste(True) < coste(False)
    lado_d = np.full(fte.sum(), def_izq)
    raiz_sk = DecisionTreeClassifier(max_depth=1, random_state=0).fit(Xtr, ytr).tree_.feature[0]
    print(f"{nombre}: faltan {ftr.mean():.0%} de x1. Sustituto en x2: acuerdo {acuerdo:.3f}, λ = {lam:.2f}")
    print(f"   acierto en los ejemplos de prueba sin x1:  sustituto {acierto(lado_s):.3f}   regla ciega {acierto(lado_m):.3f}   "
          f"dirección por defecto ({'izquierda' if def_izq else 'derecha'}) {acierto(lado_d):.3f}")
    print(f"   scikit-learn (dirección por defecto) elige como raíz x{raiz_sk + 1}")

escenario("A. Faltan al azar; x2 correlada con x1", 0.9, 0.3, 0.3, 0)
escenario("B. Faltar depende de y; x2 sin relación", 0.0, 0.5, 0.05, 1)

In scenario A, 31 % of x1x_1 is randomly missing and x2x_2 correlates 0.90.9 with x1x_1. The x2x_2 surrogate matches the primary split 85 % of the time (λ=0.70\lambda = 0.70: removing 70 % of blind-rule error) and correctly classifies 81 % of test examples missing x1x_1. Default direction sends all to the same side and cannot beat the blind rule: 48 %, worse than a coin flip. scikit-learn, evaluating x1x_1 with all missing on one side, directly prefers x2x_2 as root. In scenario B missingness is informative (missing for half of positives and 5 % of negatives) and x2x_2 knows nothing: no useful surrogate (λ=0\lambda = 0), blind rule gets 8 %, while default direction learns to send missing cases positive and gets 92 %. Neither dominates: choose based on why data are missing.

Diagnosis with scikit-learn

Now real data: scikit-learn’s Wisconsin breast-cancer dataset (569 tumors, 30 numerical image-derived features, benign or malignant diagnosis).

[ ]Full tree and a depth-2 treeBrowser
from sklearn.datasets import load_breast_cancer
from sklearn.tree import export_text

data = load_breast_cancer()
X, y, nombres = data.data, data.target, list(data.feature_names)
Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.3, stratify=y, random_state=0)
print(f"entrenamiento {Xtr.shape}, prueba {Xte.shape}; clase 1 = benigno ({y.mean():.1%})")
grande = DecisionTreeClassifier(random_state=0).fit(Xtr, ytr)
print(f"árbol sin límites: {grande.get_n_leaves()} hojas, profundidad {grande.get_depth()}, "
      f"acierto en entrenamiento {grande.score(Xtr, ytr):.3f}, en prueba {grande.score(Xte, yte):.3f}\n")
print(export_text(DecisionTreeClassifier(max_depth=2, random_state=0).fit(Xtr, ytr), feature_names=nombres, decimals=2, show_weights=True))

The unlimited tree has 16 leaves and depth 6, 100 % training accuracy and 90.6 % test accuracy. The depth-2 tree illustrates impurity: the right branch (worst perimeter > 106.10) splits into leaves (19,16)(19, 16) and (120,2)(120, 2) in (malignant, benign) counts, both predicting class 0. That split changes no prediction or training error; Gini chooses it because it separates a nearly pure group of 122 tumors from an ambiguous 35, which a third level could resolve.

[ ]Pruning sequence and cross-validationBrowser
import matplotlib.pyplot as plt
from sklearn.model_selection import StratifiedKFold, cross_val_score

path = grande.cost_complexity_pruning_path(Xtr, ytr)
alphas = path.ccp_alphas[:-1]                           # el último α deja solo la raíz
cv = StratifiedKFold(5, shuffle=True, random_state=0)
media, ee = [], []
for a in alphas:
    s = cross_val_score(DecisionTreeClassifier(ccp_alpha=a, random_state=0), Xtr, ytr, cv=cv)
    media.append(s.mean()); ee.append(s.std(ddof=1) / np.sqrt(len(s)))
media, ee = np.array(media), np.array(ee)
k = int(np.argmax(media))
k1 = int(np.flatnonzero(media >= media[k] - ee[k]).max())   # regla de un error estándar
for nombre, kk in [("máximo de CV", k), ("regla 1-EE  ", k1)]:
    m = DecisionTreeClassifier(ccp_alpha=alphas[kk], random_state=0).fit(Xtr, ytr)
    print(f"{nombre}: α = {alphas[kk]:.4f}, CV {media[kk]:.3f} ± {ee[kk]:.3f}, {m.get_n_leaves()} hojas, prueba {m.score(Xte, yte):.3f}")
arboles = [DecisionTreeClassifier(ccp_alpha=a, random_state=0).fit(Xtr, ytr) for a in alphas]
hojas = [int(t.get_n_leaves()) for t in arboles]
print("α:", np.round(alphas, 4).tolist())
print("hojas:", hojas)

fig, ax = plt.subplots(figsize=(6.4, 3.2))
ax.errorbar(range(len(alphas)), media, yerr=ee, marker="o", capsize=3, label="validación cruzada ± 1 EE")
ax.plot(range(len(alphas)), [t.score(Xtr, ytr) for t in arboles], "--", color="gray", label="entrenamiento")
ax.axvline(k, color="C1", lw=1, label="máximo de CV")
ax.axvline(k1, color="C2", lw=1, ls=":", label="regla 1-EE")
ax.set_xticks(range(len(alphas)), [str(h) for h in hojas])
ax.set_xlabel("hojas del subárbol (α creciente hacia la derecha)"); ax.set_ylabel("acierto"); ax.legend(fontsize=8)
plt.show()

The sequence has 12 subtrees from 16 leaves to root alone; the cell validates the first 11. Cross-validation peaks at 92.5 % with 4 leaves (α=0.0196\alpha = 0.0196), and the one-standard-error rule selects 2 leaves, one split. On test, the 4-leaf tree scores 90.1 %, virtually the same as the full 16-leaf tree (90.6 %): with 171 test cases, standard error at 90 % accuracy is about 2.3 points, so those differences are noise. Pruning gains a model four times smaller at equal accuracy, not accuracy itself. (In a real medical problem accuracy would not suffice: examine malignant sensitivity with the confusion matrix.) On noisier labels, like the pruning figure’s L model, pruning also reduces error.

[ ]Drawing the selected treeBrowser
from sklearn.tree import plot_tree

elegido = arboles[k]
fig, ax = plt.subplots(figsize=(7.5, 4))
plot_tree(elegido, feature_names=nombres, class_names=["maligno", "benigno"], filled=True, impurity=True, fontsize=7, ax=ax)
plt.show()
[ ]How much does the tree change across resamples?Browser
from collections import Counter

rng = np.random.default_rng(0)
B = 100
raices, n_hojas, preds = [], [], []
for b in range(B):
    i = rng.integers(0, len(Xtr), len(Xtr))             # remuestreo bootstrap
    t = DecisionTreeClassifier(random_state=0).fit(Xtr[i], ytr[i])
    raices.append(nombres[t.tree_.feature[0]]); n_hojas.append(int(t.get_n_leaves())); preds.append(t.predict(Xte))
preds = np.array(preds)
for nombre, c in Counter(raices).most_common():
    print(f"raíz = {nombre:22s} en {c:3d} de {B} árboles")
acc = (preds == yte).mean(1)
voto = (preds.mean(0) > 0.5).astype(int)
desacuerdo = np.mean([np.mean(preds[a] != preds[b]) for a in range(B) for b in range(a + 1, B)])
print(f"hojas: de {min(n_hojas)} a {max(n_hojas)}; acierto en prueba de cada árbol: media {acc.mean():.3f}, de {acc.min():.3f} a {acc.max():.3f}")
print(f"dos árboles discrepan de media en el {desacuerdo:.1%} de los casos de prueba; en el "
      f"{np.mean((preds.mean(0) > 0) & (preds.mean(0) < 1)):.1%} de los casos algún árbol discrepa del resto; "
      f"el voto de los {B} acierta {np.mean(voto == yte):.3f}")

Across 100 bootstrap resamples of the same training set, root is worst perimeter in 52 trees, worst concave points in 31, and three other features in the rest. Leaf count ranges from 6 to 18 and individual test accuracy 88.3–94.7 %. Any two trees disagree on 7.8 % of test cases on average, and on 34.5 % at least one tree differs from the others. The 100-tree vote scores 91.8 %, slightly above average tree 91.6 %: the gain is small because trees agree strongly on correct cases; the next lesson’s random forest deliberately decorrelates them so averaging helps more.

Typical mistakes

Exercises

NumericGini reduction of a split
A node with 40 positives and 60 negatives splits into a child with (30,10)(30, 10) (positive, negative) and another with (10,50)(10, 50). Compute Gini reduction ΔG=G(t)−nLnG(tL)−nRnG(tR)\Delta G = G(t) - \tfrac{n_L}{n}G(t_L) - \tfrac{n_R}{n}G(t_R).
NumericThe same split in bits
For the preceding split (parent (40,60)(40, 60), children (30,10)(30, 10) and (10,50)(10, 50)), compute information gain in bits, H(t)−nLnH(tL)−nRnH(tR)H(t) - \tfrac{n_L}{n}H(t_L) - \tfrac{n_R}{n}H(t_R).
QuizIs scaling needed?
You train a decision tree on features with very different scales (income in euros, age in years). Must they be standardized?
QuizTwo splits with the same error
A node has 400 examples of each class. Split A gives children (300,100)(300, 100) and (100,300)(100, 300); B gives (200,400)(200, 400) and (200,0)(200, 0). Which statements are true?

More than one answer may be correct.

QuizHow much does growing the tree cost?
You build a balanced tree of depth log⁡2n\log_2 n on nn examples and dd features, re-sorting every feature at every node and finding splits by sweep. What is total cost?
NumericThe weakest link
In a tree trained on n=200n = 200 examples, internal node tt has 50 examples, (30,20)(30, 20) by class. Its branch has three leaves: (25,5)(25, 5), (5,10)(5, 10) and (0,5)(0, 5). With R(t)=ntnG(t)R(t) = \tfrac{n_t}{n}G(t), from what value of α\alpha should the branch of tt collapse to one leaf?
QuizSurrogate or default direction?
In a fraud problem, ‘account age’ is missing mostly on recently created fraudulent accounts and no other feature resembles it. The tree splits on it at the root. Which missing-value treatment works best?
QuizTwo trees, two stories
You fit a tree and the root splits on ‘income’. A colleague fits the same algorithm on the same data minus 20 rows and its root splits on ‘wealth’, with equal validation accuracy. What is most reasonable?
ProofWhat Gini is and why it is strictly concave
Prove: Let p=(p1,…,pK)\vb{p} = (p_1, \dots, p_K) be the class-proportion vector of a node and G(p)=∑kpk(1−pk)G(\vb{p}) = \sum_k p_k(1 - p_k). Then (a) G(p)G(\vb{p}) is the error probability of a classifier randomly labeling each node example with probabilities p\vb{p}, and (b) GG is strictly concave on the simplex.
0
Take a random node example with class YY (P(Y=k)=pk\Pr(Y = k) = p_k), and a label Y^\hat Y independently drawn with the same probabilities, independent of YY.

Step 1 of 4. What is P(Y^≠Y)\Pr(\hat Y \neq Y)?

ProofAn optimal categorical split respects mean order
Prove: In squared-loss regression, let xx be a categorical feature whose levels ℓ=1,…,L\ell = 1, \dots, L have nℓn_\ell examples and response mean mℓm_\ell. There exists an optimal binary split of xx among the L−1L - 1 splits separating levels sorted by mℓm_\ell.
0
For a level group AA with mean yˉA\bar y_A, its sum of squares is ∑ℓ∈A[Vℓ+nℓ(mℓ−yˉA)2]\sum_{\ell \in A}\big[V_\ell + n_\ell(m_\ell - \bar y_A)^2\big], where VℓV_\ell is the sum of squares within level ℓ\ell around its mean. Let (A,B)(A, B) be an optimal split (minimum total sum of squares), with means a=yˉAa = \bar y_A and b=yˉBb = \bar y_B.

Step 1 of 3. What part of total sum of squares depends on the partition?

Summary

Key idea
A decision tree partitions space into rectangles with questions xj≤tx_j \le t chosen greedily to maximize reduction of a strictly concave impurity; a sorted sweep evaluates all feature splits in O(nlog⁡n)\bigO(n\log n), cost-complexity pruning traverses a finite nested subtree sequence, and instability, its major defect, is what bagging and boosting exploit.
  • A tree partitions space into axis-aligned rectangles with a constant per leaf: mean in regression, majority class or proportions in classification. It depends only on value order per feature.
  • Each impurity is best-constant risk for a loss: error (0–1), Gini (Brier), entropy (log), variance (squared). Gini and entropy are strictly concave and give positive gain when children differ; piecewise-linear error misses splits preparing better ones.
  • The sweep sorts once and accumulates sufficient statistics; regression gain is nLnRn(yˉL−yˉR)2\tfrac{n_Ln_R}{n}(\bar y_L - \bar y_R)^2. Optimal tree search is NP-complete and CART is greedy, failing in cases such as exclusive-or.
  • A categorical with LL levels has 2L−1−12^{L-1} - 1 splits, but regression and binary classification need only the L−1L - 1 respecting mean order. One-hot fragments splits; native support preserves them.
  • Cost-complexity pruning R(T)+α∣T~∣R(T) + \alpha|\tilde T| yields a nested subtree sequence by weakest link; α\alpha is cross-validated.
  • Missing values use surrogates (feature correlations) or default direction (missingness information).
  • Trees are unstable: small perturbations change the root and whole structure. Do not interpret one tree alone; average them.