CART: grow a tree, then price its leaves
CART 与树的剪枝
Grow an exact regression tree, derive its cost-complexity pruning path and separate fixed-tree optimality from validation selection.
cartEight readings, or two operating regimes?
A hypothetical workshop records a machine’s load index and its cooling time. At load indices zero through seven, the times are 1, 2, 1, 2, 8, 9, 8, 9. A tree can memorize all eight readings. Another tree asks one question: is the load at most 3.5? It predicts 1.5 on one side and 8.5 on the other. The larger tree fits the observations perfectly; the smaller one describes two operating regimes. The data alone do not tell us which will predict the next measurement better.
Decision trees introduced a single split. Here we grow a complete small regression tree and then compute which branches survive as we charge more for each leaf. CART means Classification and Regression Trees; its binary partitions support either kind of target. This chapter’s executable model uses one numerical feature and squared-error regression. Classification losses are compared mathematically, without presenting the program as a classifier. The official tree guide, sections 1.10.6–1.10.7 distinguishes the tasks and their criteria.
Fix the loss before charging for a leaf
For a numerical feature, a split asks versus . Between adjacent distinct training values, all thresholds induce the same training partition; their predictions between observations can differ. Our convention uses the exact midpoint. Repeated feature values stay together. Each child must have at least min_leaf observations.
In a regression leaf containing observation indices , the mean minimizes squared error:
The second term explains the optimum: moving the constant prediction away from the mean can only increase loss. Greedy growth selects the admissible split with the lowest sum of child squared errors, then recurses. It compares immediate children, not every possible future partition. Our code requires a strictly positive improvement and breaks ties by the smaller threshold. Shalizi’s CMU lecture, section 2.2, printed pages 12–13, describes squared-error growth and the danger of stopping before useful later splits.
For classification, let be the class proportions in a leaf. The majority class minimizes zero-one loss; Gini impurity measures a different quantity:
Gini also equals the average summed squared error between a one-hot class label and the probability vector . Thus proportions give Gini but majority-class error . A split criterion, a pruning loss and a reporting metric must be named separately. Original cost-complexity formulations can use misclassification risk; scikit-learn’s implementation uses sample-weighted leaf impurity. Changing that definition changes the numerical penalty path. This distinction is explicit in section 1.10.9 of the official guide.
For our regression tree, let be the original training size, the error contribution if node becomes one leaf, and the leaves retained in a pruned tree. Every contribution keeps the same denominator:
This is training MSE plus a charge per leaf. It is not the unweighted average of leaf MSEs. The permitted candidates are rooted prunings of one already-grown tree: replace a whole branch with its root leaf, retaining that node’s training mean. Pruning cannot invent a new threshold or move samples between branches. With this normalization, has units of squared target value. Multiplying all targets by three multiplies every breakpoint by nine; using total SSE instead would multiply breakpoints by .
Let be a branch of the current tree, with leaves and retained-leaf risk . Collapsing it saves leaf charges. The tie occurs at:
The weakest-link algorithm repeatedly finds the smallest , collapses all tied branches and recomputes the ratios. If tied nodes are ancestors and descendants, collapsing the ancestor already removes the descendant. The denominator counts leaves removed, not nodes, depth or observations. This is the pruning operation described in the official guide; the implementation below uses exact fractions to expose equality rather than a floating-point tolerance.
Why does this find an optimal pruning rather than merely another heuristic? Any pruning of the current tree can be described by disjoint collapsed branches. Its objective change is the sum of over those branches. Until the smallest ratio is reached, every such change is nonnegative. At equality, tied collapses preserve the optimum. A branch already collapsed at an optimum cannot become preferable again as increases: each alternative expansion has more leaves and therefore a steeper objective line. Repeating the argument gives a nested optimal path. At a breakpoint we choose the smallest optimal tree, removing all ties; other optimal trees can also exist at that exact value.
A second way to state the fixed-tree optimization is a bottom-up recurrence. If is the best objective within the original branch rooted at , then for an internal node:
At an original leaf only the first option exists. Every valid pruning either collapses the root or keeps both children, so induction proves this recurrence. It establishes the scope of optimality: all prunings of the supplied tree, not all binary trees that could have been grown from the data.
An exact growth and pruning path
This complete standard-library program accepts nonempty lists or tuples of pairs (x, y), using integers or Fraction values. Booleans, floats and malformed rows are rejected. min_leaf is a positive integer; even if it exceeds the sample size, the root remains a valid unsplit tree. Both children of any executed split satisfy the minimum. The tree helpers accept the immutable Node objects returned by grow; path helpers expect a nonempty path returned by pruning_path. They are not validators for arbitrary externally constructed node graphs.
from collections import namedtuple
from fractions import Fraction as F
Node = namedtuple('Node', 'threshold mean risk left right')
def rational(value):
if type(value) is int or isinstance(value, F):
return F(value)
raise ValueError('use integers or Fraction values, not bool or float')
def observations(rows):
if not isinstance(rows, (list, tuple)) or not rows:
raise ValueError('a nonempty list or tuple of (x, y) pairs is required')
result = []
for row in rows:
if not isinstance(row, (list, tuple)) or len(row) != 2:
raise ValueError('each row must be an (x, y) pair')
result.append(tuple(rational(value) for value in row))
return tuple(result)
def grow(rows, min_leaf=1):
data = observations(rows)
if type(min_leaf) is not int or min_leaf < 1:
raise ValueError('min_leaf must be a positive integer')
n = len(data)
def leaf(part):
mean = sum((y for x, y in part), F()) / len(part)
risk = sum(((y - mean)**2 for x, y in part), F()) / n
return Node(None, mean, risk, None, None)
def build(part):
node = leaf(part)
values = sorted(set(x for x, y in part))
best, best_risk = None, node.risk
for low, high in zip(values, values[1:]):
threshold = (low + high) / 2
left = tuple(row for row in part if row[0] <= threshold)
right = tuple(row for row in part if row[0] > threshold)
if min(len(left), len(right)) < min_leaf:
continue
risk = leaf(left).risk + leaf(right).risk
if risk < best_risk:
best, best_risk = (threshold, left, right), risk
if best is None:
return node
threshold, left, right = best
return node._replace(threshold=threshold,
left=build(left), right=build(right))
return build(data)
def statistics(tree):
if tree.threshold is None:
return tree.risk, 1
left_risk, left_size = statistics(tree.left)
right_risk, right_size = statistics(tree.right)
return left_risk + right_risk, left_size + right_size
def pruning_path(tree):
# Node objects must come from grow; all risks keep its original denominator.
path = [(F(), tree)]
while tree.threshold is not None:
candidates = []
def collect(node):
if node.threshold is None:
return node.risk, 1
a, k = collect(node.left)
b, j = collect(node.right)
candidates.append((id(node), (node.risk - a - b) / (k + j - 1)))
return a + b, k + j
collect(tree)
alpha = min(value for key, value in candidates)
weakest = {key for key, value in candidates if value == alpha}
def cut(node):
if id(node) in weakest:
return node._replace(threshold=None, left=None, right=None)
if node.threshold is None:
return node
return node._replace(left=cut(node.left), right=cut(node.right))
tree = cut(tree)
# Equal breakpoints designate the most-pruned optimal tree.
if path[-1][0] == alpha:
path[-1] = (alpha, tree)
else:
path.append((alpha, tree))
return tuple(path)
def at_alpha(path, alpha):
alpha = rational(alpha)
if alpha < 0:
raise ValueError('alpha must be nonnegative')
chosen = path[0][1]
for breakpoint, tree in path:
if breakpoint > alpha:
break
chosen = tree
return chosen
def predict(tree, x):
x = rational(x)
while tree.threshold is not None:
tree = tree.left if x <= tree.threshold else tree.right
return tree.mean
def select(path, validation):
# path must be the nonempty output of pruning_path.
data = observations(validation)
scores = tuple(sum(((predict(tree, x) - y)**2 for x, y in data), F())
/ len(data) for alpha, tree in path)
index = min(range(len(path)),
key=lambda i: (scores[i], statistics(path[i][1])[1], i))
return {'index': index, 'alpha': path[index][0], 'tree': path[index][1],
'validation_mse': scores}
if __name__ == '__main__':
train = tuple(zip(range(8), (1, 2, 1, 2, 8, 9, 8, 9)))
validation = tuple((x, F(3, 2) if x < 4 else F(17, 2)) for x in range(8))
tree = grow(train)
path = pruning_path(tree)
chosen = select(path, validation)
print('root threshold:', tree.threshold)
for alpha, candidate in path:
risk, leaves = statistics(candidate)
print('alpha:', alpha, 'leaves:', leaves, 'training MSE:', risk)
print('validation MSE:', tuple(str(x) for x in chosen['validation_mse']))
print('selected alpha:', chosen['alpha'])
print('predictions:', tuple(str(predict(chosen['tree'], x)) for x in (0, 3, 4, 7)))
Running it prints:
root threshold: 7/2
alpha: 0 leaves: 8 training MSE: 0
alpha: 1/24 leaves: 2 training MSE: 1/4
alpha: 49/4 leaves: 1 training MSE: 25/2
validation MSE: ('1/4', '0', '49/4')
selected alpha: 1/24
predictions: ('3/2', '3/2', '17/2', '17/2')
The small fractions matter. The full tree has eight leaves and zero training loss. Both four-observation branches have risk if collapsed, so their ratio is . Some descendants tie this value too. Cutting all ties produces the two-leaf tree directly, with training MSE . The next collapse costs and removes one leaf. There is no obligatory candidate with every intermediate leaf count.
| Lower endpoint of the penalty interval | Leaves | Training MSE | Validation MSE |
|---|---|---|---|
| 0 | 8 | 0 | 1/4 |
| 1/24 | 2 | 1/4 | 0 |
| 49/4 | 1 | 25/2 | 49/4 |
Each row applies up to, but excluding, the next endpoint; the last continues indefinitely. The validation values are deliberately constructed new responses, 1.5 at the first four inputs and 8.5 at the last four. They make the computation inspectable, not an estimate of performance in a real workshop. select chooses the lowest validation MSE, then fewer leaves on a tie. It returns the corresponding lower endpoint as one representative . Validation does not recompute thresholds, node means or training breakpoints. Replacing validation responses can change the chosen row while leaving the path intact.
For production model selection, keep a final test set untouched. With cross-validation, rebuild growth and pruning inside each training fold; a validation observation must not help grow the tree it evaluates. Choose the tuning procedure on development data, refit as specified by that procedure, and evaluate once on the final test data. A validation-selected score can itself be optimistic after repeated comparisons; see overfitting.
This deliberately simple growth code rescans each candidate split. At a node with observations it uses arithmetic operations, including a dominated sort. Across an unbalanced tree it takes operations and at most temporary observation references held by recursive frames. These are conservative bounds, not library performance claims. If the grown tree has nodes, the pruning path uses operations and at most node/reference storage for all immutable snapshots. Each pass is linear and removes at least one internal node.
Prediction takes comparisons for depth , with constant auxiliary stack space. For path members and validation observations, selection takes operations and extra storage. Exact rational arithmetic is not constant-time in bit length; large numerators and denominators add cost. Recursive growth and pruning can also hit Python’s recursion limit. The program is intended for small teaching data, without a claim to handle arbitrarily large trees.
A perfectly pruned tree can still start from a poor split
Take inputs zero through four and targets 0, 0, 1, 3, 0. Greedy growth first splits at 1.5. Among all three-leaf prunings of that tree, the best training MSE is . A different tree groups the first three observations, then isolates each of the last two. Its predictions are , 3 and 0, giving MSE . That partition requires different earlier splits. No amount of pruning the greedy tree can recover it. The tests enumerate both candidates explicitly.
Pruning can trade fit for size within its candidate family; it does not prove that smaller trees generalize better on every dataset. Pre-pruning with min_leaf changes the original family as well. It cannot be undone by selecting a smaller . Our strict-improvement stopping rule is another explicit restriction; methods that permit zero-gain splits may reach different trees.
Numerical thresholds are one CART split form. Categorical subset splits, sample weights, missing-value handling, multifeature search and classification training require additional implementation choices. This program implements none of them. Predictions remain piecewise constant outside the observed feature range too: crossing no further threshold does not justify extrapolating a trend. A split on machine load is an association in the observations, not a causal intervention on the equipment.
Check the charge, then check the candidate family
- A branch has four leaves, retained risk zero and collapsed risk . At what penalty does collapse tie? What goes wrong if the denominator is four? Answer: . Four counts all existing leaves; collapse saves only three. Dividing by four incorrectly gives and prunes too early.
- In the workshop example, choose the tree at and at . Why is a six-leaf tree absent? Answer: both penalties choose the two-leaf tree. At the first breakpoint all tied weakest branches collapse, including both four-observation branches. Intermediate tied optima need not appear when the convention retains the smallest optimal tree.
- Multiply every training and validation target by three. What changes in the path and the choice? Answer: thresholds and leaf counts remain the same, predictions triple, and both MSEs and breakpoints multiply by nine. The breakpoints become 0, , . Validation still chooses the two-leaf member.
- For targets 0, 0, 1, 3, 0, compare the best three-leaf pruning with the alternative partition described above. Does this refute the optimal-pruning result? Answer: the errors are and . It refutes a claim of globally optimal tree growth. It does not refute optimal pruning: the second partition is outside the first tree’s pruning family.
What to compare next
The 1984 book Classification and Regression Trees by Breiman, Friedman, Olshen and Stone is the historical reference listed in the official guide. The guide provides explicit loss and pruning definitions. Shalizi’s university lecture also discusses validation-based pruning; that should not be confused with our training-derived weakest-link path followed by validation selection.
Compare the category-based information criteria in ID3 and C4.5 topic. To investigate why averaging or sequential fitting changes the behavior of a single tree, continue to random forests and gradient boosting topics. A useful reproduction task is to compare the exact breakpoints here with a library using the same squared-error normalization, then deliberately change the loss or minimum leaf size and explain the changed path.
Make a prediction, then check
A branch has four leaves, retained risk zero and collapsed risk 1/8. What is its effective alpha?
Learning objectives
- Distinguish binary split criteria, classification leaf errors and globally normalized regression risk.
- Derive effective alpha and audit a nested pruning path, including simultaneous ties and endpoint conventions.
- Separate optimal pruning of a fixed tree from greedy growth and validation-based model selection.
Prerequisites & connections
Explore related knowledge →References
- Decision Trees
scikit-learn developers - Classification and Regression Trees — 36-350 Data Mining, Lecture 22
Cosma Shalizi · 2009
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.
- Nine tests passed. For 52 small fitted models (26 datasets at min_leaf 1 and 2), independently enumerated every rooted pruning, recomputed losses from routed observations, and compared path choices at every nonnegative objective-line intersection, between adjacent intersections and beyond the last. No weakest-link ratios used by the oracle.
- Checked the 8→2→1 example with breakpoints 0, 1/24, 49/4; sibling/ancestor ties, exact endpoints, immutable snapshots, duplicate features, minimum size, target scaling, validation ties and malformed inputs. All three-leaf consecutive partitions expose greedy risk 2/5 versus alternative 2/15. Classification zero-one and probability-vector squared losses were separately recalculated.
- Read the published decision-trees article first to avoid duplicating its classification stump. Complete original bilingual prose, identical Python and seven stdout lines, five displays, six anchors, four answered exercises and one table per language. Strict MDX/KaTeX and actual React HTML passed; all 60 mathematical annotations match. Humanizer reread. AI author checks only; review remains written pending independent review. No repository edits or whole-site build.
- Ran all nine author tests. Independently computed minimum risk at each exact retained-leaf count via child-budget convolution, with node risks recomputed as pairwise target dispersion divided by local size times the fixed original n. Sixteen small fitted models produced 98 DP entries; objective envelopes at 100 nonnegative intersections, interval interiors and beyond the last matched both path optimality and smallest-leaf tie policy. This avoids full-subtree enumeration and weakest-link ratios.
- Independently checked 21 internal greedy choices by weighted squared differences between child means. Reviewed fixed global risk normalization, positive-growth restriction, immutable snapshots, ancestor/descendant simultaneous cuts, exact endpoint convention and nondecreasing pruning penalties. The nested-optimality argument and bottom-up proof are scoped to rooted prunings of the fixed grown tree; the alternative three-region partition is explicitly outside that family.
- For two targeted validation datasets, replaced grow/pruning_path with failure stubs during select and independently scored explicit leaf intervals. Validation losses and tie behavior matched without modifying training path or node means. Reviewed input exclusions, helper preconditions, recursion/bit-cost limits and the conservative full-growth/pruning/selection storage bounds.
- Read both full articles, formulas, exercises and metadata. Strict MDX/KaTeX and actual React HTML passed: each language has five displays, six anchors, four answers and one table; all 60 math annotations match. Identical code/stdout checked by author tests. All final five hashes match the frozen manifest and peer source IDs/URLs match metadata.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- Decision Trees · Actually opened https://scikit-learn.org/1.7/modules/tree.html (rendered version 1.7.2): sections 1.10.6–1.10.7, lines 244–303, binary partitions, class proportions, Gini and regression means; section 1.10.9, lines 366–382, weighted leaf impurity versus traditional misclassification risk, R_alpha, effective alpha and the 1984 book reference. Source formula |T| is interpreted as the branch leaf count. The original book itself was not read or claimed as independently verified.
- Classification and Regression Trees — 36-350 Data Mining, Lecture 22 · Actually opened the 25-page PDF: header lines 0–18 identifies title, course and 6 November 2009; printed 12–14 (PDF indices 11–13), lines 280–412, squared-error decomposition, greedy growth, minimum-size/early-stop limits and validation-based pruning. Also opened https://www.stat.cmu.edu/~cshalizi/350/ to verify Fall 2009 and lecture 22 listing. Read extracted text, not a visual audit of all pages; no source code, figures or data reused.
- Decision Trees · Actually opened the fixed https://scikit-learn.org/1.7/modules/tree.html page, rendered 1.7.2. Read §§1.10.6–1.10.7 (lines 244–303): binary partition, task-specific loss, Gini proportions and regression means; §1.10.9 (366–382): sample-weighted impurity versus traditional misclassification risk, terminal-node penalty, effective alpha and 1984 book reference. Reused metadata source ID and stable URL; actual read version is stated here. No original-book reading or scikit-learn execution claimed.
- Classification and Regression Trees — 36-350 Data Mining, Lecture 22 · Actually opened the 25-page university PDF. Header identifies 36-350 Data Mining, 6 November 2009. Read printed pp. 12–14 (lines 280–412): greedy squared-error growth, means, early stopping and validation-based pruning. The article correctly distinguishes that validation procedure from training-derived cost-complexity pruning. Text extraction, not a visual audit or source-code reproduction.
Related topics