AI Wiki中文/EN

Decision trees

决策树

Partition data through feature questions and understand impurity, greedy splits, pruning, and generalization.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Intuition: 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 xj≤tx_j\leq t. 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 kk has proportion pkp_k in a node, Gini impurity is G=1−∑kpk2G=1-\sum_kp_k^2. A pure node has impurity zero; a balanced binary node has impurity 0.5. Entropy, H=−∑kpklog⁡pkH=-\sum_kp_k\log p_k, is another option, with 0log⁡0=00\log0=0 by convention.

For a parent containing NN samples and children containing NL,NRN_L,N_R, the gain is:

Δ=G(parent)−NLNG(left)−NRNG(right).\Delta=G(parent)-\frac{N_L}{N}G(left)-\frac{N_R}{N}G(right).

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

  1. What is the impurity of labels 0, 0, 1, 1? Answer: 0.5.
  2. What is the gain from splitting these perfectly into pure children? Answer: 0.5.
  3. Must the best threshold remain unchanged after flipping one label? Answer: no; this illustrates the sensitivity of a single tree.
  4. 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?

Choose one answer

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

  1. Decision Trees
    scikit-learn developers
  2. 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:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.