Decision trees
决策树
Partition data through feature questions and understand impurity, greedy splits, pruning, and generalization.
decision-treesIntuition: turn prediction into a sequence of questions
To predict whether equipment needs maintenance, a tree might first ask whether vibration exceeds a threshold, then whether operating time exceeds another threshold. The final leaf stores a class distribution or a numeric prediction. Training chooses these questions from data rather than requiring a person to write every rule.
A binary split on a continuous feature often takes the form . Recursively partitioning regions produces a piecewise prediction function. A small tree can be read directly, but a very deep tree is not necessarily easy to understand as a whole. See the scikit-learn tree guide and CS229 decision-tree notes, Sections 1.1–1.4 for the broader methods.
Choosing a split
If class has proportion in a node, Gini impurity is . A pure node has impurity zero; a balanced binary node has impurity 0.5. Entropy, , is another option, with by convention.
For a parent containing samples and children containing , the gain is:
Weighting by sample count is essential. Averaging child impurities without these weights overemphasizes tiny children. Training considers candidate features and thresholds, chooses the best immediate gain, and recurses. This is greedy search: the best local split need not yield the globally best tree at a given complexity.
A regression tree can instead optimize squared-error reduction and predict the training mean in a leaf. Classification and regression share partitioning, but their objectives and leaf outputs differ. Sorting one continuous feature and scanning thresholds makes split evaluation efficient; total training cost also depends on depth, feature count, and implementation.
Enumerating one-dimensional thresholds
This complete example fits a one-level decision stump. It demonstrates the split criterion, not a full recursive tree.
from collections import Counter
import math
def gini(labels):
if not labels:
return 0.0
n = len(labels)
return 1-sum((count/n)**2 for count in Counter(labels).values())
def best_split(xs, ys):
if not xs or len(xs) != len(ys) or any(not math.isfinite(x) for x in xs):
raise ValueError("nonempty matching arrays with finite features required")
values = sorted(set(xs))
result, parent = None, gini(ys)
for low,high in zip(values,values[1:]):
threshold = low/2+high/2
if not low <= threshold < high:
threshold = low
left = [y for x,y in zip(xs,ys) if x <= threshold]
right = [y for x,y in zip(xs,ys) if x > threshold]
weighted = (len(left)*gini(left)+len(right)*gini(right))/len(ys)
gain = parent-weighted
if result is None or gain > result[1]:
result = threshold,gain
return result
assert best_split([0,1,2,3],[0,0,1,1]) == (1.5,0.5)
assert best_split([1,1,1],[0,1,0]) is None
assert best_split([0,1,2],[0,0,0]) == (0.5,0.0)
assert best_split([1.0,math.nextafter(1.0,math.inf)],[0,1])[1] == 0.5
assert gini(['a','b','c','d']) == 0.75
for xs,ys in [([],[]),([1],[0,1]),([float('nan')],[0])]:
try:
best_split(xs,ys)
except ValueError:
pass
else:
raise AssertionError("invalid data accepted")
The code checks nonempty equal-length data and finite numeric features; labels must be hashable. It returns None when no distinct feature values permit a split. Equal gains keep the first threshold, and a zero-gain split is returned for inspection rather than automatically used to grow a tree. Adjacent floating-point values may lack a representable midpoint; choosing the lower value preserves the intended partition.
With n examples and at most n−1 thresholds, this direct scanning implementation takes O(n²) expected time and O(n) extra space. Counter computes class frequencies once per impurity calculation. Production implementations can reuse sorted orders and update counts incrementally. Sample weights, missing-value behavior, categorical encoding, and pruning require separate choices.
Why trees overfit
Repeated splitting can isolate tiny groups or individual noisy samples, producing low training error and poor test performance. Maximum depth, minimum leaf size, minimum gain, and cost-complexity pruning constrain complexity. Choose them with validation data or cross-validation, not repeated inspection of the test set.
Trees can also be sensitive to small data changes. Choices between correlated features may be unstable. Impurity-based importance can favor features offering more candidate splits. A readable tree diagram does not establish causal meaning.
Experiments and exercises
- What is the impurity of labels 0, 0, 1, 1? Answer: 0.5.
- What is the gain from splitting these perfectly into pure children? Answer: 0.5.
- Must the best threshold remain unchanged after flipping one label? Answer: no; this illustrates the sensitivity of a single tree.
- A parent has labels [0,0,0,1,1], split into [0] and [0,0,1,1]. Compare gains. Answer: parent Gini is 0.48. Weighted child impurity is 0.4, giving gain 0.08; unweighted child impurity is 0.25, misleadingly giving 0.23.
Research connections
Random forests combine randomization and averaging to reduce variance. Gradient boosting adds models that address remaining prediction errors. Understand the single tree’s objective and generalization limits first. When ensembling improves accuracy, reconsider interpretability, latency, and maintenance cost as well.
Make a prediction, then check
How should child impurities be combined?
Learning objectives
- Calculate weighted impurity for a split using child-node sample counts.
- Explain how tree depth, overfitting, and evaluation splits interact.
Prerequisites & connections
Explore related knowledge →References
- Decision Trees
scikit-learn developers - CS229 Lecture Notes: Decision Trees (revision 26 August 2023)
Selwin George · 2023
Version2 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: cited-source comparison, re-derivation and recalculation, bilingual argument comparison, and executed Python assertions; no independent human peer review.
- Enumerated 3⁵ five-sample multiclass labelings and checked all candidate gains with rational arithmetic; recomputed 0.08 versus 0.23 for unequal children.
- Corrected frequency counting and implementation complexity; checked constant features, pure nodes, adjacent floats, and invalid inputs.
- Compared the main claims, assumptions, examples, exercises, and citations across languages; structural checks additionally compare display equations, code, and source IDs. This is an AI technical check, not independent human peer review.
Source locations checked:
- Decision Trees · §1.10.7 mathematical formulation, Gini classification criterion and pruning discussion
- CS229 Lecture Notes: Decision Trees (revision 26 August 2023) · Revision 26 August 2023, §§1.1–1.4: partitions, thresholds, weighted gain, regularization
Related topics