decision tree
how it works
The idea in short steps and three pictures, then the tree grown on the same 8 points, 2 questions deep, step by step.
Given points whose shapes are known, a decision tree learns questions that name the shape of a new point. Each question is a cut, halfway between two neighbouring places the points stand at: across below 3.5 asks whether a point stands left of 3.5. To weigh a question, the tree reads every point of the group once to see which side it falls on; each read is one look. For a group it weighs every question, across and up, and asks the one that gains most. Below, 3 triangles low on the left and 5 squares, entropy 0.954. Their places across, 1, 2, 3, 4, 7 and 8, give 5 cuts, and up gives 5 more: 10 questions. That is fewer than 2(n - 1) = 14, the most 8 points can have, as some points share a place. Across below 3.5 gains 0.954 − (4/8 × 0.811 + 4/8 × 0), about 0.549, the most: the group's entropy less each side's entropy times its share, 4 of 8. Each side then becomes a group, split the same way. A group of one shape is a leaf, and so is one at the greatest depth, or one no question helps. A leaf takes the shape most of its points have.
| question | gain |
|---|---|
| across below 3.5? | 0.549 |
| across below 5.5? | 0.348 |
| up below 1.5? | 0.199 |
The question gains 0.549.
With scripts on, a picker shows each question's two sides. The drawing and this line change with it.
Training points
Test points
The tree, each group's triangles+squares
At most 2 deep, the tree has 3 leaves. It gets 1 of its 10 training points wrong and 1 of the 10 test points.
With scripts on, a slider sets the greatest depth from 1 to 3. Both planes, the tree, the chart and this line change with it.
step 1 of 9
8 points of two shapes, and a tree that asks at most 2 questions on the way to any leaf. Every point starts in one group, A.
what it remembers to know where it is
- groups made
- 1
- leaves found
- 0
step 2 of 9
Group A: weigh 10 questions, each a cut across or up halfway between two of its points. Another gains as much, so the tie goes to across.
what it remembers to know where it is
- groups made
- 1
- leaves found
- 0
step 3 of 9
Split group A by asking whether a point is across below 3.5. It gains 0.549. 4 points say yes and 4 say no, and each side is a new group below it.
what it remembers to know where it is
- groups made
- 3
- leaves found
- 0
step 5 of 9
Split group B by asking whether a point is up below 5.5. It gains 0.811. 3 points say yes and 1 says no, and each side is a new group below it.
what it remembers to know where it is
- groups made
- 5
- leaves found
- 0
step 6 of 9
Group C holds 0 triangles and 4 squares. Every point in it is one shape, so it is a leaf: a square.
what it remembers to know where it is
- groups made
- 5
- leaves found
- 1
step 7 of 9
Group D holds 3 triangles and 0 squares. Every point in it is one shape, so it is a leaf: a triangle.
what it remembers to know where it is
- groups made
- 5
- leaves found
- 2
step 8 of 9
Group E holds 0 triangles and 1 square. Every point in it is one shape, so it is a leaf: a square.
what it remembers to know where it is
- groups made
- 5
- leaves found
- 3
step 9 of 9
The tree has 3 leaves. Each leaf's part of the plane is shaded in its shape, the shape a new point there would get.
what it remembers to know where it is
- groups made
- 5
- leaves found
- 3
the steps, in plain words
choose a step to mark the Python, a programming language, that does it
- start with every point in one groupPython line 18
- take the next group, top to bottomPython lines 19 and 20
- weigh every question across and up, and keep the one that gains mostPython lines 13, 14, 15, 16, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34 and 38
- split the group by it into two groups belowPython lines 39 and 40
- a group of one shape, at the greatest depth, or that no question helps, is a leafPython lines 21, 24, 35, 36 and 37
- shade each leaf's part of the plane in the shape most of its points havePython line 22
the same in Python
The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.
from math import log2
def decision_tree(points, depth):
"""The tree grown on points, breadth first, top to bottom.
Each point is a tuple (across, up, shape), the shape "triangle" or
"square"; depth is the most questions asked in a row. A question is
("across", cut) or ("up", cut): a point below the cut goes to the
first group, the rest to the second. A leaf is (shape,). A tie goes to
across, then the smaller cut; a leaf's tie to the triangles.
"""
def entropy(group):
n = len(group)
tri = sum(1 for p in group if p[2] == "triangle")
return -sum(c / n * log2(c / n) for c in (tri, n - tri) if c)
tree, queue = [], [(points, 0)] # every point in one group
while queue:
group, level = queue.pop(0) # the next group, top to bottom
tri = sum(1 for p in group if p[2] == "triangle")
shape = "triangle" if 2 * tri >= len(group) else "square"
scored = []
if 0 < tri < len(group) and level < depth:
for axis, name in ((0, "across"), (1, "up")): # every question
values = sorted({p[axis] for p in group})
for a, b in zip(values, values[1:]):
cut = (a + b) / 2 # halfway between neighbours
below = [p for p in group if p[axis] < cut]
above = [p for p in group if p[axis] >= cut]
low, high = len(below) / len(group), len(above) / len(group)
gain = entropy(group) - low * entropy(below) - high * entropy(above)
scored.append((gain, name, cut, below, above))
top = max((s[0] for s in scored), default=0)
if top <= 1e-12:
tree.append((shape,)) # one shape, the greatest depth, or no gain
continue
gain, name, cut, below, above = next(s for s in scored if abs(s[0] - top) < 1e-12)
tree.append((name, cut)) # the question that gains most
queue += [(below, level + 1), (above, level + 1)]
return tree
how it scales
How the points looked at grow, from ten points to two thousand, on two sets of points.
Each step across or up is ten times the one before. From 10 to 100 points, the row's looks go from 90 to 9,900, about a hundred times: ten times across, a hundred times up. So both lines climb two steps up for each step across. A slope of 2 means the count grows as , as section 4 works out.
points looked at, ten times more at each mark up
, how many points have a shape, ten times more at each mark to the right
- the diagonal, a triangle then a square by turns, grown 3 deep, where each question peels off one end pointsolid where measured by running it; dashed where its formula carries it on to ten millionslope 2: ten times n, 100 times the work
- one row of points, triangles on the left half and squares on the right, which one question splitssolid where measured by running it; dashed where its formula carries it on to ten million
| points looked at | time | |
|---|---|---|
| 1,000 | 5,982,016 | about 6 milliseconds |
| 100,000 | 59,998,200,016 | about 60 seconds |
| 10,000,000 | 599,999,820,000,016 | about 6.9 days |
The points looked at are the same on any computer. The times are not: a real computer may be faster or slower than a billion a second.
make these counts yourself
Copy this script and run it with Python 3.12 or later. It counts the same steps as the plot. Where a count depends on a random shuffle, yours will differ a little.
"""Count a decision tree's looks yourself, as the plot on this page does.
Run it with Python 3.12 or later. For each n it grows the tree on two sets
of n points, 3 questions deep at most, and prints how many points the
questions look at: one row in two halves, triangles then squares, and the
diagonal with a triangle then a square by turns. The counts are the same on
any computer; only the time differs.
"""
from math import log2
def decision_tree(points, depth):
"""The tree grown on points, breadth first, top to bottom.
Each point is a tuple (across, up, shape), the shape "triangle" or
"square"; depth is the most questions asked in a row. A question is
("across", cut) or ("up", cut): a point below the cut goes to the
first group, the rest to the second. A leaf is (shape,). A tie goes to
across, then the smaller cut; a leaf's tie to the triangles.
"""
def entropy(group):
n = len(group)
tri = sum(1 for p in group if p[2] == "triangle")
return -sum(c / n * log2(c / n) for c in (tri, n - tri) if c)
tree, queue = [], [(points, 0)] # every point in one group
while queue:
group, level = queue.pop(0) # the next group, top to bottom
tri = sum(1 for p in group if p[2] == "triangle")
shape = "triangle" if 2 * tri >= len(group) else "square"
scored = []
if 0 < tri < len(group) and level < depth:
for axis, name in ((0, "across"), (1, "up")): # every question
values = sorted({p[axis] for p in group})
for a, b in zip(values, values[1:]):
cut = (a + b) / 2 # halfway between neighbours
below = [p for p in group if p[axis] < cut]
above = [p for p in group if p[axis] >= cut]
low, high = len(below) / len(group), len(above) / len(group)
gain = entropy(group) - low * entropy(below) - high * entropy(above)
scored.append((gain, name, cut, below, above))
top = max((s[0] for s in scored), default=0)
if top <= 1e-12:
tree.append((shape,)) # one shape, the greatest depth, or no gain
continue
gain, name, cut, below, above = next(s for s in scored if abs(s[0] - top) < 1e-12)
tree.append((name, cut)) # the question that gains most
queue += [(below, level + 1), (above, level + 1)]
return tree
def count(points, depth):
"""The same method on points, counting each point each question looks at."""
looked, queue = 0, [(points, 0)]
while queue:
group, level = queue.pop(0)
tri = sum(1 for p in group if p[2] == "triangle")
if tri in (0, len(group)) or level == depth:
continue # a leaf weighs no question
first = decision_tree(group, 1) # the question this group asks
questions = sum(len({p[axis] for p in group}) - 1 for axis in (0, 1))
looked += questions * len(group) # each question looks at every point
if len(first) == 1:
continue # no question gains: a leaf
name, cut = first[0]
axis = 0 if name == "across" else 1
queue += [([p for p in group if p[axis] < cut], level + 1), ([p for p in group if p[axis] >= cut], level + 1)]
return looked
def cheapest(n):
"""One row of n points, 1 apart, the left half triangles: one question splits them."""
return [(i, 5, "triangle" if i < n / 2 else "square") for i in range(n)], 3
def dearest(n):
"""The diagonal, a triangle then a square by turns: each question peels off one end point."""
return [(i, i, "triangle" if i % 2 == 0 else "square") for i in range(n)], 3
if __name__ == "__main__":
print(f"{'n':>5} {'two halves':>11} {'by turns':>10}")
for n in (10, 20, 50, 100, 200, 500, 1000, 2000):
print(f"{n:>5} {count(*cheapest(n)):>11} {count(*dearest(n)):>10}")
best, worst and average
Here best and worst only name two sets of points, both measured; no average is worked out, as there is no one way to pick points. The best column is the one row's cost, not the cheapest set: points packed in a square block need fewer looks, as the table shows. The diagonal by turns is the dearest set grown 3 deep. Why: each way, a group has at most one gap fewer than its points, so its questions are at most twice that. Setting one point apart leaves the biggest group, all but one point, to weigh next. One big group looks more than two smaller ones. At 8 points, groups of 7 and 1 look 2 × 7 × 6 = 84 times below the root. Groups of 4 and 4 look only 24 + 24 = 48.
A case is one kind of input, the thing the method is given, such as a set of points. A bound says how fast that case's cost grows as more points come in.
The count is in the grid. Every question looks at every point of its group. So the row looks about n times n times and the diagonal about 6 times that, and the three bounds all grow as n squared.
| bestone row of points, triangles on the left half and squares on the right, which one question splits | worstthe diagonal, a triangle then a square by turns, grown 3 deep, where each question peels off one end point | |
|---|---|---|
| points looked at | , from 2 points on; 1 point is a leaf, 0 looks | |
| how the points looked at grow in each case | ||
| tight, | ||
| ceiling, | ||
| floor, | ||
extra memory: the tree, at most 1 + 2 + 4 + 8 = 15 groups at depth 3, and the groups' points, at most n at each depth
Extra memory is the room it needs on top of the input itself, while it runs.
| 16 points | places across | places up | questions | looked |
|---|---|---|---|---|
| one row in halves | 16 | 1 | 15 | 240 |
| a 4 by 4 block in halves | 4 | 4 | 6 | 96 |
where the formula comes from
The two counts above, and the gain of a perfect question, each worked out in small steps naming the line it comes from.
the move: see the questions
the line:why it is allowed: On the diagonal no two points share a place across or up. A group of points has gaps each way, so questions, and each looks at all points.
the move: an end point peels off
the line:points gain of each cut across, left to right 3 0.252, 0.252 4 0.311, 0, 0.311 5 0.171, 0.020, 0.020, 0.171 6 0.191, 0, 0.082, 0, 0.191 Every cut's gain on the diagonal by turns. The two end cuts gain most, and up has the same cuts, so the first cut across is asked. The same holds at every size measured, 3 to 1,000. why it is allowed: On the diagonal by turns, the end cuts leave one point alone, of one shape, and gain most, as the table shows. A tie goes to the smaller cut. That point is a leaf and weighs nothing. What is left is again a diagonal by turns.
guess it, thenthe move: three groups weighed
the line:group points questions looked the root 4 6 24 after one end point leaves 3 4 12 after another 2 2 4 The 4 points of section 5, grown 3 deep. Each question that gains most peels off one end point, a leaf of one shape. 24 + 12 + 4 = 40. why it is allowed: is the points looked at. By lines 1 and 2, the groups weighed hold , then , then points. After 3 questions in a row the groups are leaves. At 3 points the third group holds 1 point and weighs nothing: 2 × 1 × 0 = 0. At 2 points the second group holds 1 point, 2 × 1 × 0 = 0, and the third holds none, 2 × 0 × (−1) = 0.
guess it, thenthe move: multiply out
the line:why it is allowed: By line 3, each pair of brackets multiplied out.
guess it, thenthe move: add like terms
the line:why it is allowed: By line 4, the squares add to , the terms to , and the numbers to 16. For 4 points, 40.
guess it, thenthe move: a ceiling
the line:why it is allowed: By line 5, is with 18 times taken away and 16 put back. From 1 point on, more is taken away than put back.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 6, is at most 6 times .
guess it, thenthe move: drop the later groups
the line:why it is allowed: By line 3, the other two terms are never below 0 from 2 points on, so is at least its first term.
guess it, thenthe move: a floor
the line:points 2 4 4 3 12 9 4 24 16 5 40 25 The first term against . They meet at 2 points, and the first term pulls ahead from there. why it is allowed: By line 8. From 2 points on, is at least half of ; times , line 8's term is at least , as the table shows.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 9, never drops below 1 times .
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 7 and 10 bound by the same growth, .
guess it, then
try it with a small : at , line 3 gives , which you can work out by hand
the move: one group weighed
the line:question left side right side looks across below 0.5 1 triangle 1 triangle, 2 squares 4 across below 1.5 2 triangles 2 squares 4 across below 2.5 2 triangles, 1 square 1 square 4 One row of 4 points, 2 triangles then 2 squares. Three questions, each looking at all 4: 12 looks. The middle one leaves two groups of one shape, so the tree stops. why it is allowed: is the points looked at. All points stand at one height, so up has no question, and across has gaps. Each question looks at all points. The cut between the halves leaves both sides one shape, so it gains the group's whole entropy, the most any question can. It is asked, and the tree stops.
the move: multiply out
the line:why it is allowed: By line 1. For 4 points, 12.
guess it, thenthe move: a ceiling
the line:why it is allowed: By line 2, is less .
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 3, is at most 1 times .
guess it, thenthe move: a floor
the line:why it is allowed: By line 2, is less , and from 2 points on is at most half of .
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 5, never drops below a half times .
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 4 and 6 bound by the same growth, .
guess it, then
try it with a small : at , line 1 gives , which you can work out by hand
the move: the gain, written out
the line:why it is allowed: Here is how many of each shape, so points, as on the concept page. is the gain. The group's entropy comes first. Each side holds half the points, all of one shape, so each side's entropy is 0.
the move: drop the zeros
the line:why it is allowed: By line 1, both sides add nothing.
guess it, thenthe move: the group is half and half
the line:where does this come from?
question 1 of the page information and entropyWhy is a group of triangles and squares exactly 1 mixed? the move: each share times the log of one over it
the line:why it is allowed: is the entropy of triangles and squares. Each shape's share is of the points, and one over it is over .
the move: cancel the n
the line:why it is allowed: By line 1, over is a half, and over is 2.
the move: two halves make one
the line:why it is allowed: By line 2, half of a number added to half of it is the number.
the move: read the log
the line:why it is allowed: By line 3, 2 is 2 to the power 1, so its log to base 2 is 1. For 4 triangles and 4 squares, 1.
why it is allowed: Line 2 is the entropy of triangles and squares, which is exactly 1; the steps that show it open just below. For the row of 4 points in the ladder above, 2 of each, the middle question gains 1.
guess it, then
try it with a small : at , line 1 gives , which you can work out by hand
count it yourself
Count every step on four points on the diagonal, a triangle then a square by turns, grown 3 deep. In its table, the counts are running totals so far, the questions weighed and the points they looked at. A point such as 0 0 t is a triangle at 0 across, 0 up (s is a square). After the semicolon comes the greatest depth. Then check the looks against the formula.
| step | what happens | questions weighed | points looked at |
|---|---|---|---|
| 1 | 4 points of two shapes, and a tree that asks at most 3 questions on the way to any leaf. Every point starts in one group, A. | 0 | 0 |
| 2 | Group A: weigh 6 questions, each a cut across or up halfway between two of its points. 3 others gain as much, so the tie goes to across, then to the smaller cut. | 6 | 24 |
| 3 | Split group A by asking whether a point is across below 0.5. It gains 0.311. 1 point says yes and 3 say no, and each side is a new group below it. | 6 | 24 |
| 4 | Group B holds 1 triangle and 0 squares. Every point in it is one shape, so it is a leaf: a triangle. | 6 | 24 |
| 5 | Group C: weigh 4 questions, each a cut across or up halfway between two of its points. 3 others gain as much, so the tie goes to across, then to the smaller cut. | 10 | 36 |
| 6 | Split group C by asking whether a point is across below 1.5. It gains 0.252. 1 point says yes and 2 say no, and each side is a new group below it. | 10 | 36 |
| 7 | Group D holds 0 triangles and 1 square. Every point in it is one shape, so it is a leaf: a square. | 10 | 36 |
| 8 | Group E: weigh 2 questions, each a cut across or up halfway between two of its points. Another gains as much, so the tie goes to across. | 12 | 40 |
| 9 | Split group E by asking whether a point is across below 2.5. It gains 1. 1 point says yes and 1 says no, and each side is a new group below it. | 12 | 40 |
| 10 | Group F holds 1 triangle and 0 squares. Every point in it is one shape, so it is a leaf: a triangle. | 12 | 40 |
| 11 | Group G holds 0 triangles and 1 square. Every point in it is one shape, so it is a leaf: a square. | 12 | 40 |
| 12 | The tree has 4 leaves. Each leaf's part of the plane is shaded in its shape, the shape a new point there would get. | 12 | 40 |
In all, 40 points looked at. The formula from section 4, , gives at : the same.
where you meet it
Decision trees are old, quick to read, and still offered by toolkits such as scikit-learn.
scikit-learn, a Python library for machine learning
Its DecisionTreeClassifier tool grows a tree of yes-or-no questions on numbers, as this page does. It can weigh a question by entropy, as here. Unless told, it uses another measure of how mixed a group is. A greatest depth, max_depth, stops it growing.
source: scikit-learn's documentation, the user guide's section on decision trees and the DecisionTreeClassifier reference
ID3
In 1986 J. Ross Quinlan set out ID3, a program he first described in 1979. It grows a tree by asking at each group the question that gains most, its gain worked from entropy. Its questions asked about named values, such as a colour, red, green or blue, and could split a group in more than two.
source: Quinlan, Induction of Decision Trees, Machine Learning, volume 1, 1986
CART
In 1984 Leo Breiman, Jerome Friedman, Richard Olshen and Charles Stone described CART, whose trees ask only yes-or-no questions, as this page's do. They grew a tree large, then cut it back a step at a time. They chose among the cut-back trees by how well each did on points held aside, like this page's test points.
source: Breiman, Friedman, Olshen and Stone, Classification and Regression Trees, 1984
| greatest depth | training points wrong | test points wrong |
|---|---|---|
| 1 | 2 of 10 | 4 of 10 |
| 2 | 1 of 10 | 1 of 10 |
| 3 | 0 of 10 | 2 of 10 |
what is used instead
A tree's cuts are always across or up, so a boundary that runs on a slant takes many questions. k-nearest neighbours, on this site, needs no cuts: it looks at the points nearest each new point. It measures every point for each new point, where a grown tree asks only a few questions.
how it compares
A decision tree beside k-nearest neighbours on the same points. One plane, two ways of drawing its parts.