Search

Search papers and lessons

Decision Tree

Level 2 · 9 min read

A decision tree predicts by asking a short series of yes-or-no questions about the inputs, choosing each question to make the answers as clean as possible.

On this page

  • Colour = topic mix
  • Probability
  • Classical models
  • Learning basics
  • Losses & regularization
  • Discrete math
  • Sign in to see your progress

TL;DR

A decision tree is a flowchart learned from data. Each internal node asks a question about one input feature, such as "is the size above 70?", and each leaf gives a prediction. To grow the tree, the algorithm tries many questions and keeps the one that splits the training examples into the purest groups, then repeats on each group.

Trees predict categories (classification) or numbers (regression), and they are easy to read. A single deep tree tends to memorise its training data, so they are usually combined into ensembles.

Where you'll see it: credit and fraud scoring rules, medical triage checklists, and as the base learner inside random forests and gradient-boosted models such as ensembles.

Intuition

A game of twenty questions

Think of the game where one player hides an object and the other asks yes-or-no questions to narrow it down. A good first question removes about half the possibilities. A bad one, like "is it exactly this one thing?", removes almost none. A decision tree plays the same game with data. The "objects" are training examples, labelled with the answer you want to predict, and each question tests one input feature.

Each question sorts the examples into two piles. The best question is the one that leaves each pile as uniform as possible, so that knowing which pile an example is in tells you a lot about its label. Once a pile contains only one label, there is nothing left to ask, and that pile becomes a leaf.

The plot shows why purity is measured the way it is. For a two-class node where a fraction pp of examples belong to one class, the two standard impurity measures are entropy and Gini impurity. Both are zero when the node is pure and largest when p=0.5p = 0.5.

0.20.40.60.800.20.40.60.81p (fraction in one class)impurity
  • entropy (bits)
  • Gini impurity
Both measures peak at a 50/50 split and fall to zero when the node is pure. The split search rewards questions that push nodes toward the ends of this curve.

Two kinds of tree

For classification, a leaf predicts the most common label among its training examples, or the label fractions. For regression, a leaf predicts the average of its training targets. The splitting logic is the same; only the impurity measure changes. The name CART (classification and regression trees) covers both.

flowchart TD
  R["Sender in contacts?"] -->|"yes"| L1["Leaf: not spam (3 of 3)"]
  R -->|"no"| N["Contains free?"]
  N -->|"yes"| L2["Leaf: spam"]
  N -->|"no"| L3["Leaf: not spam"]

The math

Setup

We have nn training examples (xi,yi)(\mathbf{x}_i, y_i), where xi\mathbf{x}_i is a vector of input features and yiy_i is the target. A node holds a subset SS of these examples. A split chooses a feature jj and a threshold tt, and sends examples with xij≤tx_{ij} \le t to a left child and the rest to a right child.

For a node with KK classes, let pkp_k be the fraction of SS belonging to class kk. The two impurity measures are

H(S)=−∑k=1Kpklog⁡2pk(entropy, in bits)H(S) = -\sum_{k=1}^{K} p_k \log_2 p_k \qquad \text{(entropy, in bits)} G(S)=1−∑k=1Kpk2(Gini impurity)G(S) = 1 - \sum_{k=1}^{K} p_k^2 \qquad \text{(Gini impurity)}

Entropy is the measure in the entropy lesson, and it measures average surprise. Gini impurity is the probability that two examples drawn at random from the node carry different labels. Both are zero for a pure node.

Information gain

A split is scored by how much it reduces impurity. With entropy, the gain is

IG⁡(S,j,t)=H(S)−∑c∈{left,right}∣Sc∣∣S∣ H(Sc),\operatorname{IG}(S, j, t) = H(S) - \sum_{c \in \{\text{left}, \text{right}\}} \frac{|S_c|}{|S|}\, H(S_c),

where ScS_c is the child subset and ∣Sc∣/∣S∣|S_c|/|S| is the fraction of examples that went there. The weighted average means a split that sends most examples to a very pure child is rewarded. For Gini, replace HH with GG; the formula is otherwise identical.

For regression the impurity is the sum of squared errors around the node mean, ∑i∈S(yi−yˉS)2\sum_{i \in S} (y_i - \bar{y}_S)^2, and the gain is the drop in that sum. The leaf prediction is yˉS\bar{y}_S.

Growing the tree

The algorithm is greedy and recursive:

  1. For each feature, sort the examples by that feature and try a threshold midway between each pair of neighbouring values.
  2. Keep the feature and threshold with the largest gain.
  3. Split, and repeat on each child.
  4. Stop when a node is pure, when it has fewer than a minimum number of examples, or when the depth reaches a limit. Its prediction is then the leaf value.

Greedy means the tree picks the best question now, not the best tree overall. That is cheap and usually good enough, but it is not optimal.

Worked examples

Example
Choosing a split for spam, with entropy

Eight emails: 4 spam, 4 not spam. The root entropy is H=1H = 1 bit, since the classes are exactly even.

Candidate A, "contains the word free": 4 emails have it (3 spam, 1 not), and 4 do not (1 spam, 3 not).

  1. Entropy of each child with p=3/4p = 3/4: H=−(0.75log⁡20.75+0.25log⁡20.25)=0.75×0.415+0.25×2=0.811H = -(0.75 \log_2 0.75 + 0.25 \log_2 0.25) = 0.75 \times 0.415 + 0.25 \times 2 = 0.811.
  2. Both children have the same entropy, 0.8110.811, so the weighted sum is 48(0.811)+48(0.811)=0.811\tfrac{4}{8}(0.811) + \tfrac{4}{8}(0.811) = 0.811.
  3. Information gain: 1−0.811=0.1891 - 0.811 = 0.189 bits.

Candidate B, "sender is in contacts": 3 emails are from contacts, all not spam. The other 5 contain 4 spam and 1 not.

  1. The contacts child is pure, so H=0H = 0.
  2. The other child has p=4/5p = 4/5: H=−(0.8log⁡20.8+0.2log⁡20.2)=0.722H = -(0.8 \log_2 0.8 + 0.2 \log_2 0.2) = 0.722.
  3. Weighted sum: 38(0)+58(0.722)=0.451\tfrac{3}{8}(0) + \tfrac{5}{8}(0.722) = 0.451.
  4. Information gain: 1−0.451=0.5491 - 0.451 = 0.549 bits.

Interpretation: B removes far more uncertainty than A, so the root asks about contacts first. The contacts branch becomes a leaf, and the other branch is split again.

Example
A regression leaf for house prices

Four houses, with size in square metres and price in thousands:

SizePrice
50150
60170
80250
100290
  1. Without any split, predict the mean price yˉ=(150+170+250+290)/4=215\bar{y} = (150 + 170 + 250 + 290)/4 = 215. The sum of squared errors is 652+452+352+752=13,10065^2 + 45^2 + 35^2 + 75^2 = 13{,}100.
  2. Split at size 70. The left child is {50,60}\{50, 60\} with prices 150 and 170, mean 160. Its squared errors are 102+102=20010^2 + 10^2 = 200.
  3. The right child is {80,100}\{80, 100\} with prices 250 and 290, mean 270. Its squared errors are 202+202=80020^2 + 20^2 = 800.
  4. Total error after the split is 200+800=1,000200 + 800 = 1{,}000, a reduction of 12,10012{,}100 from the root.
  5. A new 65 square metre house falls on the left, so the tree predicts 160 thousand.

Interpretation: the leaf predicts the average of the houses it contains. A tree with a single split is a step function, so a finer tree gives finer steps and, if it goes too far, starts following noise.

Tradeoffs and failure modes

Trees are easy to explain, need little preprocessing, handle mixed feature types and interactions, and are fast to predict with. Their weaknesses are just as real.

SituationProblemBetter choice
Tree grown until leaves are pureHigh variance; memorises noise, see OverfittingLimit depth or minimum leaf size, or prune
Small data changesGreedy splits can change the whole structureBagging or random forests
Smooth underlying functionAxis-aligned steps approximate it poorlyLinear models, or boosting many small trees
Need a probability, not a labelLeaf fractions are noisy when leaves are smallCalibration, or ensembles that average
Very high-cardinality categoriesMany possible splits favour features with many valuesTarget encoding, or limit the feature

A single tree is usually the wrong final model for accuracy. It is the right model when someone needs to read the rule.

History

The first tree-growing method for data analysis was AID, developed by James Morgan and John Sonquist in the early 1960s to find which variables explained survey responses. Leo Breiman, Jerome Friedman, Richard Olshen and Charles Stone published CART in 1984, which gave the cost-complexity pruning and binary splits used in most libraries today. Ross Quinlan developed ID3 in 1986 and C4.5 in 1993, which used information gain and handled categorical features more directly.

Trees became a building block when Breiman showed in 1996 that averaging trees trained on bootstrap samples reduces variance, and in 2001 added random feature selection to form random forests. Those ensembles, not single trees, are where decision trees are most widely used.

Check yourself

QuestionIn one sentence, what makes a split good, and what happens to a node once its examples all share one label?Show answer

A good split leaves the child nodes purer than the parent, meaning lower entropy or Gini impurity, with the largest weighted reduction in impurity. A node whose examples all share one label is pure, so it becomes a leaf that predicts that label.

QuestionA node has 6 examples: 5 of class A and 1 of class B. What is its Gini impurity?Show answer

G=1−(5/6)2−(1/6)2=1−25/36−1/36=1−26/36=10/36≈0.278G = 1 - (5/6)^2 - (1/6)^2 = 1 - 25/36 - 1/36 = 1 - 26/36 = 10/36 \approx 0.278.

QuestionUsing the spam example, why does information gain for the contacts split (0.549) beat the gain for the word free split (0.189), even though both are binary?Show answer

The gain measures how much the weighted child impurity falls. The contacts split puts three examples into a pure child and five into a child that is 80 percent one class. The free split leaves both children at 75 percent, which removes little uncertainty. A split is rewarded for producing purer children, not for being binary.

QuestionIn the house example, why is the leaf prediction 160 and not the nearest single neighbour's price?Show answer

The leaf predicts the mean of the training targets in its region, because for squared error the mean minimises the sum of squared errors within that leaf. Using one neighbour's price would be a nearest-neighbour rule, and it would give a much noisier prediction.

QuestionYou grow a tree until every leaf is pure and it scores 100 percent on training data but 60 percent on new data. What is happening, and what would you change first?Show answer

The tree has memorised the training examples, including their noise, so its variance is high and it does not generalise. The first change is to limit growth, by setting a maximum depth or a minimum number of examples per leaf, and then to check performance on a validation set. If accuracy is still unstable, averaging many trees with bagging or a random forest is the next step.

Sources