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 , k-nearest neighbors measure and SVM uses inner products. Three consequences have already cost you: features must be standardized, interactions (, a polynomial basis) built by hand, and categorical features encoded as numbers.
A decision tree does something else: it asks. “Is ?” 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 may differ on each side of . A linear model needs the term supplied; the tree discovers it.
- Invariance to monotone transformations. A question depends only on the order of values. Replace by or its rank and the tree makes exactly the same data partitions. No scaling is needed, and an outlier in 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 is the intersection of half-spaces or : a rectangle (product of intervals, some unbounded). The leaf rectangles are disjoint and cover : 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 and , 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 . The best value minimizes mean loss of leaf examples, familiar from loss functions:
- with squared loss, the leaf response mean ;
- with 0–1 loss, the leaf majority class;
- with logistic or Brier loss, class-proportion vector (so a classification tree gives probabilities: leaf frequencies).
Learning a tree therefore means choosing a partition. Empirical tree risk with optimal constants is , where is the example count in leaf and measures how poorly its best constant performs. That number is leaf impurity and decides where to split.
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 points at a node there are at most 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 be a node with examples and class proportions , .
Gain is measured within the node. Reduction in total tree impurity when splitting is : 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 .
- Gini and squared loss on one-hot. Predicting vector for every node example gives mean Brier loss , minimized at with value : total variance of the one-hot vector. With two classes 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 . The first lab cell checks it.
- Entropy and log loss. Mean log loss of predicting is , minimized at (Gibbs inequality) with value . Entropy gain is then in the node, with 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: with , . Gain is then the difference between a function at an average and the average of the function, Jensen’s inequality territory.
Proof
By concavity , which is . If is strictly concave and , with the inequality is strict. If , also and all three terms agree.
∎Gini is strictly concave (you will prove it in an exercise), as is entropy. Error is not: 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
and , so .
∎Example: a node with 70 positives and 30 negatives splits into and . Both children remain majority positive, so error does not move: before and after. But the left child is nearly pure (89 % positive), and the nearly balanced right child can profitably split again. Gini gives gain and entropy 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 and , B with and . Both leave 25 % error but B makes one child pure. Gini prefers B ( versus ), as does entropy ( versus bits). A pure child is a finished leaf; one at 75 % still needs work.
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 examples and features, how many splits must be examined? For feature , split depends only on which examples lie on each side, changing only when crosses an observed value. Sort distinct values of at the node; the distinct splits are separating from . Representing them needs a convention: scikit-learn uses midpoint , other implementations itself. Training data are unaffected, but a new point between and is not.
Evaluating each threshold separately costs (count each side) and there are : per feature. The observation reducing this to is that impurities depend on a few sufficient statistics per side, updated in when an example crosses the threshold:
- in classification, class counts ; right-side counts are node totals minus left;
- in regression, with and .
In regression gain is computed without revisiting data. For a node , so the sum-of-squares reduction is:
Dividing by gives variance gain 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: .
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 . Nodes at one depth partition the examples, so processing a whole level costs . Total depends on tree shape:
- Balanced, depth : . This is divide-and-conquer recurrence .
- Degenerate, if each split separates one example: depth and .
- With presorting: sort each feature once at the root and pass each child its already sorted list (stable partition costs ); each level costs and the balanced tree . 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.
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 with x <= t on the left, and its gain. If all x values are equal, return (None, None). It must cost : a test runs it with .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, NoneGreedy, 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 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 , gain ). But split , useless alone, enables two 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 levels (neighborhood, brand, postal code) has no order. A binary split sends a subset left, and there are nontrivial partitions: 511 for 10 levels and over half a million for 20. Trying all quickly becomes infeasible as grows. For the two most important cases it is unnecessary.
This categorical split result reduces search from exponential to linear (plus sorting 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 , 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.
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 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 versus the rest.” Separating a group of levels from the rest costs chained splits, each on a node with less data; many levels dilute signal among nearly empty columns.
- Arbitrary integer codes (): 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
HistGradientBoostingClassifieralso 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 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 , then remove branches while considering the whole tree. This is CART’s proposal, most studied as cost-complexity pruning. A pruned subtree is obtained by collapsing internal nodes of into leaves (retaining the root). Write for its leaf set and for its risk, with . CART used classification error for ; scikit-learn uses the same impurity as growth (Gini or entropy).
is the price of a leaf: with the full tree wins and large leaves only the root. This seems to require a different optimization for each , but no:
Proof
Since is a sum over leaves, the best pruned subtree hanging from node is computed bottom-up. Let be its cost: at a leaf of , ; at an internal node , and to keep the smallest collapse on a tie. Each is the minimum of finitely many lines in (one per branch subtree), with slope equal to its leaf count.
Let 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 . So is continuous and strictly increasing: the set of for which collapses () is an interval . Once collapsed, a node stays collapsed for every larger , so are nested and change only at finitely many values. Near an , the branch of in is fixed and , vanishing at : the first node collapsing as increases minimizes .
∎The weakest link has a direct interpretation: is branch risk improvement over collapsing it, and is the leaves it costs. 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 .
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 by cross-validation. Breiman et al.’s original procedure: compute sequence on all data; in each fold grow a tree on its training data, prune at representative values (geometric mean of each interval) and measure held-out error. Fold means yield a validation curve versus ; they also proposed the one-standard-error rule: the largest (smallest tree) whose validation error is within one standard error of the minimum. In scikit-learn use cost_complexity_pruning_path for and cross-validate ccp_alpha, as in the lab.
Missing values
If an example lacks and the node asks about , 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 using examples with observed. Then for each other feature find split that best imitates : maximizes fraction of examples (with both features observed) sent to the same side. Since blind “send all to larger child” already gets fraction right, CART measures surrogate quality by predictive association
the fraction of blind-rule error eliminated by the surrogate. Store surrogates with in order. At prediction, if 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 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 is missing but imitates it well, the example usually goes where it would have. Default direction uses information in missingness itself: if 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 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.
The figure shows three things. Root jumps from to 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 in 9 and 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.
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 ). 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 .
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 at is infinite and has slope 1, so entropy penalizes small contamination of a nearly pure node more than Gini.
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 , 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 to float32, motivating the cell’s conversion) and tie-breaking.
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.
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 values and risk at each step. Notice the leaf list: early 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 .
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 is randomly missing and correlates with . The surrogate matches the primary split 85 % of the time (: removing 70 % of blind-rule error) and correctly classifies 81 % of test examples missing . Default direction sends all to the same side and cannot beat the blind rule: 48 %, worse than a coin flip. scikit-learn, evaluating with all missing on one side, directly prefers as root. In scenario B missingness is informative (missing for half of positives and 5 % of negatives) and knows nothing: no useful surrogate (), 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).
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 and 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.
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 (), 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.
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()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
More than one answer may be correct.
Step 1 of 4. What is ?
Step 1 of 3. What part of total sum of squares depends on the partition?
Summary
- 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 . Optimal tree search is NP-complete and CART is greedy, failing in cases such as exclusive-or.
- A categorical with levels has splits, but regression and binary classification need only the respecting mean order. One-hot fragments splits; native support preserves them.
- Cost-complexity pruning yields a nested subtree sequence by weakest link; 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.