…
…
AI Fundamentals · Lesson 8 / 31 · First model: nearest neighbor
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 has two complaints about the nearest neighbor model: the question "Do I need an enrollment letter for my scholarship application, and will my scholarship stop?" went to the residence unit, and a 12-word scholarship question went to enrollment. There is no bug in the code. Elena asks you to try the model's two knobs, k and scaling, and to report which one fixes which problem.
We are not writing code in this lesson; we will turn the two knobs of the model you built in the last lesson. By the end you will have an experiment table like the one below: for each setting, how many of the 12 questions Elena set aside the model sent to the right unit. For now, the table is empty.
| Setting | k = 1 | k = 3 | k = 5 | k = 7 | k = 9 |
|---|---|---|---|---|---|
| Unscaled: correct out of 12 | ? | ? | ? | ? | ? |
| Scaled: correct out of 12 | ? | ? | ? | ? | ? |
In this lesson you will:
The model you built last time found the single example most like the new question and gave its unit. If that one example is right, there is no problem. But you saw in lesson 5: people write the labels, and people get tired and rush. In the archive you find wrongly labeled rows such as questions.csv id 89. Wrong or inconsistent records like these in data are called noise. A model that looks at a single neighbor copies the noise as it is; Elena's first complaint is exactly this.
The fix is simple: ask not one person but several. The method is called k-nearest neighbors. k is the number that says how many neighbors will be consulted. The model finds the k examples closest to the new question, each example casts a vote for its own unit, and the unit with the most votes becomes the prediction. This is called the majority vote. Last lesson's model was the k = 1 version of this method.
The vector of Elena's question is [2, 0, 1, 0, 0]: with the vocabulary order (scholarship, dorm, enrol, exam, password), scholarship appears twice and enrol appears once. There are 12 examples in the small archive; the five closest to the new question rank like this:
| Rank | Example vector | Distance | Unit |
|---|---|---|---|
| 1 | [2, 0, 1, 0, 0] | 0 | residence |
| 2 | [2, 0, 0, 0, 0] | 1 | aid |
| 3 | [1, 0, 1, 0, 0] | 1 | aid |
| 4 | [1, 0, 0, 0, 0] | 2 | aid |
| 5 | [1, 0, 2, 0, 0] | 2 | enrollment |
The example in first place is noise: its words match a scholarship question exactly, but its label is residence. When k = 1, that single example decides the prediction on its own. To count the votes, it is enough to look at the first k of the units ordered from near to far.
Example 1 (case): Counting the votes of five neighbors
# 1. Units of the neighbors, from near to far neighbors = ["residence", "aid", "aid", "aid", "enrollment"] k = 5 # 2. Count the votes of the first k neighbors votes = {} for unit in neighbors[:k]: votes[unit] = votes.get(unit, 0) + 1 # 3. Pick the unit with the most votes prediction = max(votes, key=votes.get) print(votes) print("Prediction:", prediction)
Output{'residence': 1, 'aid': 3, 'enrollment': 1}
Prediction: aidThe noisy neighbor still cast a vote, but its single vote was lost next to the three aid votes.
According to the ranking in the table, which unit does the model predict if k = 3 is chosen?
So the bigger we make k, the better the model gets? No. As k grows, far-away examples that do not look much like the question start to vote too. In Elena's small archive, 5 of the 12 examples belong to the enrollment unit; at a large enough k, this crowd wins the vote even though it has nothing to do with the question. When k equals the whole archive, that is k = 12, the model behaves as if it never looked at the question: it tells every question the most crowded unit.
The code below makes two small additions to last lesson's model: it sorts the examples from near to far and counts the votes of the first k. You do not need to read the code; change k and watch the two output lines.
Change k: how do the vote counts and the prediction change?
Pick a value; predict the output first, then look.
1k = 12new = [2, 0, 1, 0, 0]3examples = [4 ([2, 0, 1, 0, 0], "residence"),5 ([2, 0, 0, 0, 0], "aid"),6 ([1, 0, 1, 0, 0], "aid"),7 ([1, 0, 0, 0, 0], "aid"),8 ([1, 0, 2, 0, 0], "enrollment"),9 ([0, 0, 2, 0, 0], "enrollment"),10 ([0, 0, 1, 1, 0], "enrollment"),11 ([0, 1, 1, 0, 0], "enrollment"),12 ([0, 0, 3, 0, 0], "enrollment"),13 ([0, 2, 0, 0, 0], "residence"),14 ([0, 0, 0, 2, 0], "courses"),15 ([0, 0, 0, 0, 2], "it"),16]17def distance(a, b):18 return sum(abs(x - y) for x, y in zip(a, b))19ranked = sorted((distance(v, new), unit) for v, unit in examples)20votes = {}21for dist, unit in ranked[:k]:22 votes[unit] = votes.get(unit, 0) + 123prediction = max(votes, key=votes.get)24print("Votes:", votes)25print("Prediction:", prediction, f"({votes[prediction]}/{k})")
Votes: {'residence': 1}
Prediction: residence (1/1)Faded lines didn't run with this value. k = 1 gets stuck on the noisy example. At k = 3 and 5, aid wins, but one is 2/3 and the other 3/5: there is a majority, not unanimity. At k = 9 and 12, far-away enrollment questions take over the vote; although the question is a scholarship question, the prediction is enrollment.
The vote counts tell you more than the prediction. If all five of five neighbors say aid, the model is comfortable with this question. If three of five say aid, the prediction is still aid, but the neighbors are split. If you divide the winning unit's vote count by k, you get the vote share. In lesson 1 we compared a confidence value to a threshold and said "if you are not sure, leave it to a person"; the same idea works here. You set a threshold: if the winning unit did not get at least 80 percent of the votes, the question goes to Elena. The vote share is not an exact probability, it is a rough sign of confidence; still, it is better than no sign at all.
Example 2 (case): Leaving it to Elena when the majority is weak
votes = {"residence": 1, "aid": 3, "enrollment": 1}
k = 5
threshold = 0.8
prediction = max(votes, key=votes.get)
share = votes[prediction] / k
print("Prediction:", prediction, "Share:", share)
if share >= threshold:
print("Send to", prediction)
else:
print("Leave it to Elena")OutputPrediction: aid Share: 0.6
Leave it to ElenaWhat happens if the votes are equal? When two units get the same number of votes, it is called a tie. When k is an even number (2, 4), a tie comes up easily; that is why k is usually chosen as an odd number. But with five units, an odd number is not a guarantee either: at k = 5 the votes can split 2, 2, 1. The code does not give an error on a tie, it quietly picks one; so you need to set a rule for ties in advance.
With k = 4, the votes for a question came out aid 2, residence 2. What do you do?
Pick an option and see what happens. There are no points; you can try the other options too.
Elena's second complaint is different. This time she added the length of the question to the vector, that is, the word_count column in features.csv; she thought maybe long questions go to some units more often. A 12-word scholarship question came in, with two scholarship words in it, but the model sent it to enrollment. Below are three questions from the archive and the new question; to make it easy to follow, we show only two features.
| question | word_count | aid_k | unit |
|---|---|---|---|
| A | 11 | 0 | enrollment |
| B | 6 | 2 | aid |
| C | 9 | 0 | courses |
| new | 12 | 2 | ? |
Calculate the distance as the sum of the differences (word difference + aid_k difference). Which archive question is the nearest to the new question (12 words, aid_k 2)?
Why did this happen? In the features.csv file, word_count ranges from 3 to 13, while aid_k ranges from 0 to 2. The range of values a feature takes is called the scale of that feature. The word difference between two questions can reach 10; the difference in scholarship words is at most 2. If you add the two as they are, the feature with the large scale decides the total, and the voice of the small-scale one is not heard. And the one being muted here is the useful feature: the number of scholarship words points straight to the unit, while the length of the question says little about the unit. Every unit has short questions and long questions. A feature does not become more important because its numbers are big.
The solution is to bring the features to the same range before adding them. This is called scaling. The simplest way is this: divide each feature by its largest value in the archive. word_count is divided by 13 and aid_k by 2; that way both fall between 0 and 1. Now the biggest difference in one feature has the same weight as the biggest difference in the other.
Example 3 (case): Scaling a column
# 1. Word counts in the archive (A, B, C and the longest question) word_counts = [11, 6, 9, 13] # 2. Find the largest value largest = max(word_counts) # 3. Divide each value by the largest scaled = [round(x / largest, 2) for x in word_counts] print(largest) print(scaled)
Output13
[0.85, 0.46, 0.69, 1.0]The new question is scaled with the same divisors too: 12 / 13 ≈ 0.92 and 2 / 2 = 1. When the table is scaled, it looks like this (rounded to two digits):
| question | word_count | aid_k | unit |
|---|---|---|---|
| A | 0.85 | 0 | enrollment |
| B | 0.46 | 1 | aid |
| C | 0.69 | 0 | courses |
| new | 0.92 | 1 | ? |
Now calculate the distances again. The distance to B is about 0.46 + 0 = 0.46; to A it is 0.08 + 1 = 1.08; to C it is 0.23 + 1 = 1.23. The difference of 2 in scholarship words now counts as 1 whole unit, while the difference of 1 in word count counts as only 0.08. The nearest neighbor became B, and the prediction is aid. Scaling changed the ranking, because now the two features have an equal say.
Below, run the same calculation yourself. First keep scaling off and change the word count of the new question: the prediction follows the word count. Then turn scaling on and try the same values again.
Turn scaling on and off and change the word count of the new question: what does the prediction depend on?
Pick a value; predict the output first, then look.
1archive = [(11, 0, "enrollment"), (6, 2, "aid"), (9, 0, "courses")]2words = 123aid_k = 24scale = False5divisor = (13, 2) if scale else (1, 1)6nearest = None7for wc, a, unit in archive:8 distance = abs(words - wc) / divisor[0] + abs(aid_k - a) / divisor[1]9 print(unit, round(distance, 2))10 if nearest is None or distance < nearest[0]:11 nearest = (distance, unit)12print("Prediction:", nearest[1])
enrollment 3.0 aid 6.0 courses 5.0 Prediction: enrollment
Faded lines didn't run with this value. With scaling off, the result is enrollment if the question has 12 words, courses if 9 words, and aid if 6 words: the length makes the decision. With scaling on, the prediction is aid at all three lengths, because the scholarship words now enter the calculation with equal weight.
A warning: other knobs do not fix the scale problem. There are other distance measures too (for example straight-line distance, which adds up the squares of the differences and takes the square root); none of them fixes the scale problem alone, because all of them use the same raw differences. Raising k does not fix it either: five neighbors chosen by a wrongly measured distance still vote. The order is always the same: scale first, then calculate the distance, and count the neighbors' votes last.
k and scaling are not things the model learns from data; they are knobs you turn. Choices like these are called settings, and choosing them is tuning. There is no ready formula for the best setting: a small k loses to noise, a large k loses to the crowded unit, and the right value changes with the data. The model does not find the setting on its own either. What you do is try: test each setting on questions the model has not seen before and pick the one that gets the most right. For this, Elena set aside 12 questions from the archive; the model never sees these questions. Why we must test on questions it has not seen, we will see in lesson 11, and the name of the "number correct / total" ratio in lesson 9. For now we only count "how many correct out of 12".
The cell below has an archive of 15 questions and 12 questions set aside. Each question is written with 6 features, in the order of features.csv: the word count, then the counts of enrollment, aid, dorm, courses, and IT words. When scaling is on, the divisors are calculated from the archive: the word count is divided by 13, the courses words by 2, and the others by 1. In a few of the set-aside questions a word appears twice, so the scaled value is 2; that is not a problem, what matters is that the divisor comes from the archive.
Try it now· not graded; doesn't affect progress
Your task: set k to 1, 3, 5, 7, and 9; try each with scaling off (False) and on (True). Write the ten results into the table in exercise 3 of this lesson. Try it yourself first, then compare with the table below.
Example 4 (case): The filled experiment table
| Setting | k = 1 | k = 3 | k = 5 | k = 7 | k = 9 |
|---|---|---|---|---|---|
| Unscaled: correct out of 12 | 6 | 6 | 9 | 8 | 4 |
| Scaled: correct out of 12 | 9 | 11 | 10 | 8 | 4 |
Read the table row by row. Unscaled, the best setting is k = 5 (9 out of 12). With scaling, even k = 1 rises to 9, and the best setting becomes k = 3 (11 out of 12). In both rows, k = 9 gets only 4 right: when 9 of the 15 archive examples vote, the far-away and crowded unit, courses, takes the lead. So the two knobs fix different problems, and the best result comes when they are turned together.
Do not forget a limit: 12 questions is few. The difference between 11 and 10 is a single question; if we had picked 12 other questions, the order could have changed. This table is enough to say "scaled and a small k is good, a large k is bad", but not enough to say "k = 3 is definitely better than k = 5".
Match each problem with the knob that fixes it.
For each row, pick its match from the list, then check.
The same two knobs show up in other places too. Suppose a housing listings site shows you "homes like the one you are looking for". Each home is described by two features: monthly rent ($400 to $1,000) and distance to school (1 to 10 km). In an unscaled distance, the rent difference decides everything: a 3 km difference counts like a $3 rent difference. A home right next to school can look "far" from the home you want next to one that is hours from school but only a little closer in rent. When you divide each feature by its own largest value (rent / 1,000, km / 10), the two features get an equal say. You will do the calculation in the Examples section and in exercise 7.
The home you want is $500 in rent and 3 km from school. There are two listings: P ($515, 9 km) and R ($600, 3 km).
wanted = (500, 3)
listings = {"P": (515, 9), "R": (600, 3)}
for name, (rent, km) in listings.items():
raw = abs(wanted[0] - rent) + abs(wanted[1] - km)
scaled = abs(wanted[0] - rent) / 1000 + abs(wanted[1] - km) / 10
print(name, "raw:", raw, "scaled:", round(scaled, 3))OutputP raw: 21 scaled: 0.615
R raw: 100 scaled: 0.1In the raw calculation P looks much closer: the dollars of rent are bigger numbers than kilometers, so R's $100 rent difference counts as 100 while P's 6 km difference counts as only 6. When you scale, R takes the lead: its distance to school is the same, and its rent is a bit higher. For someone who will go to school and back every day, it is clear that R is more similar.
The divisors (13 and 2) come from the archive; the new question is scaled with the same divisors.
archive = [(11, 0, "enrollment"), (6, 2, "aid"), (9, 0, "courses")] divisor = (13, 2) new = (12 / divisor[0], 2 / divisor[1]) for wc, a, unit in archive: d = abs(new[0] - wc / divisor[0]) + abs(new[1] - a / divisor[1]) (unit, (d, 2))
Scaling the archive and leaving the new question raw. If question B in the archive has become (0.46, 1.0) while the new question is still (12, 2), the distance is abs(12 - 0.46) + abs(2 - 1.0), that is 12.54; for A it is 13.15, and for C it is 13.31. The code gives no error and even produces a prediction, but all the distances are meaningless: you added kilograms and grams again. Even if the prediction comes out as the right unit, it is luck. The new question is scaled with the same divisors as the archive (13 and 2); the divisors come from the archive, not from the new question.
Next lesson: We wrote the number correct into tables; in the next unit we will call it accuracy and look at where the mistakes go. First, the unit task: your own mini model.
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.
Outputenrollment 1.08
aid 0.46
courses 1.23