…
…
AI Fundamentals · Lesson 10 / 31 · Measuring a model
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.
A student who says "I forgot my password, I can't log in" cannot wait. So Elena has opened a fast lane for IT questions, and the model has to decide how sure it must be before it sends a question there. A week later a second piece of news arrives: the IT unit says it has not received a single question from the filter that is supposed to work at 94 percent accuracy.
By the end of the lesson you will be able to build this table for Elena and say which row you would choose, with your reason. Each row puts the confidence limit for the model to say "IT" in a different place:
| Threshold | Sent to fast lane | False alarms | Misses | Precision | Recall |
|---|---|---|---|---|---|
| 0.2 | 8 | 4 | 0 | 0.5 | 1.0 |
| 0.4 | 5 | 2 | 1 | 0.6 | 0.75 |
| 0.6 | 4 | 1 | 1 | 0.75 | 0.75 |
| 0.8 | 2 | 0 | 2 | 1.0 | 0.5 |
None of the column names are familiar yet. You will work out each one yourself as the lesson goes on.
In the last lesson you measured the model with accuracy and saw where the mistakes went in the confusion matrix. Accuracy puts all mistakes in one bag: every wrong answer takes away one point. In Elena's fast lane, though, the two mistakes are nothing alike. One means a student cannot get into a course; the other costs the IT team one minute. In this lesson we look at just one question: is this question an IT question or not?
When the model says "IT" about a question, two things can be true: the question really is IT, or it is not. Let's call the second case a false alarm: the IT team deals with an unrelated question and sends it back. The model can also be wrong when it says "not IT": the question is actually IT. Let's call this a miss: an urgent question cannot enter the fast lane and waits in Elena's queue. The other two cases are correct: an IT question goes to the fast lane (a correct catch), and a question that is not IT falls into Elena's queue (a correct skip).
Example 1 (case): The table for 12 questions
Elena picked 12 questions to try; 4 of them are really IT. The model's decisions are arranged in a table like the one in the last lesson: rows are the truth, columns are the prediction.
| Model: IT | Model: not IT | |
|---|---|---|
| Actual: IT | 3 (correct catch) | 1 (miss) |
| Actual: not IT | 2 (false alarm) | 6 (correct skip) |
Four cells, four fates. Before you read the table, know which cell each case falls into.
Match each case with its cell in the 2×2 table.
For each row, pick its match from the list, then check.
Two separate questions can be asked of this table. The first looks at a column: of the 5 questions the model called "IT", how many were really IT? 3 of them. This ratio is called precision: 3 / 5 = 0.60. The second looks at a row: of the 4 questions that are really IT, how many did the model catch? 3 of them. This ratio is called recall: 3 / 4 = 0.75. False alarms pull precision down, and misses pull recall down.
The accuracy of the same table is (3 + 6) / 12 = 0.75, and this number adds up three kinds of error in one item. Precision and recall separate the type of error: the 2 false alarms are written into precision, and the 1 miss into recall. The two measures have the same numerator, the 3 correct catches; they differ in the denominator. If you mix up which one you are calculating, ask yourself: am I dividing by what the model said, or by what really happened?
On another day the model said "IT" for 10 questions, and 8 of them really were IT. The number of really IT questions that day was 16. Which is correct?
If the two measures measured the same thing, both numbers in this block would be the same. Yet on the same day, for the same model, one is 0.80 and the other 0.50: when the model says "IT" it can be trusted, but when it stays silent it misses a lot.
So how does the model decide to say "IT"? In lesson 8 you read the vote share as a rough confidence signal: if 3 of 5 neighbors say IT, the model's IT confidence is 3 / 5 = 0.6. You also know the threshold from lesson 1: if the confidence is equal to or greater than the threshold, the question goes to the fast lane; if it is smaller, it stays with Elena. The threshold is a setting dial, and you turn it, not the model. The 3 / 1 / 2 / 6 table above is the table you get when the threshold is 0.4.
If you raise the threshold from 0.4 to 0.8, so the model says "IT" only when it is very sure, how do the two measures change?
The code below has Elena's 12 questions: for each one, the model's IT confidence and whether the question is really IT. You don't need to read the code; just change the threshold and watch first the number of questions sent to the fast lane, then the two measures.
Change the threshold: which way do precision and recall go?
Pick a value; predict the output first, then look.
1threshold = 0.42# (model's IT confidence, is the question really IT?)3questions = [4 (1.0, True), (0.8, True), (0.6, True), (0.2, True),5 (0.6, False), (0.4, False), (0.2, False), (0.2, False),6 (0.0, False), (0.0, False), (0.0, False), (0.0, False),7]8caught = sum(1 for c, is_it in questions if c >= threshold and is_it)9false_alarms = sum(1 for c, is_it in questions if c >= threshold and not is_it)10missed = sum(1 for c, is_it in questions if c < threshold and is_it)11print("Sent to fast lane:", caught + false_alarms)12print("False alarms:", false_alarms, "| Missed:", missed)13print("Precision:", caught / (caught + false_alarms))14print("Recall:", caught / (caught + missed))
Sent to fast lane: 5 False alarms: 2 | Missed: 1 Precision: 0.6 Recall: 0.75
Faded lines didn't run with this value. With a threshold of 0.2 no IT question is missed (recall 1.0), but half of the 8 questions sent to the fast lane are false alarms. With a threshold of 0.8 there are no false alarms (precision 1.0), but 2 of the 4 IT questions are missed. In the values between, one gains while the other loses.
When you try the four values in turn, you see a pattern: as the threshold rises, the number of questions sent to the fast lane falls from 8 to 2, false alarms fall from 4 to 0, and misses rise from 0 to 2. There is no threshold at which both measures are 1.0 at the same time, because the confidences overlap: an IT question can stay at 0.2 while a question that is not IT gets 0.6. Wherever you draw the line, someone ends up on the wrong side. The threshold does not remove errors; it only chooses which kind of error will be made.
One more detail: at thresholds 0.6 and 0.8 the accuracy is the same, 10 of 12 questions (about 0.83). One has 1 false alarm and 1 miss, the other has 0 false alarms and 2 misses. Someone who looks at accuracy thinks the two thresholds are equal; for a student waiting in the fast lane, the second threshold means one more miss.
Which threshold is right? The numbers do not say; the job does. In Elena's fast lane a miss is costly: a student who forgot a password cannot get into a course while waiting in the queue. A false alarm is cheap: the IT team looks at the question for a minute and sends it back. So a low threshold is chosen; a few false alarms are better than one urgent question that gets away.
Example 2 (case): Turning errors into minutes
Elena estimated the time each error costs: a missed IT question costs the student and the team 30 minutes, and a false alarm costs 5 minutes. At each threshold in the table, she multiplied the false alarms by 5 and the misses by 30 and added them up. In the last column the costs are swapped: a false alarm costs 30 minutes and a miss costs 5.
| Threshold | False alarms | Misses | Fast lane cost (alarm 5 min, miss 30 min) | Reverse case (alarm 30 min, miss 5 min) |
|---|---|---|---|---|
| 0.2 | 4 | 0 | 4 × 5 + 0 × 30 = 20 min | 4 × 30 + 0 × 5 = 120 min |
| 0.4 | 2 | 1 | 2 × 5 + 1 × 30 = 40 min | 2 × 30 + 1 × 5 = 65 min |
| 0.6 | 1 | 1 | 1 × 5 + 1 × 30 = 35 min | 1 × 30 + 1 × 5 = 35 min |
| 0.8 | 0 | 2 | 0 × 5 + 2 × 30 = 60 min | 0 × 30 + 2 × 5 = 10 min |
For the fast lane the cheapest threshold is 0.2 (20 minutes); when the costs are reversed, the cheapest threshold is 0.8 (10 minutes). The model, the data, and the table are the same; the only thing that changed is which error is costly.
Example 3 (outside the case): Spam email filter
In another job, the scale tips the other way. Think of a filter that throws spam emails into the trash. Here, saying "spam" means sounding the alarm. An important email, for example an invitation to a job interview, falling into the trash is a false alarm, and it is very costly: the invitation is never read and the opportunity is lost. Seeing one ad in the inbox is a miss and costs a few seconds. Here a high threshold is chosen: the filter throws an email in the trash only when it is very sure.
Minutes only help up to a point; the real question is who pays the cost. A fictional scholarship committee wants to use a model to pre-screen applications. If the model says "not eligible" and the application is rejected without anyone reading it, the student pays the cost of the miss: they lose a scholarship they deserved, and often never learn the reason. The committee pays the cost of a false alarm: it reads a few extra files. When the costs are this unequal, the model should not give the rejection on its own. The model only puts a flag when it is very sure, and every application it is unsure about goes to a human. Everything that falls below the threshold lands on a human's desk; choosing the threshold means choosing whose work counts as more important than whose life.
A fictional scholarship committee will use a model to pre-screen applications. If the model says "not eligible", the application will be rejected. How do you set the threshold?
Pick an option and see what happens. There are no points; you can try the other options too.
In lesson 1 we said "when you are not sure, leave it to a human"; the threshold is that "sure" turned into a number. When you choose a threshold, ask three questions together: which error costs more, who pays for it, and where does what falls below the threshold go?
Now go back to the second piece of news in the case: the IT unit's filter is 94 percent accurate, but not one question has reached the unit. First look at the archive. The distribution of the 600 questions in the questions.csv file (fictional sample data) over the units is:
| unit | number of questions | share |
|---|---|---|
| enrollment | 159 | 26.5 percent |
| aid | 140 | 23.3 percent |
| courses | 136 | 22.7 percent |
| residence | 131 | 21.8 percent |
| it | 34 | 5.7 percent |
Four units are close to each other, and IT is far behind: only one in every 18 questions is IT. When the number of examples in the classes differs this much, it is called imbalanced data. It is not a data error; real life is often like this. A student who forgot a password is rarer than a student who asks a question during enrollment season.
When the question is "IT or not?", the archive falls into two classes: 34 IT and 566 not IT. Elena opened the filter's predictions and saw this: the filter had not said "IT" to a single question. It gave every question the same answer: "not IT".
34 of the 600 questions are IT. A filter says "IT" to none of them and "not IT" to all. What is this filter's accuracy, roughly?
The confusion matrix shows the situation clearly:
| Prediction: IT | Prediction: not IT | |
|---|---|---|
| Actual: IT | 0 | 34 |
| Actual: not IT | 0 | 566 |
Accuracy is (0 + 566) / 600, that is 94.3 percent. Now calculate recall: of the really IT questions, how many were caught? 0 of 34. Recall is zero. The filter's only job was to find IT questions, and it did not find a single one. Accuracy did not show this, because it counts all questions equally and the crowded class covers the small class.
So before every measurement, one question is asked: could this number be reached without learning anything? The accuracy of a model that gives every example the name of the largest class is called the baseline. For the question "IT or not?", the baseline is 94.3 percent. In the five-unit routing, the largest class is enrollment; a model that says "enrollment" to every question gets 159 of 600 right, and the baseline is 26.5 percent. Same archive, two different baselines: the number changes with the question you ask. The accuracy of a model means something only when it is written next to the baseline. In five units, 90 percent is a big gain; in the IT filter, 93 percent is worse than doing nothing.
In the code below, you change the number of IT questions. The model stays the same, it always says "not IT"; only the data changes.
How does the accuracy of a model that always says "not IT" change as the number of IT questions among the 600 changes?
Pick a value; predict the output first, then look.
1total = 6002it_count = 343# The model says "not IT" to every question4correct = total - it_count5caught = 06print("Accuracy:", round(100 * correct / total, 1))7print("Recall:", round(100 * caught / it_count, 1))
Accuracy: 94.3 Recall: 0.0
Faded lines didn't run with this value. As IT questions become fewer, the same useless model looks brighter: 99 percent with 6 IT questions. When the classes become equal (300 and 300), accuracy falls to 50 percent and no longer misleads. Recall is 0 in all four; it is the one that tells you the real state of the model.
To see what accuracy hides, you don't need a new measure: you apply recall to each unit separately. For each unit you ask, "how many of this unit's real questions were caught?"; this is called per-class recall. The lines of the report in the last lesson (residence 3 / 22, it 2 / 4) were exactly this.
Say a second filter catches 25 of the 34 IT questions and wrongly says "IT" to 20 questions. Its accuracy is (25 + 546) / 600, which is 95.2 percent; only 0.9 points higher than the first filter. The recall of the IT class has gone from zero to 73.5 percent. Accuracy hardly shows the real difference between the two filters; recall shows it. A warning: recall measured with 34 examples is rough. A single IT question moves the result by about 3 points; read the numbers of a small class with this margin in mind.
A five-unit model has 90 percent accuracy. Per-class recall: enrollment 95, aid 94, courses 93, residence 92, it 15. Which interpretation is correct?
Don't think "the small class is small, so it is unimportant". The IT class is 5.7 percent of the archive, but it is the reason the fast lane exists. Why is a small class hard? The nearest neighbor model decides by looking at the examples in the archive; if there are 159 enrollment questions against 34 IT questions, then among the neighbors of a new IT question, questions from other units easily take the majority. The solution has two sides. The first is data: collecting more labeled examples from the small class helps the model recognize it. The second is measurement: writing the result not with a single accuracy number, but together with the baseline and the recall of the small class.
Example 4 (outside the case): Fraudulent card transactions
A bank is examining 1,000 card transactions; 10 of them are fraudulent. A model that says "none is fraudulent" is right on 990 transactions: accuracy is 99 percent. This is also the baseline, 99 percent. Recall on fraudulent transactions is zero: none of the 10 fraudulent transactions was caught. In this job the person whose card was stolen pays the cost of a miss, and the cost of a false alarm is a verification message. A model showing 98 percent accuracy cannot boast here; it is one point behind a model that does nothing. First you look at the baseline, then at the recall of the fraud class.
In these three examples you don't need to read the code; each one does the calculation from the explanation by itself. Compare the output with the table.
The 12 questions of Example 1 are counted again with the threshold raised to 0.6. The question that is not IT with confidence 0.4 no longer goes to the fast lane. The Table line writes the four cells in this order: correct catch, miss, false alarm, correct skip.
# (IT confidence, is the question really IT?) questions = [ (1.0, True), (0.8, True), (0.6, True), (0.2, True), (0.6, False), (0.4, False), (0.2, False), (0.2, False), (0.0, False), (0.0, False), (0.0, False), (0.0, False), ] threshold = 0.6 caught = sum(1 for c, is_it in questions if c >= threshold and is_it) alarms = sum(1 for c, is_it in questions if c >= threshold and not is_it) missed = sum(1 for c, is_it in questions if c < threshold and is_it) skipped = len(questions) - caught - alarms - missed (, caught, missed, alarms, skipped) (, caught / (caught + alarms)) (, caught / (caught + missed)) (, ((caught + skipped) / (questions), 2))
Looking at a single number and feeling happy. If you lower the threshold to 0, the model says "IT" to all 12 questions. No IT question is missed and recall comes out as 1.0; the result looks perfect. But precision is 4 / 12, about 0.33: two of every three questions that go to the fast lane are false alarms, and the lane is no longer fast. Accuracy has the same trap: the sentence "the IT filter is 93 percent accurate" reads like a good result. Yet on the same data a model that always says "not IT" gets 566 / 600 = 94.3 percent; 93 percent means 558 correct out of 600, which is 8 questions behind a model that does nothing. The numbers are calculated correctly; what is wrong is leaving them alone. Next to every result, write three things: the baseline, the precision, and the recall.
Next lesson: we did all our measurements with held-out questions that the model had not seen. Why? We will look at what happens when you measure a model with the questions it has seen.
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.
OutputTable: 3 1 1 7
Precision: 0.75
Recall: 0.75
Accuracy: 0.83Compared with threshold 0.4, one false alarm is gone (from 2 to 1) and the number of misses stayed the same (1); that is why only precision went up (from 0.6 to 0.75).
The second filter in section 8 catches 25 of the 34 IT questions and gives 20 false alarms.
| Prediction: IT | Prediction: not IT | |
|---|---|---|
| Actual: IT | 25 | 9 |
| Actual: not IT | 20 | 546 |
caught, missed = 25, 9 # the really IT row alarms, skipped = 20, 546 # the really not IT row total = caught + missed + alarms + skipped print("Accuracy:", round(100 * (caught + skipped) / total, 1)) print("Recall:", round(caught / (caught + missed), 3)) print("Precision:", round(caught / (caught + alarms), 3))
OutputAccuracy: 95.2
Recall: 0.735
Precision: 0.556Of the 45 questions sent to the IT team, 20 are false alarms, but 9 of the 34 IT questions still get away. Because a miss is costly in the fast lane, the next job is to reduce these 9 misses.
A camera sorts out the defective glasses among 200 glasses passing on a belt; 8 glasses are really cracked. The camera catches 6 of the cracked ones and also says "defective" about 10 sound glasses.
| Camera: defective | Camera: sound | |
|---|---|---|
| Actual: defective | 6 | 2 |
| Actual: sound | 10 | 182 |
caught, missed = 6, 2 # the 8 glasses that are really cracked alarms, skipped = 10, 182 # the 192 glasses that are really sound total = caught + missed + alarms + skipped print("Recall:", caught / (caught + missed)) print("Precision:", caught / (caught + alarms)) print("Accuracy:", (caught + skipped) / total) print("Baseline:", (alarms + skipped) / total)
OutputRecall: 0.75
Precision: 0.375
Accuracy: 0.94
Baseline: 0.96The camera's accuracy (0.94) is below the baseline of "all are sound" (0.96), and yet the camera is useful: it catches 6 of the 8 cracks. A cracked glass can cut a customer's hand; throwing away a sound glass is a small loss. For this job, what decides is not accuracy but the recall of the defective class.