Decision tree

A decision tree grown live in your browser, one split per step: Gini, entropy or MSE, every candidate threshold scored, tree diagram, 3D cone tree and pruning. Matches scikit-learn node for node.

Updated

  • Impurity: Gini, entropy, MSE
  • How the best split is chosen
  • Depth and leaf-size limits
  • Overfitting on a test set
  • Cost-complexity pruning
x₂ ≤ 0.76 ?
Preparing the lab…

Intuition

Carving rectangles one cut at a time

To separate three classes of points, a decision tree finds a horizontal or vertical line that splits the points into two piles, each as "pure" (mostly one class) as possible. Then it finds a cut for each pile, and so on, until the piles are pure enough or the tree is deep enough. Every cut looks at a single feature, so every region is a rectangle.

The three small labs below really grow trees, one cut at a time. Each rectangle is a leaf coloured by its majority class (darker = purer); the black line is the latest cut.

Three clusters: max depth 6Preparing…
XOR: max depth 2Preparing…
XOR: max depth 6Preparing…

First picture: the first cut is the horizontal line x2≤0.47x_2 \le 0.47, which slices off almost the whole green cluster at the top; later cuts separate the bottom-left and bottom-right clusters, then tidy the corners. The tree is fully grown after 18 steps with 18 leaves, 99% training accuracy and 91% test accuracy.

The second and third use the same XOR data (bottom-left and top-right are one class, top-left and bottom-right the other). With depth 2 the test accuracy is only 49%, no better than guessing; with depth 6 it reaches 95%. The culprit is greediness: whichever single cut you make on XOR data, both sides are still half and half, so the first cut looks worthless and the tree has to make a few arbitrary cuts before later ones start to help.

Math

Impurity

A node has nn samples with class proportions pkp_k. Two common impurities:

Gini:  I=1−∑kpk2,Entropy:  I=−∑kpklog⁡2pk\text{Gini}: \; I = 1 - \sum_k p_k^2, \qquad \text{Entropy}: \; I = -\sum_k p_k \log_2 p_k

Both are 0 for a pure node (one class) and largest when the classes are equally represented. Three equal classes give a Gini of 1−3×(1/3)2=0.6671 - 3\times(1/3)^2 = 0.667.

The best cut

For every feature jj of node tt and every candidate threshold ss (the midpoint between two consecutive distinct values), split the samples into left L={xj≤s}L = \{x_j \le s\} and right RR and compute the impurity decrease:

Δ(t;j,s)=ntN[I(t)−nLntI(L)−nRntI(R)]\Delta(t; j, s) = \frac{n_t}{N}\Big[I(t) - \frac{n_L}{n_t} I(L) - \frac{n_R}{n_t} I(R)\Big]

NN is the total number of training samples (the factor nt/Nn_t/N makes decreases at different nodes comparable, as in scikit-learn). Take the (j,s)(j, s) with the largest Δ\Delta.

The root of this page's default data: 200 points, about a third per class (67, 67, 66), Gini ≈ 0.667. The best cut is x2≤0.472x_2 \le 0.472:

SamplesClass countsGini
Left (≤)12762, 62, 30.523
Right (>)735, 5, 630.246

Weighted impurity 127200×0.523+73200×0.246≈0.422\tfrac{127}{200}\times0.523 + \tfrac{73}{200}\times0.246 \approx 0.422, decrease Δ≈0.667−0.422=0.245\Delta \approx 0.667 - 0.422 = 0.245.

When to stop

A node becomes a leaf if any of these holds: it is pure; it reached the maximum depth; it has fewer samples than the split minimum; or every split would leave one side with fewer than the leaf minimum. A leaf predicts its majority class (its mean, for regression).

Cost-complexity pruning

A fully grown tree is often too fine-grained. Define the penalised cost Rα(T)=R(T)+α ∣T∣R_\alpha(T) = R(T) + \alpha\,|T|, where R(T)R(T) is the weighted impurity summed over leaves and ∣T∣|T| the number of leaves. For each internal node tt, measure whether removing its subtree is worth it:

g(t)=R(t)−R(Tt)∣Tt∣−1g(t) = \frac{R(t) - R(T_t)}{|T_t| - 1}

R(t)R(t) is the cost of collapsing tt into a leaf and R(Tt)R(T_t) the cost of its subtree. Repeatedly prune the node with the smallest gg (the weakest link) until the smallest g(t)g(t) exceeds α\alpha.

With a maximum depth of 14 these data grow 19 leaves with 91% test accuracy; α = 0.01 prunes to 9 leaves at the same 91%; α = 0.02 prunes to 4 leaves and test accuracy falls to 83%.

Depth and overfitting

Max depthTraining accuracyTest accuracy
162.5%63%
293%83%
496.5%84%
6 (default)99%91%
10100%91%

At depth 10 the tree classifies every training point correctly (19 leaves), yet test accuracy does not improve: the extra leaves are memorising noise.

How it is computed, with real numbers

Below is the computation behind the lab's latest split. Step the lab once more and this switches to the new cut.

Once the lab above has loaded, this panel works through the same formulas with its current numbers.

Experiment

Follow the lesson

Course

Lesson 1: greedy cuts and overfitting

5 steps · each one: set up and run → look → answer

  1. 1. The first cut

    Take one step. Look at the black line in "Feature space" and the split-search chart on the right.

    Why is the first cut the horizontal x₂ ≤ 0.47 rather than a vertical line?
  2. 2. Fully grown

    Continue until the tree is fully grown. Compare training and test accuracy.

    Training 99%, test 91%: where does the 8% gap come from?
  3. 3. XOR fools the greedy search

    Switch to XOR with max depth 2.

    Why does a depth-2 tree reach only 49% test accuracy?
  4. 4. Go deeper

    Set the max depth to 6.

    Why does a bit more depth fix it (95%)?
  5. 5. Pruning

    Back to the three clusters with max depth 14 and pruning strength α = 0.01. Watch it grow fully, then prune.

    Pruned to 9 leaves, why is the test accuracy unchanged?

Try these settings

Exercises

Exercises

Exercise 1: crack XOR with as few leaves as possible

At least 95% test accuracy with no more than 11 leaves.

Hint

Max depth 6 is exactly right: 11 leaves, 95%. Depth 5 gives only 84%; depth 7 adds a leaf.

  • Test accuracy ≥ 0.950
  • Leaves ≤ 11

Exercise 2: slim down without losing accuracy

Max depth is fixed at 14 (fully grown: 19 leaves, 91% test). Bring the leaves down to 10 or fewer without losing test accuracy.

Hint

Two ways: pruning strength α = 0.01 (9 leaves), or a leaf minimum of 5 (10 leaves). A leaf minimum of 10 goes too far: 82% test.

  • Leaves ≤ 10
  • Test accuracy ≥ 0.910

Exercise 3: circles without overfitting

The defaults give 100% training but only 88% test accuracy (9 leaves). Reach 91% test accuracy with at most 7 leaves.

Hint

A leaf minimum of 5: 7 leaves, 91%. Or max depth 14 with α = 0.02: 5 leaves, 91%.

  • Test accuracy ≥ 0.910
  • Leaves ≤ 7

Quiz

What does a decision tree's boundary look like?
A node holds 90 of class A and 10 of class B. What is its Gini impurity?
Raising the max depth from 6 to 10 gives 100% training accuracy and unchanged test accuracy. What does that mean?

Further reading

Frequently asked questions

How does a decision tree choose its splits?

For every candidate threshold of every feature it computes how much the weighted impurity (Gini or entropy) of the two children falls below the parent's, and takes the largest decrease. It is greedy: it considers only this cut, not the ones after it.

What is the difference between Gini and entropy?

Both measure how mixed a node is and are 0 when it is pure. Gini needs no logarithm and is slightly faster; entropy is more sensitive to small probabilities. In practice they pick the same split almost every time — on this page's three clusters, entropy also gives 18 leaves and 91% test accuracy.

Why do decision trees overfit, and what can I do?

Unconstrained, a tree keeps splitting until every leaf holds one point: 100% training accuracy, but the little rectangles trace noise. Limit the maximum depth or the minimum leaf size, or grow fully and then apply cost-complexity pruning (scikit-learn's ccp_alpha); more thoroughly, average many trees (random forests).

Do decision trees need feature scaling?

No. A split only compares values of one feature, so any monotonic transformation (scaling, taking logs) leaves the tree unchanged.

Can decision trees do regression?

Yes. A leaf outputs the mean of its region and the impurity becomes the variance (mean squared error). This page's "Wave" data use a regression tree.

Further reading