…
…
AI Fundamentals · Lesson 13 / 31 · Decision trees and linear models
PreviewIn this lesson you will
You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
The help desk has a new job this term: deciding which of a course's 200 students to invite to the support program. Elena does not only want a list; when an invited student asks "Why me?", she wants an answer to give. In this lesson we build a model with two questions that can explain every one of its decisions.
So far we have had one model: nearest neighbor. In lesson 7 we saw that it compares a new question with its look-alikes in the archive. But if a student asked "Why me?", what would nearest neighbor say? "The student most like you failed." That is a similarity, not a reason. The student cannot tell from it what to change to get a different result. Elena needs something else: the decision itself must be readable.
The data changes in this lesson too. The file grades.csv holds the records of 200 students in one campus course (fictional sample data). Each row has three features: weekly study hours, attendance percentage, and homework score. There is a single label: did the student pass or fail the course? Of the 200 students, 111 passed and 89 failed.
By the end of the lesson you will be able to build and read this table yourself:
| Step | Question | If yes | If no |
|---|---|---|---|
| 1 | Fewer than 7 study hours? | Leaf: failed | Go to question 2 |
| 2 | Attendance below 61%? | Leaf: failed | Leaf: passed |
In this lesson you will:
A decision tree is a model made of yes/no questions asked one after another. Each question looks at one feature and one threshold: in "Fewer than 7 study hours?" the feature is study hours and the threshold is 7. Depending on the answer, you either go to a new question or arrive at a prediction. The end where the prediction is written is called a leaf. When you reach a leaf, no more questions are asked; the model says whatever is written there.
Read the table above like a road map. Every student starts at the first row. If the answer is "yes", they go to the first cell on the right; if "no", to the second. If the second cell says "Go to question 2", they move down one row and do the same there. The questions are asked only with <: a student who studies exactly 7 hours answers "no" to "Fewer than 7?".
Try it yourself first. Use the table to follow one student's path.
Which leaf does a student who studies 16 hours a week and has 59% attendance reach in the tree above?
In Python, the same tree is nested if statements. You do not need to read the code line by line; step through it and watch which lines each student visits. Your task: Which students were never asked the second question?
Run the code line by line: see which line runs next, the variable boxes and the output.
def tree(study_hours, attendance): if study_hours < 7: return "failed" else: if attendance < 61: return "failed" else: return "passed" # (weekly study hours, attendance percentage) students = [(5, 76), (16, 59), (12, 61)] for study_hours, attendance in students: prediction = tree(study_hours, attendance) print(study_hours, "hours, attendance", attendance, "->", prediction)
The output has three lines: 5 hours, attendance 76 -> failed, 16 hours, attendance 59 -> failed, 12 hours, attendance 61 -> passed. Not everyone gets the second question; only a student who answers no to the first question does. The student who studies 5 hours a week has 76% attendance, but that number was never looked at: the path ended at the first question. The third student's attendance is exactly 61; the answer to "Below 61?" is no, so they reach the passed leaf.
This is where the tree is strong. The reason for each prediction can be read from the path in one sentence. For the second student you can say: "Predicted failed, because you study enough but your attendance is below 61%." That sentence also tells the student what to do. With nearest neighbor you could not form such a sentence. Below, match each student's path to the right explanation.
Match each student (study hours, attendance percentage) to the sentence that describes their path through the tree.
For each row, pick its match from the list, then check.
At first glance you might think a professor sat down and wrote these rules. They did not: nobody wrote them; the tree learned them from the data. To see how, let's look at what a question does to the data.
When a question splits the data into those who say yes and those who say no, this is called a split. After the split, the tree writes one prediction for each group: the majority of that group. If 7 of the 10 students in a group passed, the prediction is "passed" and the other 3 students are that group's mistakes. Add the mistakes of the two groups and you get the question's total mistakes. A good question is the one that leaves the fewest total mistakes. Ready-made tools use a slightly finer measure, but the idea is the same: make the groups as close to a single class as possible.
Example 1 (outside the case): Gym memberships
A gym wants to predict which members will renew. It has the records of 10 members; 6 renewed.
| Member | Visits per week | Membership month | Renewed? |
|---|---|---|---|
| 1 | 1 | 8 | yes |
| 2 | 0 | 1 | no |
| 3 | 1 | 2 | no |
| 4 | 1 | 5 | no |
| 5 | 0 | 7 | no |
| 6 | 3 | 2 | yes |
| 7 | 4 | 10 | yes |
| 8 | 2 | 6 | yes |
| 9 |
Let's try two candidate questions. A: "Fewer than 2 visits a week?" Five members say yes (1, 2, 3, 4, 5) and only 1 of them renewed; the majority is "did not renew", so 1 mistake. All 5 members who say no renewed; 0 mistakes. Total mistakes: 1 + 0 = 1. B: "Membership shorter than 3 months?" Three members say yes (2, 3, 6) and 1 of them renewed; 1 mistake. Of the 7 members who say no, 5 renewed; the majority is "renewed", so 2 mistakes. Total mistakes: 1 + 2 = 3. The tree picks A. If you had said "will renew" to everyone without asking anything, you would have made 4 mistakes; A brings that down to 1.
Now do the same calculation on the case data. Below are 12 students taken from grades.csv. The question is "Fewer than threshold study hours?" Change the threshold and watch how the two groups change.
Change the threshold: how do the two groups change, and at which threshold are the mistakes fewest?
Pick a value; predict the output first, then look.
1threshold = 72# (weekly study hours, result: 1 passed, 0 failed)3students = [(16, 0), (5, 0), (5, 0), (7, 1), (8, 1), (17, 1),4 (4, 0), (12, 1), (0, 0), (5, 1), (12, 1), (7, 1)]5def mistakes(group):6 passed = sum(group)7 return min(passed, len(group) - passed)8yes_group = [result for hours, result in students if hours < threshold]9no_group = [result for hours, result in students if hours >= threshold]10print("Question: fewer than", threshold, "study hours?")11print("Yes group:", len(yes_group), "total,", sum(yes_group), "passed")12print("No group:", len(no_group), "total,", sum(no_group), "passed")13print("Mistakes:", mistakes(yes_group) + mistakes(no_group))
Question: fewer than 7 study hours? Yes group: 5 total, 1 passed No group: 7 total, 6 passed Mistakes: 2
Faded lines didn't run with this value. At threshold 7, only 1 of the 5 students in the yes group passed and 6 of the 7 students in the no group passed: 2 mistakes in total, the best of these five thresholds. At threshold 3, only one student is left in the yes group and the no group stays mixed (4 mistakes). At threshold 12, more than half of the students who passed fall into the yes group and the groups get mixed again (5 mistakes).
At threshold 7 both groups are almost a single class: the yes group is mostly students who failed and the no group is mostly students who passed. When you make the threshold smaller or larger, the groups mix again and the mistakes go up.
When it learns, the tree does not limit this trial to one feature and five thresholds. It tries all three features and every threshold it sees, counts each one's total mistakes, and picks the fewest. The point of comparison is the baseline from lesson 10: if you said "passed" to everyone without asking anything, you would make 89 mistakes among 200 students. A good first question should bring that number down clearly. Make a guess before looking at the table.
Two questions are tried on 200 students. A: "Attendance below 60?" The yes group has 12 students, all failed; the no group has 188 students, 111 passed. B: "Fewer than 7 study hours?" The yes group has 71 students, 10 passed; the no group has 129 students, 101 passed. Which does the tree pick as the first question?
A's perfectly clean group looks attractive, but a question that separates 12 students and leaves the other 188 mixed only brings the baseline's 89 mistakes down to 77. Here is the best question for each feature across the 200 students:
| Question | Yes group | No group | Total mistakes |
|---|---|---|---|
| Fewer than 7 study hours? | 71 students, 10 passed | 129 students, 101 passed | 10 + 28 = 38 |
| Homework score below 61? | 63 students, 18 passed | 137 students, 93 passed | 18 + 44 = 62 |
| Attendance below 74%? | 75 students, 28 passed | 125 students, 83 passed | 28 + 42 = 70 |
So the first question is settled: fewer than 7 study hours? Attendance is not "unimportant" in this data; asked alone, it simply splits the students into more mixed groups than study hours does.
After the first question, the same search is repeated in each group. In the no group of 129 students, the best question turns out to be "Attendance below 61%?": of the 12 students who say yes, 1 passed, and of the 117 who say no, 100 passed. This group's mistakes drop from 28 to 1 + 17 = 18. A gain of ten students; worth adding the question.
In the yes group of 71 students, though, the best question lowers the mistakes from 10 to only 9. You do not have to split every group that can be split: adding a question for a single student makes the tree longer but does not capture a general pattern; most likely it learns that one student's special case. We stopped there and made that end a leaf. In the end the two-question tree gets 10 + 18 = 28 of the 200 students wrong and 172 right: 86%. The baseline was 111 of 200.
Put the steps by which a decision tree learns from data in the right order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
Example 2 (case): Measuring the tree on 12 students
Let's run the 12 students from the threshold block through the two-question tree. The table shows each student's values, their path through the tree, the prediction, and the real result.
| Hours | Attendance | Path | Prediction | Actual |
|---|---|---|---|---|
| 16 | 59 | 1st no, 2nd yes | failed | failed |
| 5 | 76 | 1st yes | failed | failed |
| 5 | 72 | 1st yes | failed | failed |
| 7 | 94 | 1st no, 2nd no | passed | passed |
| 8 | 75 | 1st no, 2nd no | passed | passed |
| 17 | 66 | 1st no, 2nd no | passed | passed |
| 4 | 82 |
The tree gets 11 of the 12 students right. The student it gets wrong studies 5 hours a week and passed anyway; their path ended at the first question and landed on the failed leaf. In that leaf, 10 of the 71 students were like this. A leaf is not a verdict; it is the majority of that group. Data is noisy, and a tree, like any model, makes mistakes.
What would have happened if we had not stopped in the yes group and had kept splitting every group? The largest number of questions a student can meet before reaching a leaf is called the tree's depth. Our tree's depth is 2. In lesson 11 we saw that nearest neighbor has a flexibility knob: k. In a tree that knob is called depth. As depth grows, the tree asks more questions, splits the groups into smaller pieces, and fits the training data more tightly.
We measured this honestly, as in lesson 11: we shuffled the 200 students with a fixed seed and split them into 160 training and 40 test students, built the tree with the training students only, and measured it on the test. Because a single student moves a 40-student test by 2.5 points, we repeated the split with 40 different shuffles and took the average. Change the depth and watch four numbers.
Change the depth: how do the number of leaves, and training and test accuracy (percent), change?
Pick a value; predict the output first, then look.
1depth = 22# average of 40 shuffles: depth -> (leaves, training, test)3results = {2: (4, 87, 83), 6: (19, 91, 82), 12: (45, 97, 81)}4leaves, training, test = results[depth]5print("Leaves:", leaves, "· Training:", training, "· Test:", test, "· Gap:", training - test)
Leaves: 4 · Training: 87 · Test: 83 · Gap: 4
Faded lines didn't run with this value. When depth goes from 2 to 12, training accuracy rises from 87 to 97 but test accuracy falls from 83 to 81; the gap widens from 4 points to 16 points. A deep tree asks questions that separate students one by one: this is memorization. Nobody can read the decision of a 45-leaf tree in one sentence either.
The deep tree reaches 97% in training, but it gains nothing on students it has not seen; on the contrary, it loses a little. The gap widens from 4 points to 16 points. Remember the diagnosis from lesson 11: a model that is very good in training and clearly worse on the test is memorizing. The deep questions no longer capture a pattern like "students with low study hours fail"; they pick out individual students with narrow ranges of all three features, and most of its leaves receive only one or two training students. On top of that, a 45-leaf tree cannot be read in one sentence; the reason we preferred a tree disappears.
The tree's strength is that it can be read: every decision is a path and every path is an explanation sentence. Elena can answer the invited student's "Why me?", and can even say what would have to change (Example 3). Its weakness comes from the same place: adding a question always raises training accuracy, so a tree memorizes easily. As it gets deeper, it both stops gaining on the test and loses its readability.
A third question was added to the two-question tree; 2 more students in the training set are now classified correctly. What happens to test accuracy?
In the next lesson, instead of asking questions, you will meet another model that adds up points, and we will decide which of the models we have to recommend.
A student who studies 9 hours a week and has 55% attendance was invited to the support program and asked "Why me?" Elena first follows the path, then writes two sentences.
OutputPath: question 1 (fewer than 7 study hours?) -> 9: no
question 2 (attendance below 61%?) -> 55: yes -> leaf: failed
Elena's answer:
"You study enough each week, but your attendance is below 61%; that is why
the model put you among the students at risk of failing. If your attendance
reaches 61%, the same tree takes you to the passed leaf."The second sentence is specific to a tree: which of the student's values would have to change for the leaf to change can be read from the path. Raising study hours would not change this student's leaf, because they already answer no to the first question.
The intern wrote the tree on a rule card: "1. If hours are below 7, failed. 2. If attendance is below 61, failed, otherwise passed." Two readings of the card for a student who studies 5 hours a week and has 76% attendance:
OutputCorrect reading (tree):
Rule 1: 5 < 7 -> failed. The path ends; rule 2 is not looked at.
Result: failed
Wrong reading (two separate rules):
Rule 1: 5 < 7 -> failed
Rule 2: 76 < 61 is false -> passed (overwrites the earlier result)
Result: passedSame card, same student, two different results. The only difference is who the second rule is applied to.
In the gym example, the yes group of question A had 5 members and only 1 of them (member 1, with an 8-month membership) had renewed. Let's try splitting this group with a second question.
OutputYes group (5 members, 1 renewed): 1 mistake
"Membership shorter than 3 months?" yes: members 2, 3 (0 renewed) -> 0 mistakes
no: members 1, 4, 5 (1 renewed) -> 1 mistake
total: 1 (no gain)
"Membership shorter than 8 months?" yes: members 2, 3, 4, 5 (0 renewed) -> 0 mistakes
no: member 1 (renewed) -> 0 mistakes
total: 0 (gain of a single membership)Applying the second rule to everyone. When the rule card in Example 4 is read as two separate rules, every student goes through both rules and the second rule overwrites the first. A student who studies 5 hours a week and has 76% attendance is first "failed", then "passed" by the second rule. This reading gives no error message; it just quietly sends everyone whose study hours are below 7 and whose attendance is 61 or higher to the wrong leaf. In a tree, the second question is asked only of those who answer no to the first. The way to write the card correctly is to move the second rule into the "otherwise" branch of the first: "1. If hours are below 7, failed; otherwise go to question 2."
grades.csv the first question is "Fewer than 7 study hours?" (38 mistakes), and the tree gets 172 of 200 right.Next lesson: you will build a model that adds up features with weights and gives each student a single score, and we will decide which of the three models to recommend.
Exercises and quiz are for members
This lesson has 7 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
| 12 |
| yes |
| 10 | 3 | 4 | yes |
| failed |
| failed |
| 12 | 76 | 1st no, 2nd no | passed | passed |
| 0 | 71 | 1st yes | failed | failed |
| 5 | 80 | 1st yes | failed | passed |
| 12 | 61 | 1st no, 2nd no | passed | passed |
| 7 | 83 | 1st no, 2nd no | passed | passed |
The second question lowers the mistakes from 1 to 0, but it does so by separating a single member. "Members with a membership of 8 months or more who rarely visit the gym renew" is not a pattern; it is one person's property. As with the yes group in the case, stopping is the wiser choice here: adding the question makes the tree longer, and it is not expected to help with new members.