π³ Decision Trees
πΏ What is a decision tree?
It is morning. You are dressed and ready to go outside. You wonder whether your clothes suit the weather: if it is warm outside, you would rather wear short sleeves, otherwise a coat. You can draw this decision process as a few yes/no questions:
- Question 1: π‘οΈ Is it warm outside?
- β
Yes β Question 2a: π Are you wearing short sleeves?
- β Yes β π― Perfect
- β No β ποΈ Change clothes (too warm!)
- β No β Question 2b: π§₯ Are you wearing a coat?
- β Yes β π― Perfect
- β No β ποΈ Change clothes (you will freeze!)
- β
Yes β Question 2a: π Are you wearing short sleeves?
You start at the top with the first question, "Is it warm outside?". Depending on your answer, you follow a branch to the next question, until you reach a final conclusion: "π― Perfect!" or "ποΈ Change clothes". Such a diagram of successive yes/no questions is exactly what a decision tree is.
A decision tree is a model that makes a decision by asking a series of simple questions. Each answer divides the possibilities into smaller groups, until you reach a final prediction. In machine learning, nobody draws that tree by hand: the algorithm learns the questions from examples.
Just like a real tree, a decision tree has several parts:
- πͺ΅ Root: the first question at the top, where the process starts.
- π‘ Nodes: every question in the tree. A question is always about one feature ("Is it warm?", "Is the color orange?", "Is the height greater than 80 mm?").
- πΏ Branches: the connections between the questions, one for each possible answer.
- π Leaves: the end points of the tree, which hold the decision or prediction.
You come across decision trees everywhere, even outside AI. An identification key for naming a plant or a bird ("Does the leaf have a serrated edge?"), the triage protocol in an emergency department, the flowchart that helps a doctor or psychologist make a diagnosis, even the game Guess Who?: they are all decision trees that people drew by hand. In this chapter, we let the computer work out such a tree from examples by itself. The result is a model whose every decision you can explain: you simply follow the questions from top to bottom.
π Using a tree
π― From question to prediction
How do you use a decision tree to predict something for a new case? You "walk" through the tree from the root to a leaf, and on the way you answer each question for that case.
Take this tree, which predicts from the weather whether you should take an umbrella:
Suppose it is not raining today, but it is cloudy and the weather app gives a 60% chance of rain. Then you follow this path:
- "π§οΈ Is it raining?" β β No β to the right
- "βοΈ Is it cloudy?" β β Yes β to the left
- "π¦οΈ Chance of rain (%)": 60 is greater than 50 β to the right, along the branch "> 50"
- Conclusion: π Take an umbrella
The last question shows that a tree can also work with numbers. "Is the chance of rain higher than 50%?" is a question with a threshold: the branch "β€ 50" (50% or less) leads to "no umbrella needed", the branch "> 50" (more than 50%) to "take an umbrella".
Using a trained model to make a prediction for new, unseen data is called inference. For a decision tree, that means walking from the root to a leaf, each time choosing the correct branch.
πΊοΈ Decision regions
Just as with nearest neighbors, we can draw which label a decision tree predicts for every possible point: the decision regions.
With nearest neighbors, those were irregular islands around the examples; a decision tree works differently. Here too, we represent each piece of fruit as a point in the plane, with its width and height as coordinates. Every question in the tree divides that plane into two parts. The question "Is the height greater than 80.5 mm?" draws a horizontal line at height 80.5: everything below it belongs to the "no" branch, everything above it to the "yes" branch. Each part gets the color of the kind of fruit that occurs most often in it:
Every further question cuts one of those parts in two again, with a horizontal or a vertical line. Below, the tree may grow two questions deep: each of the two parts is split in turn. Follow the questions in the tree and find the matching rectangles in the plot. If you let the tree grow further (you can do that in the practice demo at the bottom), each region is divided into ever smaller rectangles.
Notice that a decision tree always makes straight cuts, horizontal or vertical. Each question is about only one feature, so the boundaries always run parallel to the axes. A slanted boundary (such as "height + width > 150") is something the tree cannot draw in a single step; it can only approximate it as a staircase of many small rectangles. That contrasts with the irregular boundaries of nearest neighbors.
π± Learning a tree from data
πΉ The cocktail bar
We now know how to use a decision tree. But how do you learn one from data?
Suppose you often go to the same cocktail bar with friends, who keep ordering new cocktails for you to taste. Unfortunately, some cocktails made you nauseous. To avoid that, you want to be able to predict from what you see whether a cocktail will make you nauseous.

The cocktails in our dataset: can you see which ones would make you nauseous?
You have collected your experiences in a dataset:
π Shape | π¨ Color | π₯’ Stirrer | π Lemon slice | π Volume | π΅βπ« Nauseous? |
|---|---|---|---|---|---|
| Cylinder | Orange | β No | β No | 25 cl | βΊοΈ No |
| Cylinder | Black | β No | β Yes | 25 cl | βΊοΈ No |
| Cone | White | β No | β No | 10 cl | βΊοΈ No |
| Trapezoid | Green | β Yes | β No | 15 cl | βΊοΈ No |
| Cone | Yellow | β No | β Yes | 15 cl | βΊοΈ No |
| Trapezoid | Orange | β Yes | β No | 15 cl | π€’ Yes |
| Cone | Orange | β No | β No | 15 cl | π€’ Yes |
| Cone | Orange | β No | β Yes | 10 cl | π€’ Yes |
The table contains five features (π shape of the glass, π¨ color, π₯’ stirrer, π lemon slice, π volume) and one label (π΅βπ« nauseous or not). Our goal: a decision tree that predicts from those features whether we will feel nauseous.
β From feature to yes/no question
A decision tree only asks yes/no questions, so we have to be able to turn every feature into such questions. How we do that depends on the kind of feature:
- Yes/no features are the simplest: the question is the feature itself. "Does it have a stirrer?", "Does it have a lemon slice?"
- Categorical features with more than two values are split per value: "Is the color orange?" (yes: orange; no: black, white, green or yellow), "Is the color black?", "Is the glass a cylinder?", and so on.
- Numeric features get a threshold: "Is the volume at most 20 cl?", "Is the height at most 80.5 mm?". Choosing thresholds well does not have to be hard: sort the values and only try thresholds halfway between two consecutive values. If an orange measures 63 mm wide and the next apple 66 mm, then 64.5 mm is a candidate.
In our cocktail example, the volume has only three values (10, 15 and 25 cl), so we may just as well treat it as a category.
π The algorithm
You build a tree from the top down, one question at a time:
- π― Choose the question that best splits the current group.
- βοΈ Split the group into two subgroups according to that question.
- π Repeat this for every subgroup that is still mixed.
- π Stop as soon as a group is pure (all examples have the same label) or cannot be divided any further (all features are equal, or the tree is deep enough). That group becomes a leaf, with the most common label as its prediction.
Try it yourself below. The panel under the node at the top shows the cocktails in it; choose a question with βοΈ Choose a split. Repeat that for every group that is still mixed. Can you divide the data perfectly with as few questions as possible?
πͺ΅ The first split
Let's build a tree together. We start with all 8 cocktails: 5 times βΊοΈ not nauseous, 3 times π€’ nauseous.
Which question do we ask first? Let's follow our gut feeling and start with the shape of the glass: Is the glass a cylinder?
- Yes (cylinder): cocktails 1 and 2 β 2Γ βΊοΈ No
- No (not a cylinder): cocktails 3 to 8 β 3Γ βΊοΈ No, 3Γ π€’ Yes
The cylinder group is pure right away: none of them make you nauseous. The other group is still mixed, but that is fine: we split it further.

π The second split
The cylinder group becomes a leaf with the label "βΊοΈ No". For the other group, we look for a new question. Look at the six remaining cocktails:
| # | Shape | Color | Stirrer | Lemon slice | Volume | Nauseous? |
|---|---|---|---|---|---|---|
| 3 | Cone | White | No | No | 10 cl | βΊοΈ No |
| 4 | Trapezoid | Green | Yes | No | 15 cl | βΊοΈ No |
| 5 | Cone | Yellow | No | Yes | 15 cl | βΊοΈ No |
| 6 | Trapezoid | Orange | Yes | No | 15 cl | π€’ Yes |
| 7 | Cone | Orange | No | No | 15 cl | π€’ Yes |
| 8 | Cone | Orange | No | Yes | 10 cl | π€’ Yes |
Do you notice something? All the orange cocktails (6, 7 and 8) made us nauseous, and none of the others did. So the question Is the cocktail orange? splits this group perfectly:
- Yes (orange): cocktails 6, 7 and 8 β 3Γ π€’ Yes
- No (not orange): cocktails 3, 4 and 5 β 3Γ βΊοΈ No
Both groups are pure and become leaves. The tree is done.

With this tree, we can assess a new cocktail, for example an orange cocktail in a cone-shaped glass with a stirrer:
- "Is the glass a cylinder?" β No (it is a cone) β to the right
- "Is the cocktail orange?" β Yes β to the left
- Prediction: π€’ Nauseous. Better leave this one alone.
We just chose our first question on gut feeling. Was "Is the glass a cylinder?" really the best start? To answer that, you need to be able to measure how good a question is.
π Splitting criteria
π€ What makes a question good?
Think of the game Guess Who?: you have to guess which character your opponent picked, with as few yes/no questions as possible. "Is he wearing a hat?" is a bad question if only one character has a hat: if the answer is "no", you are hardly any wiser. A question that divides the candidates neatly into two halves gets you to the answer fastest (external link).
It is the same with a decision tree, except that we do not want to know who it is, but which label an example has. A good question produces subgroups that are as pure as possible: ideally only π€’ or only βΊοΈ.
- No uncertainty: a group with 100% βΊοΈ not nauseous. You know for sure what the answer is. The same goes for a group with 100% π€’ nauseous.
- Maximum uncertainty: a group with 50% π€’ and 50% βΊοΈ. You might as well toss a coin.
Compare three possible first questions for our eight cocktails:
| First question | "Yes" group | "No" group | For how many cocktails do you already know the answer? |
|---|---|---|---|
| π Is the glass a cylinder? | 2Γ βΊοΈ | 3Γ βΊοΈ, 3Γ π€’ | 2 of the 8, and the rest stays 50/50 |
| π¨ Is the cocktail orange? | 1Γ βΊοΈ, 3Γ π€’ | 4Γ βΊοΈ | 4 of the 8, and three quarters of the rest make you nauseous |
| π₯’ Does it have a stirrer? | 1Γ βΊοΈ, 1Γ π€’ | 4Γ βΊοΈ, 2Γ π€’ | 0 of the 8 |
The color is clearly the best first question: after one question, four cocktails are already known to be safe, and in the other group three of the four make you nauseous. Our own choice, the glass, was not bad, but taught us less. The stirrer teaches us next to nothing.
The algorithm makes exactly this comparison, but for all possible questions and with a number instead of a gut feeling. It measures how much uncertainty there is in a group, and picks the question that reduces that uncertainty the most. The usual measure for that uncertainty is called entropy.
π‘οΈ Entropy
The entropy of a group is a number that expresses how uncertain the label of a random example from that group is. It is 0 for a pure group (everyone has the same label) and highest when all labels occur equally often.
Entropy comes from information theory (external link), where it measures how much "surprise" or "disorder" there is in a distribution.
- A group with only βΊοΈ not nauseous has entropy 0: no surprise is possible, you know the label in advance.
- A group with 50% π€’ and 50% βΊοΈ has the highest entropy: with two labels, that is 1.
- A group with 75% π€’ and 25% βΊοΈ lies in between: still some uncertainty, but less than with a coin.
- With more than two labels (for example three kinds of fruit), the entropy is highest when every kind occurs equally often.
The more evenly the labels are distributed, the higher the entropy:
The entropy of a group with two labels: maximal (1) for a 50/50 distribution, 0 for a pure group.
You do not need to know the formula to work with the intuition: entropy is high for a mixed group and 0 for a pure one. Try it yourself in the demo below: change how many examples each class has and watch how the entropy changes.
π² The entropy formula
Call the share of class in the group (for example for our eight cocktails). The entropy of the group is then:
In words: for each class, you take how "surprising" it is (, large for a rare class) and weight that by how often it occurs (). A class that almost always occurs is hardly surprising and counts for little; a class that never occurs () you simply leave out. The unit is bits: with a 50/50 distribution, you need exactly one yes/no question (one bit) to know the label.
asks: to what power do you have to raise 2 to get ? So (because ) and (because ). For numbers between 0 and 1, the logarithm is negative, which is why the formula has a minus sign. No key on your calculator? Use .
Perfect mix π€’π€’π€’π€’βΊοΈβΊοΈβΊοΈβΊοΈ ():
Skewed distribution π€’π€’π€’π€’π€’π€’βΊοΈβΊοΈ (, ), with and :
Pure group π€’π€’π€’π€’π€’π€’π€’π€’ (): .
π Information gain
With entropy, we can now measure how much a question teaches us: how much purer do the groups become through the split?
The information gain of a question is the difference between the entropy of the group before the split and the average entropy of the subgroups after it. The higher the information gain, the better the question.
In that average, a large subgroup counts more than a small one: it is a weighted average. A question that makes a small group perfectly pure but hardly improves a large group is usually less useful than a question that cleans up both groups considerably.
In an ordinary average, all values count equally; in a weighted average, each value gets a weight that says how much it counts. Here, that weight is the size of the subgroup: you multiply the entropy of each group by the number of examples in it, divided by the total number of examples. If you split the eight cocktails into a group of 6 with entropy 1 and a group of 2 with entropy 0, the weighted average is , and not .
For our three candidate questions, that gives:
| First question | Information gain |
|---|---|
| π¨ Is the cocktail orange? | 0.549 bits |
| π Is the glass a cylinder? | 0.204 bits |
| π₯’ Does it have a stirrer? | 0.016 bits |
That confirms our intuition: the color is by far the best first question, and the stirrer teaches us almost nothing. At every step, the algorithm computes the information gain of all possible questions and simply picks the highest. Feel free to skip the calculation itself; if you want to see it, you will find it in the math section below.
π§Ύ Calculating the information gain
Call the group before the split and and the two subgroups, with the number of examples in a group. The information gain of a question is:
The term in square brackets is the weighted average of the entropy after the split: each subgroup counts according to its share of the original group.
Before the split, we have 5Γ βΊοΈ and 3Γ π€’, so and :
"Is the cocktail orange?" gives an orange group (cocktails 1, 6, 7, 8: 1Γ βΊοΈ, 3Γ π€’) with and a non-orange group (cocktails 2, 3, 4, 5: 4Γ βΊοΈ) with :
"Is the glass a cylinder?" gives a cylinder group (cocktails 1, 2: 2Γ βΊοΈ) with and a remaining group (cocktails 3 to 8: 3Γ βΊοΈ, 3Γ π€’) with :
In the same way, "Does it have a stirrer?" gives only 0.016 bits: the groups (1Γ βΊοΈ, 1Γ π€’) and (4Γ βΊοΈ, 2Γ π€’) are hardly purer than the whole group.
π Information gain as the decider
Watch below how the algorithm goes about it. Click the "Build" button at the top, or keep clicking the suggested split at the top of the table: you see the best question with its information gain (0.549) and, through +12 splits, all the other candidates, sorted from best to worst. After the color, the algorithm picks the shape of the glass, and it is done. Then try another dataset.
π² The Gini index: an alternative to entropy
Besides entropy, the Gini index is often used as a measure of how mixed a group is.
Imagine this thought experiment: you draw a random example from the group and give it a random label, drawn according to the distribution of the labels in that group. How often are you wrong? In a pure group never; in a 50/50 group half of the time. The Gini index is exactly that probability of a mistake.
Here is the probability that your label and the example happen to match; one minus that probability is the probability that you are wrong.
For a 50/50 group, the Gini index is ; for a pure group, it is . As with entropy, lower means purer, and the tree picks the question that reduces the weighted average Gini index the most.
In practice, entropy and the Gini index usually give the same or almost the same tree. The Gini index is a little faster to compute (no logarithm) and is therefore the default in popular software such as scikit-learn (external link). In this course, we mainly work with entropy, because its intuition ("how much uncertainty disappears?") is clearer. Compare both measures below: they call the same distributions pure or mixed, but on a different scale.
π Regression with decision trees
So far, our trees predicted a category: nauseous or not, apple or pear. That is called classification. A decision tree can also predict a number, for example how old someone in a photo is. That is called regression.
Suppose you have this training data of people with their real age:
| Person | π΄ Gray hair? | πΌ Pacifier? | π Age |
|---|---|---|---|
| 1 | No | Yes | 2 |
| 2 | No | Yes | 3 |
| 3 | No | No | 35 |
| 4 | No | No | 42 |
| 5 | Yes | No | 65 |
| 6 | Yes | No | 72 |
Two things change compared to classification:
- π A leaf does not predict the most common label, but the average of the numbers in that leaf. Whoever ends up in the leaf "pacifier: yes" gets (2 + 3) / 2 = 2.5 years as the prediction.
- βοΈ A good question does not make the groups "pure" but "closer together". The measure for that is the variance: how far, on average, do the values lie from their mean? Just as the tree maximizes the information gain in classification, here it maximizes the variance reduction: the drop in variance thanks to the split.
The variance is the usual measure of the spread of a group of numbers: how far, on average, do they lie from their mean? You take the difference between each number and the mean and square it (that way, too high and too low count equally and do not cancel each other out), and of all those squares you take the average. If all the numbers lie close together, the variance is small; if they lie far apart, it is large.
The six ages lie far apart (from 2 to 72 years), so the variance of the whole group is large. If we split on "Pacifier?", the two babies (2 and 3 years) end up together in a group with almost no spread. The other group (35 to 72 years) is still wide, and the algorithm splits it further on "Gray hair?":
Each leaf shows the average () of the people in it: 2.5 years for the babies, 68.5 years for those with gray hair and 38.5 years for the rest. Those are the tree's predictions.
Try it yourself. The panel under the node at the top shows the candidate questions with their variance reduction. Build the tree step by step:
βοΈ Calculating the variance
The variance of a group of numbers with mean is the average of the squared deviations from that mean:
The square makes sure that deviations upward and downward do not cancel each other out.
For the whole group, and
After the split on "Pacifier?", the group {2, 3} has mean 2.5 and variance 0.25, and the group {35, 42, 65, 72} has mean 53.5 and variance 237.25. Weighted by group size:
So the variance reduction is : exactly the number the demo above shows for this split. Of all possible questions, the tree always picks the one with the largest variance reduction.
ποΈ Practice
Now try building a decision tree yourself!
In the decision tree demo below, you can load different datasets and build decision trees on them yourself. You can let the tree grow step by step with the arrows, choose the splits by hand, or let the algorithm build it automatically.
Try the following exercises:
- Start with the dataset "π₯€ Does this drink make you nauseous?" and choose "Manual" as the criterion. Build the tree by choosing the best split each time. Can you classify the data perfectly with only two splits?
- Now switch to "Entropy" as the splitting criterion and let the algorithm build the tree automatically with the arrows. Does the algorithm choose the same first split as you did?
- Load the dataset "πΎ Tennis in this weather?" and build the tree automatically. Which feature does the algorithm choose first? Does that match your intuition?
- Try the "π₯ Quick triage" dataset, which has three possible outcomes instead of two. How does the tree deal with more than two labels?
- For one dataset, compare the result with entropy versus the Gini index as the splitting criterion. Do you get the same tree?
- Switch to a regression dataset such as "π¬ Film revenue". Notice how the leaves now predict an average value instead of a category. The tree keeps splitting until each leaf holds only one element. Click "Regularization" and require at least 2 data points per leaf. What changes?
π² From tree to forest: ensembles
A single decision tree overfits easily, and it is unstable: a small difference in the training data can already produce a very different tree. In practice, you therefore often train a whole forest of trees and let them decide together.
π³οΈ The wisdom of the crowd
In 1906, nearly 800 visitors to a livestock show in Plymouth estimated the weight of an ox. The statistician Francis Galton saw that the estimates varied widely, but that their median, 1207 pounds, was less than 1% off the real weight of 1198 pounds (Galton, 1907 (external link)). Errors in both directions cancel each other out, as long as the estimators guess independently of each other.
That same wisdom of the crowd also works for models. Suppose you have five trees that are each right in 70% of cases, and that make their mistakes independently of each other. If you let them vote, the majority is only wrong when at least three trees are wrong at the same time, and that happens much less often.
In the demo, such a forest votes on twenty new cases. Each row is a case, each cell the vote of one tree, and the last column the decision of the majority. Increase the number of trees and see how often the majority still gets it wrong.
With five trees, the majority is right in 84% of cases, and with eleven trees in 92%, while each tree on its own stays at 70%. If the accuracy per tree drops below 50%, voting makes things worse: the trees have to be better than guessing.
And it only works if the trees make different mistakes. If you train the same tree a hundred times on the same data, they all make the same mistakes and voting does not help. In the demo below, the trees resemble each other: at a similarity of 50%, they all say the same thing in half of the cases.
Now the forest no longer gets above 85%, however many trees you add. So a good forest needs trees that differ from each other.
An ensemble method combines the predictions of several models into one ensemble, by voting (classification) or averaging (regression). That works better than each model on its own, as long as the models are better than guessing and make different mistakes.
π Bagging: each tree gets its own sample
To get different trees from one dataset, you give each tree a slightly different version of the data. You draw a bootstrap sample by drawing as many examples as there are in the dataset, each time at random and with replacement: after every draw, the example goes back into the pot. That way, some examples are in it several times and others are missing.
Try it with the eight cocktails. Every click draws a new sample, and the algorithm from earlier builds a tree on it. A cocktail that was drawn twice also counts twice.
In the first sample, cocktail 8 appears three times and cocktails 3 and 7 are missing. Click a few times: each time, other cocktails are missing (about a third on average) and the tree changes with them. When cocktail 1 is missing (the only orange cocktail that did not make you nauseous), the question about the color is enough on its own.
Bagging (short for bootstrap aggregating) consists of three steps:
- π² Draw a number of bootstrap samples from the training data.
- π³ Grow a full tree on each sample, until every leaf is pure.
- π³οΈ Let the trees vote, or, for regression, take the average of their predictions.
π Why the forest overfits less
Below, on the left, you see a single tree on the fruit data, grown until every leaf is pure. It cuts out little rectangles around a few pieces of fruit that lie among another kind. On the right, a forest of trees votes, each grown on its own sample; the brighter the color, the more the trees agree.
Each tree in the forest makes its own little rectangles, depending on which pieces of fruit were in its sample (at the bottom you see the first four trees). In the vote, those rectangles disappear, because they lie somewhere else for every tree. The broad outlines remain: pears are tall and narrow, short fruit is mostly apples, and where apples and oranges are mixed, the forest hesitates.
The forest also does better on new fruit. If you leave out one piece of fruit at a time and predict it with the rest (leave-one-out), a single tree is right 14 out of 30 times and a forest of a hundred trees 19 times.
π² Random forest: drawing the questions at random too
For the cocktails, a tree grown on a bootstrap sample starts with the question about the color (the strongest feature) in about two out of three cases. As a result, the trees still look very much alike. A random forest therefore also draws the features at random: each node may only look at a few random features and picks the best question among them. A common choice is the square root of the number of features; with the five cocktail features, that is two.
In the demo, turn on Draw features. Under each question, you then see the two features that this node was allowed to look at, with the chosen feature in bold.
Without the random draw, four of the five trees start with the color; with it, only one does. Each tree on its own gets a little worse, because sometimes it may not use the best feature. Yet the forest usually gets better, because the mistakes of the trees now differ more. At the bottom, you can put together a new cocktail and see how each tree votes; they disagree about an orange cocktail in a cylinder glass.
A random forest needs little tuning. You let the trees grow fully, extra trees only cost computing time, and all the trees can be trained at the same time. The forest also shows which features are important: the feature importance adds up, for each feature, how much it reduced the uncertainty across all the trees.
π Ensembles in practice
For tabular data (rows and columns, such as sensor measurements or lab samples), random forests and gradient boosting (another kind of tree ensemble) are the standard choice. Recent comparisons (external link) find that tree ensembles often score better than neural networks on such data.
The price is interpretability. You can read one tree as a series of rules, but not hundreds of trees. The feature importance shows which features the model uses, but not how it arrives at one particular decision. If you have to be able to explain every decision, a single small tree remains a defensible choice.
β Strengths of decision trees
π Interpretability
The big advantage of decision trees is their transparency.
You see exactly why the model made a decision: follow the path through the tree.
You can even write the tree out literally as rules: IF color = orange AND shape β cylinder THEN nauseous.
That matters wherever a decision has to be justified:
- π¦ Financial sector: the GDPR (external link) protects citizens against fully automated decisions with a major impact, and obliges organizations to give meaningful information about how such a decision is made. If a bank turns down a loan, it must be able to say why.
- π₯ Health care: doctors want to understand why a system suggests a diagnosis before they adopt it.
- βοΈ Justice: in a court case, you must be able to explain how a decision was reached.
You can easily translate a tree into readable rules:
- If (income < β¬2000) AND (existing debt > β¬5000): β β loan rejected
- Otherwise, if (income β₯ β¬2000) AND (employment contract = permanent): β β loan approved
- Otherwise: β π further investigation needed
A decision tree is really a set of logical rules: every path from root to leaf is an "if ... and ... then ..." rule. That ties in with what we learned in the chapter on logic.
π§² Automatic feature selection
A tree picks the most informative features by itself. If you have a dataset with 100 features of which only 5 are really predictive, the tree mainly uses those 5. Features that contribute nothing (such as the stirrer in our cocktails) yield no information gain and are ignored automatically. That makes trees handy for exploring a new dataset: you quickly see which features matter.
π¦ Little data preparation needed
Unlike many other algorithms, a decision tree needs little preprocessing:
- π No normalization needed: a question with a threshold works just as well in centimeters as in millimeters (unlike nearest neighbors).
- π Mixed data types: a mix of categorical and numeric features is no problem.
- π Robust to outliers: an extreme value can at most shift a threshold.
β οΈ Weaknesses of decision trees
πͺ Limited expressiveness
Each question is about one feature. The tree can ask "Is the temperature higher than 20 Β°C?" or "Is the color orange?", but not "Is temperature plus humidity greater than 100?".
Yet some patterns are exactly such a combination. Suppose the real rule is: whoever has (height + weight) > 250 gets a certain diagnosis. That is a slanted line in the height-weight plane, and a tree can only draw horizontal and vertical lines. To approximate that slanted line, it needs a great many splits, and even then you get a staircase-shaped approximation.
π Instability
Decision trees are sensitive to small changes in the data. Adding or removing one data point can change the whole tree. That is because the first question (at the root) determines all the questions that follow: if that first choice changes because of a small difference in the data, the whole tree changes with it.
π Overfitting
Decision trees tend to "keep on asking". If you leave them alone, they split until every example in the training data has its own little leaf. We call that overfitting: the tree knows the training data by heart, but it has lost the general pattern. Every coincidence and every measurement error in the data gets a rule of its own. Compare it with a student who memorizes the answers instead of understanding the material: on an exam with new questions, that student is found out.
The simplest remedy is not to let the tree keep growing: limit the maximum depth or require a minimum number of examples per leaf (the Regularization button in the demo). How you find that balance between too simple and too complex is something we look at in the chapter on model evaluation.
π§ͺ Hands-on
In this Jupyter notebook, you train decision trees and a random forest yourself in Python, with the scikit-learn library. You also see how readable they are: you read the questions of one tree as rules, and a forest shows which features it uses most.

πΉοΈ Demos
Experiment further with the full simulators and demos featured above.





π£οΈ Feedback
Just like machine learning algorithms, we also love learning from your feedback to improve the course.
Let us know how informative and how difficult you found this chapter, and where it could be better.