…
…
AI Fundamentals · Lesson 7 / 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.
A new question lands on the desk: "when is my scholarship paid". Elena flips through the archive: "A question like this came in before, and it went to aid. This one goes there too." In this lesson we will turn Elena's habit into a model, step by step, and build our first model.
By the end of this lesson you will be able to find, with pen and paper, which unit a new question should go to. For a question written as "exam password", the model will look at four examples in the archive, one by one, and tell you this:
Outputaid 4
residence 4
enrollment 2
it 1
Prediction: it | distance: 1The number on each line shows how far the new question is from that example, and the last line is the model's decision. To read this output, we will learn three things.
In this lesson you will:
In the last lesson we turned each question into a vector. Let's say our vocabulary is [scholarship, dorm, enrol, exam, password]. In "when is my scholarship paid", only "scholarship" starts with a word from the vocabulary, so its vector is [1, 0, 0, 0, 0]. To make a model do what Elena does by eye, we need just one thing: a number that says how similar two questions are. A model cannot read sentences; it can only compare lists of numbers.
We call this number the distance. The calculation has three steps: write the two vectors one above the other, take the difference of the numbers in the same position, drop the minus signs of the differences (this is called the absolute value), and add them all up. If the distance is 0, the two vectors are identical; the larger the number, the further apart the questions are.
Let's do it by hand once. The new question is [1, 0, 0, 0, 0], and the archive question "scholarship application scholarship result" is [2, 0, 0, 0, 0]. In the first position, the difference between 1 and 2 is 1; in the other four positions both vectors have 0, so there is no difference. Total: 1 + 0 + 0 + 0 + 0 = 1.
The code below does the same calculation. You do not need to read it line by line; step through it and watch the boxes on the right. Instruction: in which round did the `distance` box grow?
Run the code line by line: see which line runs next, the variable boxes and the output.
new = [1, 0, 0, 0, 0] old = [2, 0, 0, 0, 0] distance = 0 for i in range(len(new)): diff = abs(new[i] - old[i]) distance += diff print(distance)
The distance box grew only in the first round and stayed at 1: the two questions differ only in the count of the scholarship word, one said it once and the other said it twice. abs in the code is the command that drops the minus sign.
Example 1 (case): Three distances
Let's also compare the same new question with an enrollment question whose vector is [0, 0, 1, 1, 0]. In the third line we reverse the order: first the enrollment question, then the new question.
def distance(a, b): total = 0 for i in range(len(a)): total += abs(a[i] - b[i]) return total print(distance([1, 0, 0, 0, 0], [2, 0, 0, 0, 0])) print(distance([1, 0, 0, 0, 0], [0, 0, 1, 1, 0])) print(distance([0, 0, 1, 1, 0], [1, 0, 0, 0, 0]))
Output1
3
3With the enrollment question there is one difference in each of three positions (scholarship, enrol, exam), so the distance is 3. The last two lines gave the same result: it does not matter which vector you write first, because once you drop the minus sign, 1 − 0 and 0 − 1 become the same difference. A small number means a similar question, and a large number means a different question.
Now it is your turn. This time we use short vectors with three numbers; the method is the same.
What is the distance between [0, 2, 1] and [1, 0, 1]?
A single distance is not useful; the real work is to compare the new question with every question in the archive, one by one. The model calculates the distance to each training example, remembers the smallest distance it has seen so far, and at the end reports the unit of that example. This method is called nearest neighbor: the neighbor of the new question is the old question whose vector looks most like it. When Elena says "a question like this came in before", this is exactly what she does; the only difference is that the model measures similarity with a number and never skips an example.
Below is a small archive of four examples. Again you do not need to read the code; step through it and watch the boxes. Instruction: in which rounds did the `smallest` and `nearest` boxes change?
Run the code line by line: see which line runs next, the variable boxes and the output.
def distance(a, b): total = 0 for i in range(len(a)): total += abs(a[i] - b[i]) return total examples = [ ([0, 1, 0, 0, 0], "residence"), ([2, 0, 0, 0, 0], "aid"), ([0, 0, 1, 1, 0], "enrollment"), ([0, 0, 0, 0, 2], "it"), ] new = [1, 0, 0, 0, 0] nearest = None smallest = 999 for vector, unit in examples: d = distance(new, vector) if d < smallest: smallest = d nearest = unit print(nearest, smallest)
In the first round, the distance to the residence example came out as 2 and the model wrote it down (the starting 999 is a large number chosen to mean "I have not seen anything yet"). In the second round, the aid example was closer with 1; both boxes changed. The distance for the enrollment and it examples was 3, so the boxes did not change again. When the loop ends, the unit left in the box is the model's prediction: aid. The model did with numbers what Elena does by eye.
Now let's go back to the "exam password" question from the start of the lesson. With the vocabulary, its vector is [0, 0, 0, 1, 1]. This time the archive is a little different.
Example 2 (case): Where does the "exam password" question go?
def distance(a, b): return sum(abs(x - y) for x, y in zip(a, b)) # 1. Training: store the examples examples = [ ([2, 0, 0, 0, 0], "aid"), ([0, 2, 0, 0, 0], "residence"), ([0, 0, 1, 1, 0], "enrollment"), ([0, 0, 0, 0, 1], "it"), ] # 2. Vector of the new question: "exam password" new = [0, 0, 0, 1, 1] # 3. Calculate the distance to each example, keep the smallest nearest, smallest = None, 999 for vector, unit in examples: d = distance(new, vector) print(unit, d) if d < smallest: nearest, smallest = unit, d # 4. Prediction print("Prediction:", nearest, "| distance:", smallest)
Outputaid 4
residence 4
enrollment 2
it 1
Prediction: it | distance: 1You can check it by hand too: with the aid example [2, 0, 0, 0, 0] the differences are 2, 0, 0, 1, 1, total 4. With the it example [0, 0, 0, 0, 1] the only difference is in the exam position, so the distance is 1. It is the nearest neighbor, and the prediction is it. The model's whole job takes five steps. Put them in order yourself.
Put the steps of the nearest neighbor model in the correct order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
You may have noticed something odd here: the model calculated nothing while it was being trained. Training meant putting the examples into a list; all the work happened at prediction time. That is why nearest neighbor is called a lazy model. It is natural to think "a model works hard during training and thinks a lot", but with this model the opposite is true. It is like a student who does not study for the test and brings the book instead: memorizing nothing, they leaf through the book from start to finish for every question.
The good side is that teaching the model something new is very easy: you add a new labeled question to the list, and the model uses it in the next prediction. No retraining is needed.
Example 3 (case): Training is adding examples
The archive has only one aid example and one it example. The new question says "dorm" twice ([0, 2, 0, 0, 0]). Then we add a single residence example to the archive.
def predict(examples, new): nearest, smallest = None, 999 for vector, unit in examples: d = sum(abs(x - y) for x, y in zip(new, vector)) if d < smallest: nearest, smallest = unit, d return nearest, smallest examples = [([2, 0, 0, 0, 0], "aid"), ([0, 0, 0, 0, 1], "it")] new = [0, 2, 0, 0, 0] print(predict(examples, new)) examples.append(([0, 1, 0, 0, 0], "residence")) print(predict(examples, new))
Output('it', 3)
('residence', 1)The first prediction is it, but the distance is 3: because there was no residence example in the archive, the model gave the least bad option it had. When a single residence example was added, the prediction became residence and the distance dropped to 1. Nothing was recalculated.
There is a bad side too: as the archive grows, every prediction gets slower. In an archive of 600 questions, 600 distances are calculated for each new question; if the archive grows to 60,000 questions, each prediction needs 60,000 calculations. There is one more thing: the model does not question whether the examples in the archive are labeled correctly; it only copies. Below, match the consequences of these properties.
Match each situation with what happens in the nearest neighbor model.
For each row, pick its match from the list, then check.
The last row in the matching exercise is this model's most dangerous property. "A model says 'I don't know' when it does not recognize a question" is a very natural thought, but it is wrong. In the list there is always a smallest distance, and the model always picks it. The model does not learn to say "I don't know" on its own.
The new question is "when does the cafeteria open". Because none of the vocabulary words appear in it, its vector is [0, 0, 0, 0, 0]. What does the model do?
So when should we trust a prediction? Look at two things together next to the prediction: the vector and the distance of the nearest neighbor. In this archive, most questions have a nearest neighbor at distance 0 or 1; this shows that a truly similar question was found. If the distance is clearly larger than that, even the nearest neighbor is actually far away: "nearest" only means "closer than the others". If the vector is empty, the prediction cannot be trusted even when the distance comes out small, because there are no words to compare. In these two cases we apply the rule from lesson 3: the model leaves the question to Elena when it cannot be sure. We are not giving an exact limit here; "0 or 1" is an observation specific to this archive, and in another archive the limit would be different.
Below, try the model by changing the new question. You do not need to touch the rest of the code. In each try, look at two parts of the output: the vector at the start and the distance at the end.
Change the new question: which unit does the model name, and how close is the neighbor?
Pick a value; predict the output first, then look.
1vocab = ["scholarship", "dorm", "enrol", "exam", "password"]2examples = [3 ([2, 0, 0, 0, 0], "aid"),4 ([0, 2, 0, 0, 0], "residence"),5 ([0, 0, 1, 1, 0], "enrollment"),6 ([0, 0, 0, 2, 0], "courses"),7 ([0, 0, 0, 0, 1], "it"),8]9new = "dorm application date"10words = new.split()11v = [sum(1 for w in words if w.startswith(k)) for k in vocab]12nearest, smallest = None, 99913for vector, unit in examples:14 d = sum(abs(a - b) for a, b in zip(v, vector))15 if d < smallest:16 nearest, smallest = unit, d17print(v, "->", nearest, "| distance:", smallest)
[0, 1, 0, 0, 0] -> residence | distance: 1
Faded lines didn't run with this value. The model names a unit for every question. In the first two questions the neighbor is truly similar (distance 1 and 0). In the cafeteria question the vector is empty; even though the distance comes out small, the chosen unit is the unit of the example with the fewest words in the archive. In the last question even the nearest neighbor is at distance 3. Before trusting a prediction, look at the vector and the distance together; the last two questions should be left to Elena.
Do not let the distance of 1 in the cafeteria question mislead you. The reason is not similarity: the vector is empty, and the model picked the it example, which has a single word in its vector. The distance alone is not enough; the vector is read together with it. In the last question all the words are there, but no example looks like this mixture; the nearest neighbor is at distance 3. Both questions should go to Elena's desk.
Nearest neighbor does not belong only to the help desk. In lesson 2 we saw how a music app finds a recommendation for Alex: pick the listener with the most likes in common and recommend what that listener played. In that table there was only liked or not liked (1 or 0). Now let's build the same idea with distance.
Example 4 (outside the case): What is recommended to Lena?
In a music app, we have scores from 0 to 5 that each listener gave to four genres: pop, rap, classical, jazz. Each listener is now a vector of four numbers.
| Listener | Pop | Rap | Classical | Jazz |
|---|---|---|---|---|
| Hana | 5 | 1 | 0 | 2 |
| Jonas | 1 | 5 | 0 | 1 |
| Diego | 0 | 1 | 5 | 4 |
| Alex | 4 | 2 | 1 | 1 |
| Maya | 1 | 4 | 1 | 0 |
Lena, who just joined the app, has the scores (5, 1, 0, 1). The app calculates Lena's distance to each listener. With Hana the differences are 0, 0, 0, 1: distance 1. With Alex they are 1, 1, 1, 0: distance 3. With the same calculation Jonas comes out at 8, Maya at 9, and Diego at 13. Lena's nearest neighbor is Hana, and the app recommends the last song Hana listened to. The app does what the help desk model does: compare the newcomer with everyone, copy the "label" of the closest. Here the label is not a unit, but a song.
Now let's look at a side effect of this method. As Lena listens to the recommended songs, her scores move even closer to Hana's; as they get closer, her nearest neighbor is Hana again; and the recommendations from Hana are always of the same genre. Because every recommendation is copied from someone similar, the more Lena listens, the more she comes to resemble her match, and the circle narrows. What we called a "filter bubble" in lesson 2, you now see with its cause: the app does not know Lena's taste, it only copies the history of the person closest to her. The feeling that "the recommendation knows my taste" comes from here, but what is actually copied is someone else's history.
Lena has been listening only to the songs the app recommends for three weeks. Her list is always the same genre and she is getting bored. What should she do?
Pick an option and see what happens. There are no points; you can try the other options too.
This is not blame, it is the nature of the method: nearest neighbor always copies from someone similar. The way to open up the recommendations is to give the model new data with your own choices.
In this lesson we asked only a single neighbor. Trusting a single neighbor has a cost: if that neighbor is labeled wrong, the prediction is wrong too. Remember a real row in the archive: id 89, "Good afternoon, what's dorm sign-in time?", with the label courses. This is a dorm question, but its label was written wrong. If a new student asks "when is the dorm sign-in time?", the nearest neighbor is very likely this row, and the model sends the question to the courses unit. The model does not question whether the label is correct; it only copies.
There is also a common mistake in the calculation itself: adding up the differences without dropping the minus sign. The code below does this. You do not need to read the code; look at the output and the explanation under it.
a = [1, 0, 0, 0, 0] b = [0, 1, 0, 0, 0] distance = 0 for i in range(len(a)): distance += a[i] - b[i] print(distance)
Output0a is a scholarship question and b is a dorm question; the distance still came out 0. Why? The difference in the first position is +1 and in the second it is −1; when they are added, they cancel each other and 0 is left. Two questions that look nothing alike seem "the same", and the model may take a dorm question as the neighbor of a scholarship question. No error message appears; only the wrong neighbor is chosen. When you drop the minus sign, the differences become 1 and 1, and the correct distance is 2.
What if, instead of asking a single neighbor, we asked several and looked at the majority? Then a single wrongly labeled row could not decide the outcome alone. In the next lesson we will change the number of neighbors (it is called k) and the scale of the numbers, and see how the result changes.
Omar, who loves jazz and classical, joins the music table: (0, 1, 4, 5). The app calculates his distance to all the listeners.
listeners = {
"Hana": [5, 1, 0, 2],
"Jonas": [1, 5, 0, 1],
"Diego": [0, 1, 5, 4],
"Alex": [4, 2, 1, 1],
"Maya": [1, 4, 1, 0],
}
omar = [0, 1, 4, 5]
for name, scores in listeners.items():
d = sum(abs(x - y) for x, y in zip(omar, scores))
print(name, d)OutputHana 12
Jonas 13
Diego 2
Alex 12
Maya 12Diego is by far the nearest at distance 2; Hana, Alex, and Maya tie at 12, and Jonas is at 13. What Diego listened to is recommended to Omar. In this table there is only one person who loves jazz; all of Omar's recommendations will come from a single person.
Let's compare the question "when is my scholarship paid" [1, 0, 0, 0, 0] with the four examples from section 2 on paper.
OutputNew question: [1, 0, 0, 0, 0]
Example Vector Differences Distance
residence [0, 1, 0, 0, 0] 1, 1, 0, 0, 0 2
aid [2, 0, 0, 0, 0] 1, 0, 0, 0, 0 1
enrollment [0, 0, 1, 1, 0] 1, 0, 1, 1, 0 3
it [0, 0, 0, 0, 2] 1, 0, 0, 0, 2 3The smallest distance is 1, at the aid example. Prediction: aid. The distance is 1 and the vector is not empty; in this archive, a prediction we can trust.
Adding up the differences without dropping the minus sign. Positive and negative differences cancel each other; between the scholarship question [1, 0, 0, 0, 0] and the dorm question [0, 1, 0, 0, 0] the distance comes out 0, and two questions that look nothing alike seem the same. No warning appears; the model just picks the wrong neighbor. The right way: take the size of the difference in each position (1 and 1), then add: distance 2.
Next lesson: We will see how to ask several neighbors (k) instead of one, and how the scale of the numbers changes the distance.
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.