…
…
AI Fundamentals · Lesson 12 / 31 · Memorizing and generalizing
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.
IT brought the second version of the router and presented it in one sentence: "91%, ready." Elena will walk into Monday's board meeting and wants a report card from the intern, that is, from you, independent of IT. In this lesson you will combine all the measuring tools you learned in lessons 9, 10, and 11 in a single report.
This lesson is a practice lesson. We are not learning a new model; we are auditing a real model with the tools you already have. First we will build the template of the report card with a short explanation, then do the audit step by step with ready-made cells. By the end of the lesson you will have a five-item report card you can hand to the board. This report card is the unit assignment of Unit 3; you will reuse it in the final report in lesson 31.
"91%" is a result, but it is not a report. You saw in lesson 9 that a single accuracy number hides where the mistakes pile up. You saw in lesson 10 that a model that learns nothing can also get high accuracy. You saw in lesson 11 that if the measurement is set up wrongly, the number shows a success that does not exist. The board will decide "should we use it?" For it to decide by looking at a single number is like sending a car on the road only because its engine runs.
A model report card is a short report that describes a model not with a single number but with five items read together. You learned each item in an earlier lesson; here you put them side by side for the first time.
Example 1 (case): The blank report card
OutputMODEL REPORT CARD: Help desk router, version 2
1. Accuracy and baseline ........................... (lessons 9 and 10)
2. Training versus test gap ........................ (lesson 11)
3. Weak unit and most confused pair ................ (lesson 9)
4. Costly error: which unit, which measure ......... (lesson 10)
5. Recommendation: what to fix, which questions stay with a personThere is also an order to filling in the report card. First you audit the measurement itself, because every item that comes from a dishonest measurement is wrong. In the second version, IT fixed the two problems we discussed in lesson 11: of the 600 questions it dropped the 12 that are exact repeats (588 different questions remained), shuffled the rest with a fixed seed (random.seed(42)), and split them into 470 training and 118 test questions. The features are again the six columns in features.csv, each divided by its largest value in the training set; k = 5. The measurement looks properly set up. Now you can move on to the numbers.
Put the steps you follow when preparing a model's report card 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
The model sent 107 of the 118 test questions to the right unit: accuracy 107 / 118, about 0.907. That is IT's "91%." Now set the point of comparison. In the training set, the most crowded unit is enrollment (132 of 470 questions). A model that learns nothing and says "enrollment" to every question would know the 22 enrollment questions in the test set: baseline 22 / 118, about 0.186. The model is far above the baseline, so it really has learned something. This is the opposite of the IT filter in lesson 10: there, 94% accuracy was below the baseline.
The second item compares training and test. The same model knows 434 of the 470 questions in the training set: 434 / 470, about 0.923. The gap between the two numbers is about 1.7 points.
Training accuracy is 0.923, test accuracy is 0.907. According to the diagnoses in lesson 11, what is the state of the model?
Below you will find ready-made code that calculates these two items. The table is built into the code; the code prints the diagonal, the row and column totals, and each unit's recall and precision.
Try it now· not graded; doesn't affect progress
Your task: first run the code as it is and read the numbers for items 1 and 3 of the report card. Then change a cell in the table; for example, make the 4 in the residence row 0 and the 21 next to it 25. Which numbers changed, and which stayed the same? Notice that changing one cell affects both a row and a column.
"91%" is the average over all units. Expecting the same success in every unit is like thinking that in a class with an average of 91, everyone got 91. Open the table.
Example 2 (case): The confusion matrix of version 2
| actual \ predicted | enrollment | aid | residence | courses | it | total |
|---|---|---|---|---|---|---|
| enrollment | 20 | 1 | 0 | 0 | 1 | 22 |
| aid | 1 | 30 | 1 | 0 | 0 | 32 |
| residence | 0 | 0 | 21 | 4 | 1 | 26 |
| courses | 1 | 0 | 1 | 27 | 0 | 29 |
| it | 0 | 0 | 0 |
Read the rows one by one. Each unit's recall, that is, how many of its own questions it sent to the right place: enrollment 20 / 22, aid 30 / 32, residence 21 / 26 (about 0.81), courses 27 / 29, it 9 / 9. The weak unit is residence: while the average is 0.91, residence questions stay at 0.81. The largest cell off the diagonal is also in the residence row: 4 residence questions went to courses. The most confused pair is residence → courses. This error shows up in the courses column too: the model said "courses" to 31 questions, and 4 of them were residence questions; the precision of courses is 27 / 31, about 0.87.
A single type of error affects several numbers at once. Below, change the number of residence questions that go to courses and watch three numbers.
Change the number of residence questions that go to courses: how do accuracy, residence recall, and courses precision change?
Pick a value; predict the output first, then look.
1dorm_to_courses = 42table = [3 [20, 1, 0, 0, 1],4 [1, 30, 1, 0, 0],5 [0, 0, 0, 0, 1],6 [1, 0, 1, 27, 0],7 [0, 0, 0, 0, 9],8]9# The residence row has 26 questions: 1 goes to it, dorm_to_courses go to courses, the rest go to the right place10table[2][3] = dorm_to_courses11table[2][2] = 26 - 1 - dorm_to_courses12correct = sum(table[i][i] for i in range(5))13residence_recall = table[2][2] / sum(table[2])14courses_precision = table[3][3] / sum(row[3] for row in table)15print("Accuracy:", round(correct / 118, 3),16 "| Residence recall:", round(residence_recall, 3),17 "| Courses precision:", round(courses_precision, 3))
Accuracy: 0.907 | Residence recall: 0.808 | Courses precision: 0.871
Faded lines didn't run with this value. Every residence question that stops going to courses moves onto the diagonal, into the residence cell. So a single fix moves three numbers at once: accuracy grows (from 107 to 109, to 111), residence recall grows (from 21/26 to 23/26, to 25/26), and because fewer wrong questions go to the courses column, courses precision grows too (from 27/31 to 27/29, to 27/27). The courses unit's own questions did not change at all; only the number of foreign questions arriving at it went down.
The table says where to look, not why. The most valuable part of the report card is here: opening each of the 11 mistakes and looking at why it went wrong.
Example 3 (case): Breakdown of the 11 mistakes
| Error | How many | Example questions (actual → predicted) | Cause |
|---|---|---|---|
| Residence → courses | 4 | "Dorm internet very slow. Can you help?" · "Hello, bathroom hot water's gone. Many thanks." | Label errors among the neighbors |
| A question that fits two units | 3 | "Deduct dorm fee from scholarship?" (aid → residence) · "Good afternoon, can tuition come from scholarship payment?" (enrollment → aid) · "Urgent: does scholarship cover dorm fees?" (courses → residence) | The question is ambiguous |
| One by one | 4 | "Good afternoon, updating my address in system?" (enrollment → it) · "What's dorm sign-in time?" (residence → it) | Various |
The four residence → courses errors follow the same pattern. All four are seven-word questions with only one residence word and no other clue. In the training set there are 12 records with this vector: 9 are labeled residence, 3 are labeled courses. Those three records are residence questions that came by email: "What's the dorm fee? Can you help?", "Urgent: what's the dorm fee? Many thanks.", "Good afternoon, steps for leaving the dorm?". The label error you saw in lessons 5 and 9 is still in the archive. All 12 records are at zero distance; as in lesson 9, the model lists tied distances in alphabetical order of the unit name, so "courses" stays in front, and three of the first five neighbors are those wrong records. The model works correctly; the data it learned from is wrong.
Three errors come from questions that fit two units. You saw in lesson 3 that even people send such questions to different units. On top of that, the test label of "Urgent: does scholarship cover dorm fees?" is courses. This one also came by email, and its label is wrong. Here the one that is wrong is not the model but the answer key. The remaining four are one-offs: in "Good afternoon, updating my address in system?", the word "system" counts as an IT word, so the question goes to the IT unit. The nearest neighbor of "What's dorm sign-in time?" is the mislabeled record you know from lesson 5 (id 89).
One more number to watch: 9 / 9 for it. Perfect? There are only 9 it questions in the test set; a single mistake would pull the recall from 1.0 down to 0.89, that is, 11 points. A number that comes from 9 questions is rough. On the report card, you write "it 9 / 9, few examples."
Match each error or result with the cause behind it.
For each row, pick its match from the list, then check.
While you are writing the report card, a message arrives from IT: "We also tried k = 7, and it knew 113 of the 118 questions. Put that on the report card." 113 / 118 is about 0.958, truly higher. But how was this number found? k = 7 was chosen by looking at the same 118 test questions. In lesson 11 you named this: when the test set gets mixed into the choice of settings, that is data leakage. 113 is the number for the setting that fits these 118 test questions; it does not show that it will hold on the questions that arrive tomorrow.
IT says: "With k = 7 we got 113 / 118. Put that on the report card." What do you do?
Pick an option and see what happens. There are no points; you can try the other options too.
The fourth item is the question from lesson 10: which error is more costly, and to whom? At the help desk, a residence question going to courses means a student with a cold room or a door that will not lock waits for an answer at the wrong desk. The measure for this error is residence recall (21 / 26): how many residence questions reach the right place. Courses precision (27 / 31) shows the same error from the other side: of every 31 questions that arrive at the courses unit, 4 are not their business.
The fifth item is the recommendation, and it has to be concrete. "The model should be improved" is not a recommendation; it does not say who will do what. The breakdown of errors gave you four concrete steps.
Example 4 (case): The filled-in report card (sample answer)
OutputMODEL REPORT CARD: Help desk router, version 2 (118 test questions)
1. Accuracy 107/118 (0.907). Baseline (always "enrollment") 22/118 (0.186):
the model has really learned.
2. Training 434/470 (0.923), test 0.907; gap about 1.7 points: generalizes.
Repeats dropped, sets separate.
3. Weak unit residence: 21/26 (0.81). Most confused pair residence → courses (4).
It 9/9 but only 9 questions: the number is rough.
4. Costly error: a residence question going to courses (the student waits).
Measure: residence recall 21/26; courses precision 27/31.
5. Recommendation: (1) Check the residence labels that came by email (3 wrong
records found). (2) For questions that fit two units and single-residence-word
questions, if the vote share is below the threshold, leave the question to
Elena. (3) Collect more examples for it. (4) k = 7 was found by looking at
the test set (113/118); it is not accuracy, and should be tried on new
labeled questions.Which of the recommendations on the report card most directly raises residence recall?
The report card is not specific to the help desk. You can fill in the same five items for any classifier.
Example 5 (outside the case): The report card of a spam filter
A school email system received 500 messages in a week; 40 of them are spam. The filter caught 30 of the 40 and also threw 6 important messages into the trash.
messages, spam = 500, 40 caught, false_alarm = 30, 6 missed = spam - caught important = messages - spam correct = caught + (important - false_alarm) trash = caught + false_alarm # messages the filter threw into the trash print("Accuracy:", correct, "/", messages, "=", round(correct / messages, 3)) print("Baseline:", important, "/", messages, "=", round(important / messages, 3)) print("Precision:", caught, "/", trash, "=", round(caught / trash, 3)) r = round(caught / spam, 3) print("Recall:", caught, "/", spam, "=", r) print("Missed:", missed, "| Important messages sent to trash:", false_alarm)
OutputAccuracy: 484 / 500 = 0.968
Baseline: 460 / 500 = 0.92
Precision: 30 / 36 = 0.833
Recall: 30 / 40 = 0.75
Missed: 10 | Important messages sent to trash: 6Fill in the report card: accuracy is 0.968, but a filter that filters nothing would also get 0.92; the difference is 4.8 points. The costly error here is the important message sent to the trash, that is, the false alarm: an exam announcement or a scholarship result could be lost. 10 spam messages landing in the inbox is annoying but cheap. So the measure to watch is precision (30 / 36). The recommendation comes from the threshold logic of lesson 10: the filter should throw a message into the trash only when it is very sure, and put the ones it is not sure about in a "suspicious" folder.
To show item 3 of the report card at a glance, you can chart each unit's recall.
% · 118 test questions (fictional sample data)
| — | Recall |
|---|---|
| enrollment | 91 |
| aid | 94 |
| residence | 81 |
| courses | 93 |
| it | 100 |
The shortest bar is item 3 of the report card. Do not forget that the tallest bar rests on only 9 questions.
Your job is not to decide whether to use the model, but to write what the board needs in order to decide well. This has a consequence: a risk that is not written on the report card is invisible. If you do not write the residence row, the board sees only "91%"; if you do not write how k = 7 was found, 113 / 118 will be taken as accuracy. If the board decides to use the model, some of the students' questions will wait at the wrong desk; taking this risk knowingly and taking it unknowingly are not the same thing. A good report card does not make the decision; it makes the cost of the decision visible.
An independent report card means producing the numbers yourself instead of taking them from IT. The code below rebuilds the steps IT described on questions.csv and features.csv (fictional sample data). You do not need to read the code line by line; the steps in the comments are the same as the sirala block in lesson 11.
import csv, random questions = {} for r in csv.DictReader(open("questions.csv", encoding="utf-8")): questions[r["id"]] = r["question"] rows, seen = [], set() for r in csv.DictReader(open("features.csv", encoding="utf-8")): text = questions[r["id"]] if text not in seen: # 1. Drop exact repeats seen.add(text) rows.append(r) random.seed(42) random.shuffle(rows) # 2. Shuffle with a fixed seed n = int(len(rows) * 0.8) train, test = rows[:n], rows[n:] # 3. Split 80% / 20% names = ["word_count", "enrollment_k", "aid_k", , , ] divisors = [((r[a]) r train) a names] vector(r): [(r[a]) / b a, b (names, divisors)] archive = [(vector(r), r[]) r train] distance(a, b): ((x - y) x, y (a, b)) predict(r, k=5): v = vector(r) ranked = ((distance(v, a), unit) a, unit archive) votes = {} dist, unit ranked[:k]: votes[unit] = votes.get(unit, 0) + 1 (votes, key=votes.get) (, (rows), , (train), , (test)) (, divisors) (, (predict(r) == r[] r test), , (test)) (, (predict(r) == r[] r train), , (train))
Reducing the report card to a single number. Compare two report lines:
OutputWeak: The model is 91%, very good, usable.
Good: Accuracy 107/118 (baseline 22/118); residence 21/26, the weakest unit.The first sentence is not a report card. In this sentence there is no baseline, so it is not clear what the 91% is good compared to. Training and test are not compared, the weak unit is not named, and there is no costly error and no recommendation. A report like this does not tell the board that one in five residence questions goes to the wrong desk. There is also the opposite: writing every number on the report card and interpreting none of them. Writing "residence 21/26" is not enough; you also write what it means ("a student with a cold room waits at the wrong desk") and what to do.
Next lesson: in the new unit we will meet models other than nearest neighbor; starting with the decision tree, we will apply the same report card to them too.
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.
| 9 |
| 9 |
| column total | 22 | 31 | 23 | 31 | 11 | 118 |
OutputUnique: 588 | Training: 470 | Test: 118
Divisors: [13, 3, 2, 2, 2, 2]
Test: 107 / 118
Training: 434 / 470The numbers are the same as IT's. Your independent measurement confirmed their report; the rest of the report card is built on these two numbers.
"Dorm internet very slow. Can you help?" went to courses. Here are the five neighbors the model looked at; all are at zero distance.
| Rank | Neighbor question | Channel | Label |
|---|---|---|---|
| 1 | What's the dorm fee? Can you help? | courses | |
| 2 | Good afternoon, steps for leaving the dorm? | courses | |
| 3 | Urgent: what's the dorm fee? Many thanks. | courses | |
| 4 | One quick question: dorm card lost. Thanks. | web | residence |
| 5 | What are dorm mealtimes? Can you help? | web | residence |
# (channel, label) pairs of the five neighbors, in the order of the table neighbors = [("email", "courses"), ("email", "courses"), ("email", "courses"), ("web", "residence"), ("web", "residence")] votes = {} for channel, label in neighbors: votes[label] = votes.get(label, 0) + 1 print("Votes:", votes) print("Prediction:", max(votes, key=votes.get)) email_courses = sum(1 for c, l in neighbors if c == "email" and l == "courses") print("Neighbors from email labeled courses:", email_courses)
OutputVotes: {'courses': 3, 'residence': 2}
Prediction: courses
Neighbors from email labeled courses: 3The votes are courses 3, residence 2; the model says "courses." When you read the three courses labels, you see right away that they are wrong: all three are residence questions, and all three came by email. Once these three labels are fixed, all four residence questions go to the right place.