…
…
AI Fundamentals · Lesson 11 / 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.
Elena measured the router on all 600 questions in the archive and saw "Accuracy: 1.0" on the screen. Instead of celebrating, she frowned, because no model makes zero mistakes. Sure enough, on the new questions that arrived the next week, the same model sent almost every second question to the wrong unit.
In lessons 9 and 10 we always measured the model with questions we had set aside, and we said "we will talk about why later." Today is that day. By the end of the lesson you will be able to read the table below yourself: the same model, with different values of k, measured on two separate sets of questions. For now the numbers are blank.
| k | Training accuracy (%) | Test accuracy (%) | Gap (points) |
|---|---|---|---|
| 1 | ? | ? | ? |
| 5 | ? | ? | ? |
| 116 | ? | ? | ? |
Elena's model works with k = 1 and stores the 600 questions in the archive. In lesson 7 you saw that nearest neighbor is a lazy model: in training it only writes the examples into its notebook. What happens if, to measure it, you ask it the same 600 questions again?
The model works with k = 1 and stores the 600 questions in the archive. If you ask it the same 600 questions to measure it, what will the accuracy be?
100% sounds nice, but it is an empty number. The model did not show that it knows anything; it only read back what it had written in its notebook. The questions that arrive at the help desk tomorrow are not in the archive. What we care about is how well the model does on those.
The solution is to split the data in two from the start. The examples the model stores, that is, learns from, are called the training set. The examples that are never shown to the model and are used only at the very end for measuring are called the test set. A common split is 80% training and 20% test: of 600 questions, 480 go to training and 120 to the test. The model is built with 480 questions, then each of the 120 test questions is asked as if it were a new question, and the predictions are compared with the real units.
Example 1 (case): The same model, two measurements
A small trial. The model stores four questions; each question is written as three numbers: how many aid, residence, and enrollment words it contains. First it is measured with these four questions, then with four new questions it has never seen.
| Set | Question (aid, residence, enrollment) | Actual unit | Prediction |
|---|---|---|---|
| Training | [2, 0, 0] | aid | aid |
| Training | [0, 2, 0] | residence | residence |
| Training | [0, 0, 2] | enrollment | enrollment |
| Training | [1, 1, 0] | residence | residence |
| New | [1, 0, 0] | aid | aid |
| New | [0, 1, 1] | enrollment | residence |
| New | [1, 0, 1] | aid | aid |
| New | [0, 0, 1] | enrollment |
On the questions it stored, the accuracy is 4 / 4 = 1.0; on the questions it has not seen, it is 3 / 4 = 0.75. The question that went wrong, [0, 1, 1], is the same distance from the residence and enrollment examples; the model chose the residence example that comes first in the list. The model is the same; only the exam paper changed. The second number is closer to the model's real condition.
You need to shuffle the rows before splitting. Archive files are often sorted by some order: by date, by channel, or by unit. If you take the last 120 rows without shuffling, the test set may not look like the rest of the archive. The shuffle is random, but you give it a fixed seed first (like random.seed(42) in Python). The same seed produces the same order every time; that way you can repeat today's measurement tomorrow with the same split, and a friend can reproduce your result exactly.
In the cell below, a small archive of 20 questions is shuffled, split in two, and the same model is measured separately on the two sets. You do not need to read the code; run it first, then set seed to 1, 2, 3, and 7. Does the training accuracy change? How much does the test accuracy move? Finally, set ratio to 0.5: what happened when the test set got bigger?
Try it now· not graded; doesn't affect progress
Training accuracy stays at 1.0 in every trial; test accuracy, on the other hand, moves with the seed: 0.75 for seeds 1, 2, and 3, but only 0.5 for seed 7. We learn two things. First, the model's real performance is lower than its training accuracy. Second, a test set of 4 questions is very jumpy: a single question changes the result by 25 points. As the test set grows, the number settles down.
On the real archive, when the same model (using all the words in the questions, k = 1) is split with seed 42, it knows all 480 of the 480 questions in training and 110 of the 120 questions in the test: accuracy 110 / 120, about 92%. An honest number instead of "Accuracy: 1.0".
Do not trust this number right away either. In the file questions.csv, 12 rows are exact repeats of another row: the same student sent the same question twice. When you shuffle, one copy of a repeat can land in the training set and the other in the test set. Then the test question is already written in the model's notebook, and the answer comes for free. Test-set information getting mixed into training or into the choice of settings is called data leakage. Leakage inflates accuracy with a success that does not exist.
In the split we just made, 8 of the 120 test questions were also in the training set, and the model knew all 8. Of the remaining 112 questions it knew 102: its accuracy on questions it had not seen is 102 / 112, about 91%. The difference is small here because there are few repeats. As the repeats multiply, the inflation grows. The remedy is simple: drop the repeats before splitting. Of 600 rows, 588 different questions remain.
Example 2 (case): Find the leakage, drop the repeats
In a list of eight questions, the first six are training and the last two are test. The code counts how many of the test questions are also in training; then it drops the repeats and does the same split again.
questions = ["when is the scholarship paid", "is dorm application open", "I forgot my password", "when is enrollment renewal", "when is the scholarship paid", "has the exam result been announced", "where do I get a transcript", "is dorm application open"] def leaked(items): # First 6 questions are training, the rest are test; count those in both train, test = items[:6], items[6:] return sum(1 for q in test if q in train) print("Rows:", len(questions), "Leaked:", leaked(questions)) # Drop repeats: only the first place each question appears stays unique = [] for q in questions: if q not in unique: unique.append(q) print("Rows:", len(unique), "Leaked:", leaked(unique))
OutputRows: 8 Leaked: 1
Rows: 6 Leaked: 0In the first list, "is dorm application open" is in row 2 (training) and in row 8 (test); that is the leaked question. Once the repeats are dropped, six different questions remain and none is in both sets.
There is one more sneaky kind of leakage: looking at the test set again and again. If you change k and look at the test accuracy each time, you end up choosing the best setting for those 120 questions; the questions have leaked into the model indirectly, and the number you report is optimistic. That is why the test set is looked at only at the very end, after all decisions have been made. To choose settings, you use a separate piece of the training set; this is called the validation set. The 12 held-out questions in lesson 8 did exactly this job.
Put the steps of an honest measurement 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 intern tried 1, 3, 5, and 7 for k, looked at the test accuracy each time, and reported the best one as "the model's accuracy." What do you say?
Pick an option and see what happens. There are no points; you can try the other options too.
Now let's turn to Elena's second complaint: why is a model that is perfect on the archive bad on a new question? The 100% that k = 1 gets in training is not a success, it is a copy. The model already holds the answer to every training question; it also repeats the noise you saw in lesson 8, the mislabeled questions, with the same confidence. Copying the training data together with its noise and then doing clearly worse on new examples is called memorization; its technical name is overfitting. Its opposite is generalization: the model working well on examples it has not seen before. The questions that arrive at the help desk tomorrow are not in the archive, so what we want is always generalization.
In nearest neighbor, k sets the balance between memorization and generalization. k is the model's flexibility knob: k = 1 is the most flexible model and bends to every example's quirks; as k grows, the model gets simpler and looks at the vote of the crowd.
Let's look at real numbers. This time we used the six features from lesson 8 (features.csv). We dropped the repeats that carry the same feature row; if we had not, the same row would land in both sets and the leakage from earlier would appear. 145 different rows remained. We shuffled them with a fixed seed, split them into 116 training and 29 test questions, and measured the same model with different values of k. We deliberately did not scale the features; the table is the result of this model, with these features and this split, not a general rule.
The k = 1 model scores 100% in training and 55% on the test. When k goes up to 5, training accuracy drops to 88%. What do you think happens to test accuracy?
Here is the whole measurement:
| k | Training accuracy (%) | Test accuracy (%) | Gap (points) |
|---|---|---|---|
| 1 | 100 | 55 | 45 |
| 3 | 91 | 69 | 22 |
| 5 | 88 | 72 | 16 |
| 9 | 84 | 66 | 18 |
| 25 | 78 | 69 | 9 |
| 51 | 61 | 38 | 23 |
| 116 | 29 | 31 | -2 |
percent · features.csv (fictional sample data): 145 different rows, 116 training and 29 test questions
| — | Training accuracy |
|---|
Read the table from top to bottom. At k = 1, training is 100% and test is 55%; the 45 points between them are the price of memorization. Elena's complaint about "every second question" comes from here. As k grows, training accuracy drops, because the model can no longer copy each question one by one. Test accuracy, on the other hand, first rises and reaches 72% at k = 5. After k = 51, both numbers collapse together. At k = 116, the whole training set votes, and the model says enrollment, the most crowded unit, to every question: 29% in training and 31% on the test. This is exactly the baseline from lesson 10. The gap is small, but both numbers are low: since the model never looked at the question, it has not learned anything. Such a model is called too simple (underfitting).
Two warnings. First, our test set has 29 questions; a single question is worth about 3 points. The difference between k = 3 and k = 5 is just one question, so trust the shape of the curve, not the individual numbers. When we repeat the same measurement with 40 different shuffles and take the average, test accuracy comes out at 62% for k = 1, 74% for k = 5, and 28% for k = 116: the shape is the same. Second, if you choose k by looking at this table, you have used the test set for tuning; in a real project you make the choice with the validation set.
The code below makes the same measurement with 15 training and 12 test questions taken from the archive. You do not need to write the code; change k and watch the three output lines.
Change k: how do the training accuracy, the test accuracy, and the gap between them change?
Pick a value; predict the output first, then look.
1k = 12train = [([11,0,0,1,0,0],"residence"), ([5,0,0,0,2,0],"courses"), ([6,1,0,0,0,1],"enrollment"),3 ([3,1,0,0,1,0],"courses"), ([7,0,0,0,0,1],"it"), ([8,0,1,0,2,0],"courses"),4 ([9,0,1,0,0,0],"aid"), ([5,0,0,0,1,1],"it"), ([10,0,0,0,1,0],"courses"),5 ([13,0,1,0,0,0],"aid"), ([9,0,0,0,2,0],"courses"), ([10,0,1,1,0,0],"residence"),6 ([9,0,0,0,0,0],"enrollment"), ([6,0,0,1,0,0],"residence"), ([12,0,0,0,0,0],"enrollment")]7test = [([3,0,0,2,0,0],"residence"), ([5,0,1,0,2,0],"courses"), ([4,0,0,0,0,1],"it"),8 ([10,1,0,0,0,0],"enrollment"), ([7,0,1,0,2,0],"courses"), ([9,0,1,0,1,0],"courses"),9 ([6,0,0,0,0,0],"enrollment"), ([13,0,2,0,0,0],"aid"), ([3,0,0,0,0,2],"it"),10 ([7,0,0,0,0,0],"enrollment"), ([5,2,0,0,0,0],"enrollment"), ([8,0,2,0,0,0],"aid")]11def distance(a, b):12 return sum(abs(x - y) for x, y in zip(a, b))13def predict(new, k):14 ranked = sorted((distance(v, new), unit) for v, unit in train)15 votes = {}16 for dist, unit in ranked[:k]:17 votes[unit] = votes.get(unit, 0) + 118 return max(votes, key=votes.get)19def accuracy(data, k):20 correct = sum(predict(v, k) == unit for v, unit in data)21 return round(100 * correct / len(data))22print("Training accuracy (%):", accuracy(train, k))23print("Test accuracy (%):", accuracy(test, k))24print("Gap:", accuracy(train, k) - accuracy(test, k))
Training accuracy (%): 100 Test accuracy (%): 50 Gap: 50
Faded lines didn't run with this value. At k = 1, training is 100% and test is 50%: the model is memorizing. At k = 5, training drops to 80% but test rises to 75% and the gap falls to 5 points; this is the setting that generalizes best. At k = 15, the whole training set votes, the model says courses to every question, and both accuracies collapse together.
The numbers here are not the same as in the big table, but the shape is the same: first memorization, the best point in the middle, and a collapse at the end.
The gap between training and test accuracy is a warning sign. If training is high and test is clearly lower, the model is memorizing. If both are low, the model is too simple. If both are high and close to each other, the model is generalizing. But before every number, question the measurement itself: if some of the test questions are also in training, or if no test was done at all, you cannot trust the table whatever it says.
Match each measurement result to the right diagnosis.
For each row, pick its match from the list, then check.
Leakage and memorization are not specific to the help desk.
Example 3 (outside the case): Cat or dog?
A fictional app says whether the animal in a photo is a cat or a dog. The team collected 1,000 photos, but to multiply the data it had also added cropped and rotated copies of many photos: of the 1,000 photos, 300 were copies of another photo. After the shuffle and split, one copy of the same cat landed in training and another in the test. Test accuracy came out at 98%. When the app went live, accuracy on users' new photos fell to 70%.
Why? The model had in fact seen most of the test photos: leakage. On top of that, in those familiar photos it may have memorized not the cat itself but the rug or the light in the background: memorization. The team grouped the copies and dropped them before splitting and repeated the measurement: test accuracy was 81%. The rest of the gap is most likely the photos users took in other settings and in other light; still, 81 is much closer to the truth than 98.
When the copies were dropped, the number fell from 98 to 81; does that mean the model got worse? In the exercises, you will explain this to the manager.
We diagnose the three rows of the table. The thresholds (a 20-point gap, 50% test) are rough limits chosen for this example.
Outputk Train Test Gap Diagnosis
1 100 55 45 memorizing: the gap is very large
5 88 72 16 generalizing: test is highest, gap is reasonable
116 29 31 -2 too simple: the gap is small but test is only 31The gap at k = 116 is the smallest, but that does not make it good. The gap shows memorization; whether the model has learned anything is told by the test accuracy itself.
To prevent leakage, 12 repeats were dropped and the remaining 588 questions were split with the same method.
OutputNumber of rows 600 → 588 (12 repeats dropped)
Training (80%) int(588 × 0.8) = int(470.4) = 470
Test 588 - 470 = 118
In both sets 0 questionsNow no test question is in training; the accuracy measured with this split is the model's real performance on questions it has not seen. The second version whose report card you will prepare in lesson 12 uses this split too.
Two mistakes are very common, and neither is noticed because the code gives no error.
Splitting without shuffling. If the archive is sorted by unit, for example four aid questions first, then four enrollment questions, and two residence questions at the very end, then setting aside the last 20% as the test makes the test set consist only of residence questions, and not a single residence question is left in the training set:
OutputSorted archive : aid aid aid aid enrollment enrollment enrollment enrollment residence residence
Training (8) : aid aid aid aid enrollment enrollment enrollment enrollment
Test (2) : residence residenceA model cannot predict a unit it has never seen; the accuracy comes out 0 and the model looks worse than it is. In lesson 9, Elena setting aside the last 100 questions worked because the archive was not sorted by unit. That is luck, not a method: shuffle with a fixed seed first, then split.
Choosing the setting by training accuracy. The setting with the highest training accuracy in the table is k = 1 (100%); but this setting gets only 55% on the test and is one of the worst at generalizing. Training accuracy shows how much the model can memorize; test accuracy shows how much it has learned. Choose the setting by the result on unseen questions, and always report the two numbers together.
Next lesson: you now have all the measuring tools. You will prepare the report card of the ready-made model that IT has brought.
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.
| Test accuracy |
|---|
| k=1 | 100 | 55 |
|---|---|---|
| k=3 | 91 | 69 |
| k=5 | 88 | 72 |
| k=9 | 84 | 66 |
| k=25 | 78 | 69 |
| k=51 | 61 | 38 |
| k=116 | 29 | 31 |