Please enable JavaScript to use CodeHS

AI + Machine Learning

How Decision Trees Work

AI you can explain

You already know how to play 20 Questions. A decision tree is the same game, played by a computer. Build one by hand, watch it learn from examples, and find out why people like AI that can show its work.

Machine learning ~20 min 5 interactives, no coding
? ? ? ? ? ? ? yesno
The Big Idea

A flowchart that learns

Have you ever played "Which animal am I?" You think of an animal. Your friend asks, "Do you live in water?" You say no. Then, "Do you have feathers?" Each answer crosses out a lot of animals. After a few questions, only one is left.

A decision tree works the same way. It is a set of yes-or-no questions, arranged like a flowchart, that ends in an answer. You start at the top, answer a question, follow the arrow, and keep going until you reach a decision.

So what makes it AI? Normally a person draws a flowchart. With machine learning, a computer builds the tree itself. (Machine learning means a computer finds patterns in examples instead of following rules a person wrote. How Do Computers Learn? goes deeper.) We give the computer lots of examples where we already know the right answer. Its job is to find the best questions to ask, and the best order to ask them.

Why people like trees: you can read them. If a tree says "no" to something, you can point to each question that led there. Many other kinds of AI cannot do that. Keep this in mind. It comes back later.

Play

20 Questions is a decision tree

Here is a tiny tree that knows 10 animals. Pick one in your head, but do not tell it. Then answer its questions honestly and see if it guesses.

Try it

Can the tree guess your animal?

It only knows these 10:

  • Blue whale
  • Dolphin
  • Octopus
  • Shark
  • Eagle
  • Ostrich
  • Giraffe
  • Rabbit
  • Lion
  • Tiger

Question 1

    See the whole tree

    Notice that the tree never asked more than 4 questions. Every answer cut the list of animals roughly in half. That is a powerful trick. Each yes-or-no question can split the choices in two, so 20 questions can tell apart more than a million things (2 doubled 20 times is 1,048,576). A good tree picks questions that split the choices evenly, so it does not waste any.

    Vocabulary

    The parts of a tree

    Computer scientists have names for each part. Tap a word to see where it lives on a small "Should I take an umbrella?" tree. Yes, the tree is drawn upside down, with the root at the top.

    Try it
    LEVEL 0 LEVEL 1 LEVEL 2 Yes No Yes No Is it raining? Are clouds dark? Take umbrella Take umbrella Leave it home

    Pick a word

    Tap one of the buttons to light up that part of the tree.

    Ask yourself: where would a leaf be on a tree in a forest? At the very ends of the branches. It is the same here. A real tree has leaves at the tips, and so does a decision tree.

    Build

    Grow your own tree

    Now you will do the computer's job. A farmer cut open 12 mangoes to check which were truly ripe. We also wrote down three clues for each one: does it have a red-yellow blush, does it feel soft, and does it smell sweet? We want a tree that guesses "ripe" or "not ripe" from the clues alone, without cutting the fruit open.

    Which question should come first? The computer looks for the question that sorts the mangoes into the cleanest piles. A clean pile is mostly one kind of mango. To measure this, we use a mixed-up score (data scientists call it Gini impurity). It works like this:

    • 0 means the pile is all one kind. Nothing is mixed up.
    • 0.50 is the most mixed-up a pile can be: half ripe, half not.
    • Lower is better. We want questions that leave piles with low scores.
    Try it

    Sort the mangoes with questions

    • circle = really ripe
    • square = not ripe yet

    Your tree so far

    0%

    Test your tree on a mystery mango

    See the raw data (12 mangoes)
    Each row is one mango. The last column is what the farmer found.
    MangoBlush?Soft?Sweet smell?Really ripe?

    What the computer just did

    That was the whole recipe. The computer tries every question, scores the piles each one makes, and keeps the question with the lowest average mixed-up score. Then it repeats the same steps inside each pile, until the piles are clean (or it decides to stop). Because it only picks the best question for right now and never plans ahead, this is called a greedy method.

    Real programs also handle numbers, like "Is it heavier than 300 grams?" They try many cut-off points to find a good one. The idea is the same.

    A warning: if your tree got 12 out of 12, that is great, but it only proves the tree knows these 12 mangoes. What about a mango it has never seen? That is the next section.

    Watch Out

    When a tree memorizes

    Imagine studying for a test by memorizing last year's answer key. You would ace last year's quiz. But this year's quiz has different questions, and memorizing does not help. You never learned the ideas.

    Trees can do the same thing. A tree that keeps asking questions can build a tiny leaf for every odd example, even the ones that are mistakes or flukes. This is called overfitting: the tree fits its practice data too closely, including the random noise.

    To catch this, data scientists keep some examples hidden during training. After the tree is built, they check it on those new examples (the test data). If the score on practice data is high but the score on new data is low, the tree memorized.

    Try it

    Slide the depth and watch both scores

    Each dot is a mango measured two ways: how soft it is and how strong its smell is. Orange circles are ripe. Blue triangles are not. A few dots are "oddballs" on purpose, because real data is messy. The tree learns from the solid dots, then gets tested on the hollow ones.

    • ripe, practice
    • not ripe, practice
    • hollow = new data
    3
    Practice score0%
    New-data score0%

    These scores come from one made-up set of dots, so another dataset would give different numbers. The pattern, though, shows up again and again in real projects.

    The fix is not "never use deep trees." It is to measure on new data, then pick the depth that does best there. Other fixes include forcing every leaf to hold a minimum number of examples, or pruning (trimming) branches that do not help.

    Why It Matters

    A tree can show its work

    Here is the superpower of decision trees. When a tree gives you an answer, you can see the exact path it took. That is called explainable AI: an AI whose reasons a person can read and understand.

    Many modern AI systems are more like a black box. Numbers go in, an answer comes out, and what happens in the middle is a huge pile of math. It may be very accurate, but it is hard to tell you why. (There are tools that give hints about a black box's reasons. They are useful, but they are usually less direct than reading a tree.)

    Try a low-stakes example. A school library lends out laptops using a tree. Change the facts about a student and watch both systems.

    Try it

    Library laptop loan: tree vs. black box

    Facts about the student

    Decision tree

      Black box

      The facts go in as numbers, get mixed through thousands of tiny calculations, and an answer comes out.

      Why? ???

      It may be right, but it cannot point to a simple reason.

      Why does that matter? If a student is turned down, the tree lets you say exactly why ("the last loan was late"). A person can check whether that rule makes sense, and fix it if it does not. Trust is easier when you can see the reasons.

      Be Careful

      A tree can learn an unfair rule

      Here is the catch. A tree learns from examples, so it copies whatever patterns are in them. That includes unfair patterns. This is called bias: a result that treats some groups unfairly because of the data or the way a system was built.

      Imagine a school club picked members for years. Without anyone planning it, students from one street got picked a lot more often, even though their grades were about the same. Now we train a tree to copy those past picks. (This data is made up, to show the idea.)

      Maple Street
      8 of 10 picked2 not picked
      Creek Road
      3 of 10 picked7 not picked

      Same average grades in both groups. Only the picks were different.

      Deleting the street column may not fix it. Other clues, like which bus a student rides, can quietly stand in for the street. These stand-ins are called proxies. People who build these systems check the results for each group, ask whether each question is a fair reason, and keep a human in charge of important decisions. Learn more in AI Bias and Fairness.

      Level Up

      From one tree to a forest

      One tree can be wobbly. A small change in the data can change its questions. So computer scientists grow many trees. Each tree looks at a slightly different slice of the data and ends up with different questions. Then the trees vote, and the most popular answer wins. A group of trees voting is called a random forest.

      It is like asking five friends whether a mango is ripe instead of one. Any one friend might be wrong, but the group is usually steadier.

      Try it

      Ask the forest

      Pick a mystery mango. Each of the five little trees looks at only some of the clues.

      Pick a mango above to start the vote.

      Real forests are bigger: often hundreds of trees, each trained on a random sample of the examples and a random choice of questions. Forests are usually more accurate than a single tree. The trade-off is that you give up some of the "easy to read" superpower. It is much harder to follow the reasoning of 500 trees than of one.

      Quick Answers

      Quick answers

      What is a decision tree in machine learning?

      A decision tree is a model that makes a decision by asking a chain of yes-or-no questions, like a flowchart. In machine learning, the computer builds the tree itself by studying labeled examples and choosing the questions that sort those examples most cleanly.

      How does a decision tree pick which question to ask first?

      It tries every available question, splits the examples into two groups for each one, and scores how mixed-up the groups are. A common score is Gini impurity, which you used in the lab. The question that leaves the groups the least mixed-up goes first. Then the same process repeats inside each group.

      What is overfitting?

      Overfitting means a tree has memorized its practice examples, including their random quirks and mistakes. It scores very well on them but worse on new data. Very deep trees overfit easily. Checking on new data and limiting the depth are two common fixes.

      Is a decision tree just a flowchart?

      They look alike. A person usually draws a flowchart from their own knowledge. A decision tree is learned by a computer from data, so its questions come from patterns in the examples it was given.

      Can a decision tree be unfair?

      Yes. A tree copies patterns in its training data, including unfair ones. Because it shows its questions, people can read the rule and spot problems more easily than with a black box. But someone still has to check for them.

      Do real companies use decision trees?

      Yes, in many places. Trees and forests are common for tasks where the data fits in a table, such as sorting spam or estimating risk. They are often used inside bigger systems, and the exact method varies by company.

      Check Yourself

      Quick quiz

      1. In a decision tree, what is a leaf?

      2. A tree scores 100% on its practice data but does much worse on new data. What probably happened?

      3. Why do people like decision trees for choices that affect others?

      Keep learning about how AI thinks

      You just built, tested, and questioned a decision tree. Next, see how computers learn from examples in general, or dig into what makes AI fair.

      Related: How Do Recommendation Algorithms Work?