…
…
AI Fundamentals · Lesson 14 / 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.
This time Elena does not want a model that asks questions one after another for the support program: "Let's give every student one score and invite the ones with a low score," she says. Your job is to build this score, find which students it misses, and then compare the three models you have on the same test set and write Elena which one you recommend and why.
By the end of the lesson you will be able to read the table below and recommend a model to Elena. The table shows the results of four approaches on 40 test students from grades.csv (fictional sample data, 200 students). The last two columns describe what the accuracy number does not tell you: how much work is done for one prediction, and how the model explains its decision.
| Model | Test accuracy (percent) | Mistakes (out of 40) | Work for one prediction | How it explains its decision |
|---|---|---|---|---|
| Baseline (everyone "passes") | 52.5 | 19 | none | no reason to give |
| Nearest neighbor (k = 5) | 85 | 6 | 160 distances | shows the 5 similar records |
| Decision tree (2 questions) | 77.5 | 9 | at most 2 comparisons | states one condition |
| Linear model | 90 | 4 | 3 multiplications, 1 comparison | states the score and the threshold |
You do not know the model in the last row yet. First we build it, then we weigh the four rows side by side.
Last lesson's decision tree asked questions one after another: "Fewer than 7 study hours a week? Attendance below 61%?" This lesson's model does not ask questions; it calculates. A linear model multiplies each feature by a number, adds up the products, and compares the total with a threshold. The number you multiply by is called a weight. The threshold is the boundary value at which the total changes the decision: if the total is equal to or greater than the threshold you get one decision, if it is smaller you get the other.
Let's put Elena's idea into numbers. The model we pick by hand is: score = 6 × study hours + 1 × attendance + 1 × homework score. If the score is 190 or more, the model says "passed"; if it is below, it says "failed".
Example 1 (case): The scores of three students
| Study hours | Attendance | Homework score | Score | Model | Actual |
|---|---|---|---|---|---|
| 10 | 88 | 62 | 60 + 88 + 62 = 210 | passed | passed |
| 5 | 64 | 61 | 30 + 64 + 61 = 155 | failed | failed |
| 8 | 85 | 53 | 48 + 85 + 53 = 186 | failed | passed |
The model is right about the first two students. It is wrong about the third: the score fell 4 points below the threshold, yet the student passed the course. Real data is noisy; students near the boundary will always produce errors like this.
Model: score = 6 × study hours + 1 × attendance + 1 × homework score, threshold 190. A student studies 10 hours a week, has attendance 70 and a homework score of 60. What does the model say?
A weight says two things. Its sign shows the direction: with a positive weight, the score rises as the feature rises; with a negative weight, the score falls as the feature rises. Its size shows the effect: if study hours go up by 1, the score goes up by 6; if attendance goes up by 1, the score goes up by 1. So in this model, one more hour of study a week does the same work as a 6-point increase in attendance.
To see a negative weight, let's step outside the case.
Example 2 (outside the case): Spam score
An email inbox gives every incoming message a score: score = 3 × number of suspicious words + 2 × number of links - 4 × known sender (1 if known, 0 if not). If the score is 5 or more, the message goes to the spam folder.
| Suspicious words | Links | Known sender | Score | Decision |
|---|---|---|---|---|
| 2 | 1 | no (0) | 6 + 2 - 0 = 8 | spam |
| 2 | 1 | yes (1) | 6 + 2 - 4 = 4 | normal |
| 0 | 3 | no (0) | 0 + 6 - 0 = 6 | spam |
The first two messages have the same words and the same link; the only difference is that the sender is known. The weight of -4 pulled the score from 8 to 4 and moved the message below the threshold. A negative weight is not a mistake: it means "as this feature rises, the decision moves to the other side."
But do not rush to say "study hours matter six times more than attendance." The scaling topic from lesson 8 applies here too: in the file, study hours range from 0 to 19 and attendance from 42 to 100. A weight is the effect per one unit of a feature; if the unit changes, the weight changes too. If we wrote attendance as a ratio between 0 and 1 instead of a percentage, we would need a weight of 100 to give the same score, yet the importance of attendance would not have changed at all. Before comparing weights with each other, look at the scale of the features.
So where did 6, 1, 1, and 190 come from? We tried them by hand. A real model finds the weights itself: it adjusts the weights step by step so as to reduce the error in its predictions. How this is done is the topic of lesson 16. For now, just see how a weight changes accuracy. We changed the weight of study hours, kept the other two weights and the threshold fixed, and measured the model on all 200 students:
| Weight of study hours | Correct predictions (out of 200) | Accuracy (percent) |
|---|---|---|
| 0 | 91 | 45.5 |
| 2 | 113 | 56.5 |
| 4 | 160 | 80 |
| 6 | 174 | 87 |
| 8 | 160 | 80 |
| 10 | 149 | 74.5 |
With weight 0 the model ignores study hours entirely and falls even behind lesson 13's baseline (everyone "passed", 111 / 200). At weight 6 accuracy reaches its highest value and falls again with larger weights: this time study hours drown out the other two features. Making a weight bigger does not improve a model on its own; the best value is somewhere in the middle. Of the 26 mistakes of the 87% model, 12 say "passed" to a student who failed and 14 say "failed" to a student who passed.
The code below does the same calculation with 20 students taken from the file. You do not need to write the code; change the weight and watch the three output lines. The student on the last line is the student near the boundary from Example 1.
Change the weight of study hours: how do the accuracy and the example student's decision change?
Pick a value; predict the output first, then look.
1weight = 02threshold = 1903# 20 students from grades.csv: (study hours, attendance, homework score, passed)4students = [(9, 51, 72, 0), (6, 72, 62, 0), (10, 88, 62, 1), (11, 91, 85, 1),5 (5, 76, 79, 0), (14, 49, 85, 0), (7, 97, 70, 1), (17, 67, 70, 1),6 (5, 64, 61, 0), (14, 77, 92, 1), (12, 82, 81, 1), (7, 83, 69, 1),7 (8, 85, 53, 1), (12, 89, 61, 1), (0, 76, 72, 0), (6, 65, 67, 0),8 (13, 71, 71, 1), (8, 42, 56, 0), (0, 80, 45, 0), (18, 93, 49, 1)]9correct = 010for hours, attendance, homework, passed in students:11 score = weight * hours + 1 * attendance + 1 * homework12 prediction = 1 if score >= threshold else 013 if prediction == passed:14 correct = correct + 115print("Correct predictions:", correct, "/", len(students))16print("Accuracy (percent):", round(100 * correct / len(students)))17example = weight * 8 + 85 + 5318print("8 hours, attendance 85, homework 53:", example, "passed" if example >= threshold else "failed")
Correct predictions: 9 / 20 Accuracy (percent): 45 8 hours, attendance 85, homework 53: 138 failed
Faded lines didn't run with this value. With weight 0 the model ignores study hours entirely and gets only 9 of the 20 students right. At weight 6 it reaches its highest value with 18 correct, and at 10 it falls to 15: a weight that is too large gives one feature more say than it deserves. The example student actually passed; at weight 6 the model says failed with a score of 186, at 8 it says passed with a score of 202. Of the two mistakes at 6, one is this student and the other is the student who studied 14 hours with attendance 49 and failed.
These numbers are not identical to the big table, because with 20 students a single student is worth 5 points. The shape is the same, though: accuracy is highest at a weight in the middle. The example student's decision also changed not because of the data but because of the weight you chose: at 6 it is "failed" with a score of 186, at 8 it is "passed" with a score of 202.
Where does the word "linear" come from? Reduce the model to two features: 5 × study hours + attendance, threshold 120. This model, which does not use homework at all, still gets 174 of the 200 students right. On a sheet of paper, draw study hours on the horizontal axis and attendance on the vertical axis. The points where the score is exactly 120 form a straight line: attendance 100 for someone who studies 4 hours, 80 for 8 hours, 60 for 12 hours, 40 for 16 hours. Above the line is the "passed" region, below it the "failed" region. The boundary by which the model separates the two decisions is called the decision boundary. In a linear model the decision boundary is always straight; the weights set the slope of the line and the threshold sets its position.
attendance (percent) · Calculation: attendance = 120 - 5 × hours
| — | Attendance on the boundary |
|---|---|
| 0 hours | 120 |
| 4 hours | 100 |
| 8 hours | 80 |
| 12 hours | 60 |
| 16 hours | 40 |
| 20 hours | 20 |
Read the line from left to right. For a student who does not study at all to get "passed", attendance would have to be 120; since attendance is at most 100, this never happens. A student who studies 20 hours needs only 20% attendance. If you put the three students from Example 1 into this two-feature model, the first is above the line (5 × 10 + 88 = 138), the second below (25 + 64 = 89), and the third above (40 + 85 = 125).
Its strength is right here: the model is just a few weights and a threshold, a prediction is a few multiplications and additions, and by reading the weights you can see what the model looks at. Unlike nearest neighbor, it does not need to keep the whole archive.
Its weakness comes from the same simplicity. A straight line cannot draw sharp steps or curved boundaries. If a course failed both students who study very little and students who study extremely much, the "passed" region would be a band in the middle; a single straight line cannot draw both edges of a band. The problem in our data is a step.
Three-feature model (weights 6, 1, 1; threshold 190). A student studies 16 hours a week, has attendance 59 and a homework score of 96. In this course everyone with attendance below 60 fails. What does the model say?
In the file there are 12 students with attendance below 60, and all of them failed. Our three-feature model says "passed" to 3 of them. A decision tree catches this rule with a single question: "Attendance below 60?" A linear model cannot, because in it a shortfall in one feature can always be made up by a surplus in another. However much you move the weights, the line stays straight; to draw a step, the type of model has to change.
To see the making-up in numbers, go back to the two-feature model.
Model: passed if 5 × hours + attendance ≥ 120. What is the lowest attendance a student who studies 10 hours a week needs to get "passed"?
Now you have three models: nearest neighbor, decision tree, and linear model. Before deciding which to choose, the first thing to do is clear: measure all three on the same data with the same split. As you learned in lesson 11, we shuffled the 200 records in grades.csv with a fixed seed and split them into 160 training and 40 test records.
We kept all three models simple on purpose. Nearest neighbor works with k = 5 and with scaled features as in lesson 8. The decision tree asks two questions: "Fewer than 7 study hours a week?" and "Attendance below 60%?" If either is answered yes, the prediction is "fails". The linear model computes this score: 8 × study hours + 2 × attendance + homework score; if the score is 286 or more, the prediction is "passes". We searched for the questions, the weights, and the threshold so as to give the fewest mistakes on the 160 training records only; we looked at the test set only in the final measurement. That is why the numbers differ a little from lesson 13 and the first half of this lesson: there we looked at all 200 records, and the tree's attendance threshold came out as 61. Because those who passed are the majority in the training set, the baseline says "passes" to everyone.
Example 3 (case): Three models, the same 40 students
| Model | Test accuracy (percent) | Correct (out of 40) | Mistakes (out of 40) |
|---|---|---|---|
| Baseline (everyone "passes") | 52.5 | 21 | 19 |
| Nearest neighbor (k = 5) | 85 | 34 | 6 |
| Decision tree (2 questions) | 77.5 | 31 | 9 |
| Linear model | 90 | 36 | 4 |
The first thing the table says is good news: all three models are far above the baseline, so all three have learned something from the data. The highest accuracy is the linear model's. Still, do not count this order as certain. In 40 students, one student is worth 2.5 points; the 5-point gap between the linear model and nearest neighbor is only 2 students. We repeated the same measurement with 21 different shuffles and searched again for the tree's questions and the linear model's weights in each shuffle's training set. The average test accuracy came out as 85% for nearest neighbor, 83% for the decision tree, and 89% for the linear model; in three of the shuffles nearest neighbor beat the linear model. What is more, in this data the result is decided by the features contributing together; this is the situation in which a linear model is most comfortable. In other data, the order can change.
Run two models side by side on the same students. You do not need to write the code; change the model and the student, and read the reason shown with the prediction.
Change the model and the student. Why did the models disagree on the third student? Whose reason fits the school's rule?
Pick a value; predict the output first, then look.
1model = "tree"2student = (10, 88, 62)3hours, attendance, homework = student4if model == "tree":5 if hours < 7:6 print("tree: fails (study hours below 7)")7 elif attendance < 60:8 print("tree: fails (attendance below 60%)")9 else:10 print("tree: passes (7 hours or more, attendance 60 or more)")11else:12 score = 8 * hours + 2 * attendance + homework13 if score >= 286:14 print("linear: passes (score", score, "≥ 286)")15 else:16 print("linear: fails (score", score, "< 286)")
tree: passes (7 hours or more, attendance 60 or more)
Faded lines didn't run with this value. For the first two students both models give the same decision; they just state the reason differently: the tree a condition, the linear model a score. The third student (18 hours, attendance 55) is where they split: the tree says "fails" at the attendance question; in the linear model 144 points come from studying and cover the low attendance, and with a score of 324 it says "passes". The tree's reason fits the school's rule "attendance below 60 fails".
Look closely at the third student: they study 18 hours a week but their attendance is 55%. The school's rule is sharp: if attendance is below 60%, the student fails. The tree states this rule with one question. In the linear model, though, the high study hours cover the low attendance and the prediction comes out "passes". The more accurate model gives a reason for this student that does not match the school's rule.
So accuracy is necessary, but it does not decide on its own. The second criterion is explainability: the ability of a model to state the reason for one of its decisions in a way a person can understand. When a student invited to the support program asks for the reason, the decision tree answers in one sentence: "You study fewer than 7 hours a week." The linear model shows the score and the threshold: "Your score is 270, the threshold is 286; if you studied 2 more hours a week you would pass the threshold." Nearest neighbor cannot give a rule; it can only show similar records.
Example 4 (case): Four records the linear model misses
| Study hours | Attendance | Homework | Score (8, 2, 1) | Linear model | Decision tree | Actual |
|---|---|---|---|---|---|---|
| 9 | 51 | 72 | 246 | fails | fails | failed |
| 14 | 45 | 83 | 285 | fails | fails | failed |
| 16 | 59 | 96 | 342 | passes | fails | failed |
| 14 | 49 | 85 | 295 | passes | fails | failed |
All four records have attendance below 60 and all four failed. The tree gets all four right; the linear model is wrong on the last two. The second record also escaped by a hair: a score of 285, only 1 below the threshold. In the whole file there are 12 students with attendance below 60; this linear model says "passes" to 2 of them.
Besides accuracy and explainability, three more criteria are weighed:
So build a good habit: measure the baseline first, then build the simplest model. Move to a more complex model only when the simple one is not enough and you can measure the gain.
Put the steps of choosing a model for a job 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
Match which option stands out in each of the situations below.
Match each situation to the most suitable option.
For each row, pick its match from the list, then check.
Some models cannot show the reason for their decisions at all. The three models we have seen in this lesson are readable; in models with thousands of weights, like the neural network you will meet in lesson 15, the question "why?" has no short answer. When a model makes a decision that affects a person, this is a matter of responsibility. The person affected by the decision should be able to find out what was looked at about them and should be able to appeal a decision they think is wrong. In a decision whose reason cannot be stated, an appeal has nothing to hold on to; and a mistake the model makes goes unnoticed because nobody is looking.
This does not mean that a model that cannot be read can never be used. If it is used, the features that most influenced each decision are shown for every decision and a person makes the final decision. Saying "the model is 91% accurate", on the other hand, does not count as an explanation: overall accuracy does not say why one particular student was rejected. Think about the situation below in a fictional scholarship committee.
Two models were measured for a fictional scholarship pre-screening. A has a test accuracy of 91%, but does not show the reason for its decisions. B is a two-question decision tree with a test accuracy of 88%. A rejected student asks "Why?" Which model do you recommend?
Pick an option and see what happens. There are no points; you can try the other options too.
The explainability you weighed in this lesson will come back in the responsibility lessons at the end of the course: who makes a decision and to whom its reason is told.
Two models are measured on the same eight students: one gives study hours a weight of 6, the other does not look at it at all. The threshold is 190 for both.
Outputhours attend homework actual | score (6,1,1) prediction | score (0,1,1) prediction
9 51 72 failed | 177 failed | 123 failed
6 72 62 failed | 170 failed | 134 failed
10 88 62 passed | 210 passed | 150 failed
11 91 85 passed | 242 passed | 176 failed
5 76 79 failed | 185 failed | 155 failed
14 49 85 failed | 218 passed | 134 failed
7 97 70 passed | 209 passed | 167 failed
17 67 70 passed | 239 passed | 137 failed
correct: | 7 / 8 | 4 / 8The first model gets 7 of the 8 students right, the second 4. The second model says "failed" to everyone; it does not tell students apart at all. The first model's only mistake is the sixth student: 14 hours of study, homework 85, attendance 49. The score comes out as 218 and the model says "passed"; the student failed because of absences. The sharp rule from Section 5 is at work here too.
The two-feature model (5 × hours + attendance ≥ 120) was tried at every point of a grid. G means passed, a dot means failed.
Outputattendance \ hours 0 4 8 12 16 20
100 . G G G G G
90 . . G G G G
80 . . G G G G
70 . . . G G G
60 . . . G G G
50 . . . . G G
40 . . . . G GThe boundary between G and dots descends as a straight line from the top left to the bottom right; it is the same as the line in the chart. Look at the bottom right corner: a student with attendance 40 who studies 16 hours is also in the "passed" region. If the school's rule "below 60 fails" applied, the whole of the 50 and 40 rows would be dots; a straight line cannot draw this step.
Calling the feature with the biggest weight "the most important feature". Write the same model three ways for the same student (8 hours, attendance 85, homework 53):
Outputattendance percent (85), weight 1 : 6 × 8 + 1 × 85 + 53 = 186 failed
attendance ratio (0.85), weight 1 : 6 × 8 + 1 × 0.85 + 53 = 101.85 failed
attendance ratio (0.85), weight 100: 6 × 8 + 100 × 0.85 + 53 = 186 failedThe first and third lines give the same score. The two models make the same decision. The weight went from 1 to 100, but attendance did not become a hundred times more important; only its unit changed. In the second line the weight stayed 1, so attendance adds 0.85 to the score instead of 85; a model like that says "failed" to almost everyone. Before comparing weights, bring the features to the same scale as in lesson 8.
Looking at a single test accuracy and saying "this is the best model". The gap between 90% and 85% is 2 students in a 40-student test, and in 3 of the 21 shuffles the order changed. Write next to the number how many students it was measured with, repeat the measurement with a few shuffles, and make the choice together with explainability, amount of data, prediction cost, and upkeep.
Next lesson: the model that stacks many small linear units, the neural network. You will see how it builds the "this and that" rule that a linear model cannot draw.
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.
Elena's condition: the decision must be statable to the student as a rule or a score. First the model that does not meet this condition is eliminated, then among the rest the one with the highest test accuracy is chosen.
OutputModel Test accuracy States a rule or a score? Candidate?
Nearest neighbor 85 no, shows similar records no
Decision tree 77.5 yes, a condition yes
Linear model 90 yes, a score and a threshold yesThe candidates are the decision tree and the linear model; the linear model is chosen. Its gain over the baseline is 90 - 52.5 = 37.5 points, that is, 15 students out of the 40 test students. But do not forget Example 4: for students with attendance below 60, the linear model does not follow the school's rule. The recommendation written to Elena could therefore be "the linear model, with one rule in front of it: if attendance is below 60, the student fails."