🏘️ Nearest Neighbors
🧑🤝🧑 Find the nearest examples
🍎 Classifying fruit
Suppose you have crates full of mixed fruit: apples, pears and oranges. You want to sort them by type of fruit, and you have a machine that measures the height and the width of each piece of fruit. For thirty pieces of fruit you already know the measured height and width, and the label (🍎 apple, 🍐 pear, 🍊 orange). How can you classify a new piece of fruit based on that height and width?
In the chapter on naive Bayes you already saw how an AI system automatically recognizes patterns in data to assign a label to a new data point. This is called classification: you have a dataset of examples (the training data) in which every example already has a label, like the type of fruit of each of the 30 examples here. Classification is a form of supervised learning, because you train the model with labeled examples. With naive Bayes you worked with probabilities, and the features were categorical (such as color or type, with only a limited number of possible values).
🎯 The nearest-neighbor principle
How can you classify a new example when the features are numerical (like height and width, which can take infinitely many possible values)? One of the most intuitive ways is simply: "look for data points that resemble it". When you see a new data point, you search the existing labeled data for the point that resembles it most, and you give the new point that same label.
In the fruit example, that means: measure the new piece of fruit and look in the dataset for the piece of fruit that comes closest in height and width.
This principle is the basis of the nearest-neighbor algorithm, a simple technique that works surprisingly well in practice. The assumption is that things with similar features usually also have the same label.
The fruit example may seem far removed from your own life, but you use this principle every day without thinking about it. When Netflix or Spotify recommends something to you, they look for users whose taste resembles yours and recommend what those people liked: your "neighbors". And it works just as well with text instead of fruit: you can attribute an unknown poem to the writer whose style comes closest to it (average sentence length, choice of words, how often little words like "and" or "however" occur). In this chapter we use fruit because there you can literally see the distances on a graph, but the idea is always the same: find what is most similar, and take its label.
Click or drag anywhere in the graph below to place a new piece of fruit with a certain height and width. On the right you see the predicted label (apple, pear or orange) and the nearest neighbor in the dataset. The distance between the new point and its nearest neighbor is shown too, in millimeters, so you can see how far the point lies from its nearest neighbor.
Does the new piece of fruit lie right among the apples in height and width? Then it is fairly clear: it is probably an apple. But what if the point lies somewhere between two kinds of fruit? Then the single data point that lies closest decides.
🗺️ Decision regions
A good way to understand the nearest-neighbor algorithm is to visualize which label every point in the space would get. You can "color in" every point in the plane with the color of the label the algorithm would predict there. That gives you decision regions: areas in which all points get the same label. The borders between those regions are called decision boundaries.
The nearest-neighbor algorithm produces special decision boundaries. Between two neighboring data points with different labels, the boundary runs exactly halfway, perpendicular to the line that connects the two points. The result is a "Voronoi diagram" (external link): every data point claims the area around it where it is the nearest neighbor.
In the demo below, the background shows the color of the label the algorithm would predict for every point in the space. Notice how the decision boundaries form geometric patterns between the different kinds of fruit. At the bottom left, for example, you see how the perpendicular line between an apple and a pear meets the one between that apple and an orange.
Create your own decision boundaries: click the pencil in the demo above, next to "Fruit dimensions", to switch on editing mode. You can now drag data points to another position. Watch how the decision boundaries move along immediately when you move points. What happens if you drag an apple in among the pears? You can also add new pieces of fruit with the buttons at the top and a click anywhere on the graph.
📏 Calculating distance
🤏 How do you measure closeness?
To determine which point lies closest to your new point, you need to be able to measure the distance. With one feature (for example only the weight) that is easy: the distance between two values is simply their difference, without a minus sign: .
The vertical bars () stand for the absolute value: the difference without taking the sign into account, so never negative. So , and also .
Try it out: drag the slider below across the range of a feature (e.g. the weight of the fruit). Below the slider you see the data points at their positions, and the colored bar shows which class the algorithm would predict at each position. In the table underneath you see the value of the nearest neighbor and the calculated distance . Watch how the prediction changes when you drag the slider across a boundary between two classes.
But what is "distance" when you look at several features at once, such as the height and the width of the fruit? Then there are several ways to measure it, just as with the distance heuristics from the chapter on heuristic search.
Two ways to measure the distance between two points: Euclidean distance (in a straight line) and Manhattan distance (along the grid lines)
The most widely used distance metric is the Euclidean distance: the straight-line distance you would measure with a ruler between two points on the graph. You calculate it with the Pythagorean theorem: the difference in width and the difference in height are the two short sides of a right triangle, and the distance is the long side (the hypotenuse); for two points and it is:
Sometimes measuring in a straight line makes less sense, for example when the features are of completely different kinds. Then you would rather add up the difference in each feature separately. That is the Manhattan distance, which you already saw as a heuristic. The Manhattan distance between two points and is:
Try it out: in the table view below you can experiment with the two distance metrics.
- Raise and lower the height of the test fruit with the second slider, and see how that changes the predicted class.
- Switch the distance metric at the top right between Euclidean and Manhattan distance (set the height to 84, for example), and watch how this affects the calculated distances and the prediction.
🧮 More variables
In practice you often have more than two features: besides height and width, for example, the weight of the fruit. Both distance metrics still work the same way then: every extra feature simply adds one more difference to the sum. In the demo above you can select "Iris flowers (full dataset)" to see this in action.
🧾 The distance formulas
For features, where and are the values of the -th feature of point and point , the two distance metrics become:
With you get exactly the formulas given above.
🔍 K-nearest neighbors
👥 More neighbors
So far you only looked at the nearest neighbor: the one point in the training data that lies closest to the new point. That is the simplest version of the algorithm, but it has a big drawback: a single mislabeled point or a single exception can completely upset the predictions around it. An apple that happens to lie among the oranges turns all the new fruit around it into "apples".
That is why we extend the algorithm to k-nearest neighbors (k-NN): it looks at the nearest points instead of just one. With , for example, you look at the three nearest neighbors and take the label that occurs most often among those three. That one stray apple is then outvoted by the oranges around it.
In the demo below you see that with , some individual pieces of fruit create whole "islands" in the decision regions. Set to 3: the little island at the bottom left disappears, because the apple that cut it off is now outvoted by the oranges around it.
🔄 How the algorithm works
The k-nearest neighbors algorithm classifies a new data point in four steps:
- 📏 Calculate the distance from the new point to every point in the training data.
- 📊 Sort all distances from small to large.
- 🔝 Select the nearest neighbors (the points with the smallest distance).
- 🗳️ Vote: take the label that occurs most often among those neighbors (majority vote).
🗳️ Voting
Suppose you look at the 3 nearest neighbors ():
- Neighbor 1 (very close) says: "Apple"
- Neighbor 2 (close) says: "Pear"
- Neighbor 3 (a bit further away) says: "Apple"
The algorithm follows one rule: the majority wins. There are 2 votes for "Apple" and 1 for "Pear", so the algorithm predicts: Apple. In a tie, like 2 against 2 with , the demo picks the class with the nearest neighbor.
Try it out: the table view below shows exactly how the vote works. Adjust to involve more or fewer neighbors, and change the values of the test point to see how the votes and the final prediction change. On the right you see the count per type of fruit.
🎚️ Choosing the number of neighbors
The choice of has a big influence on how the algorithm behaves.
With a low (such as 1 or 3), the model follows the data very closely, as if it "memorizes" every individual point. That makes it sensitive to noise: a single mislabeled point changes the prediction in its whole surroundings. The model then follows not only the real patterns, but also the chance exceptions in the training data. That is called overfitting.
With a high (for example ), the algorithm looks at the "average" of a larger neighborhood. The decision boundaries become smoother and more robust against noise, but you lose nuance: small groups and local patterns are missed. In the extreme case, when equals the total number of data points, the algorithm always predicts the most common class, wherever the new point lies. That is called underfitting: the model is too simple to see anything anymore.
Try to find the balance in the demo below. Watch how the decision regions (the background colors) change, and with them the predictions in those regions. The drop-down list at the top switches to another dataset.
- Set to 1: do you see how irregular the colored islands are? Every point gets its own region. At the bottom left, for example, you see an orange on its own island between apples and pears. In the "Signals" dataset, too, the graph becomes a patchwork of irregular regions.
- Set to 10: many details get smoothed out, and the regions become larger and simpler. In the "Signals" dataset with , only 2 large regions remain, while with there were still many small islands.
You run into this balance between too simple and too complex with every kind of model; the chapter on model evaluation goes into it more deeply. But which is the right one for your data? To know that, you need to be able to measure how well the model works; that is what we do in the next section.
🧐 Choosing k
How well does the model do, and which should you choose? To find out, you let the model make predictions for points whose correct label you already know, and you count how many it gets right. That percentage is the accuracy you already saw with naive Bayes. The only question is: which points do you use for that?
📝 Do not test on your training data
Imagine taking a test whose answers you have already seen beforehand. You would probably score 100%, but would you really have learned anything? No.
The same thing happens when you test a model on the data it was "trained" on. With nearest neighbors you see this quite literally: choose and classify a point that is already in the dataset, and the nearest neighbor is the point itself. You are guaranteed 100% accuracy on the training data, while that says nothing about how well the model recognizes new pieces of fruit. A model that overfits scores excellently on its training data, but disappoints on new data. So what you really want to know is: how well does the model perform on new, unseen data?
✂️ Data splits
The solution is to hold back part of your labeled data: you do not give it to the model, but keep it apart to test the model on. This is one of the most important techniques in machine learning, and it applies to every kind of model, not just to nearest neighbors.
- 📚 Training set: the study material. For nearest neighbors, these are the points the algorithm stores and compares new points with; for other algorithms (such as naive Bayes or neural networks), the model learns its parameters from them.
- 📝 Validation set: the mock exam. You keep these points apart: the model does not use them to look for neighbors, but you use them to measure how well the model does and to choose settings such as .
A common split is 80% training data and 20% validation data.
Try it out: below, the fruit dataset has been split into 21 points to compare against and 8 to test on. The filled points (🍎, 🍊, 🍐) are the training set; the hollow points with a dashed line are the validation set. On the right you see how many validation points the model gets right; misclassified points get a red ❌. Change and watch how the accuracy on the validation set changes along with it: that is how you choose a good for this data. You will see what the choice of normalization does in the next section.
If you want to report a fair final score at the end, you also keep a third part apart, which you never use to make choices: the test set, the real exam. Why that is necessary, and how cross-validation gets you a reliable score even from little data, is covered in the chapter on model evaluation.
📋 Confusion matrix
Accuracy does not tell the whole story: it says how many mistakes the model makes, not which ones. That is what the confusion matrix is for; you already saw one on the right in the demo above. With three kinds of fruit, it is a three-by-three table: each row is the actual type of fruit, each column is what the model predicted. On a validation set of 60 pieces of fruit, it could look like this:
| Predicted: 🍎 | Predicted: 🍊 | Predicted: 🍐 | |
|---|---|---|---|
| Actual: 🍎 | 18 ✅ | 2 ❌ | 0 ❌ |
| Actual: 🍊 | 3 ❌ | 15 ✅ | 2 ❌ |
| Actual: 🍐 | 0 ❌ | 1 ❌ | 19 ✅ |
What stands out?
- Apples and oranges are sometimes confused with each other (2 + 3 = 5 mistakes).
- Pears are never mistaken for apples, and only once for an orange.
- The accuracy is , but that one number hides the fact that it is mainly the oranges the model struggles with.
This way you see where the model goes wrong, and that helps you improve it: apples and oranges are both round and overlap in size, so an extra feature such as color could help here. From such a matrix you can also derive finer measures than accuracy, such as the precision and the recall per class; you see how in the chapter on model evaluation.
⚖️ Scaling variables
A distance adds up the differences in all features. That is only fair if those features are on a comparable scale, and that is far from always the case. Suppose you compare restaurants on their number of Instagram likes (from 0 to 10,000) and their average rating (from 0 to 5). A difference of 100 likes then weighs a hundred times more in the distance than the difference between a rating of 1 and 2, even though the latter tells you much more. The feature with the largest numbers dominates the distance, purely because its numbers are larger.
Even the chosen unit of measurement makes a difference. Suppose another machine measures not only the height (in millimeters) but also the weight of the fruit:
- In grams you get values such as 150 g, 180 g and 200 g: differences of tens of units.
- In kilograms that becomes 0.15 kg, 0.18 kg and 0.20 kg: differences of hundredths of a unit.
The same fruit, but a completely different distance. In the demo below, use the dataset selector at the top to switch between "Fruit weight (grams)" and "Fruit weight (kilograms)", and pay attention to the decision regions. In the grams version the weight dominates (steep, mostly vertical boundaries: the height matters much less); in the kilograms version the height dominates (almost horizontal boundaries: the weight hardly matters). Click anywhere in the graph and look at the distances in the table on the right; click again after each switch.
That is why in practice you normalize the features: you convert every feature to the same scale, without units, so that no feature dominates the distance because of its unit of measurement. In the simplest form, min-max normalization, the smallest value of a feature becomes 0 and the largest becomes 1, and all other values fall proportionally in between. The demo below is already set to "Min-max" as the normalization. Switch between grams and kilograms again: the decision regions now stay the same.
Whether you normalize is itself a setting you choose in advance, a hyperparameter: usually it helps, but not always. In the section Choosing k you saw how to test such a choice on data the model has not seen yet.
📊 Min-max normalization
For every feature with minimum value and maximum value , every value is transformed into:
After this transformation, every feature has values between 0 and 1, where:
- The smallest value becomes 0
- The largest value becomes 1
- All other values lie proportionally in between
Example: if the weight varies between 100 g and 250 g:
- 100 g becomes:
- 175 g becomes:
- 250 g becomes:
If you measure in kilograms, the numbers are a thousand times smaller, but the fraction (and so the normalized value) stays exactly the same. That is why the difference between the grams version and the kilograms version disappears after normalization.
Normalization must be applied in the same way to both the training data and new test points! Always use the same minimum and maximum of the training data to normalize new points.
📊 Z-score normalization
An alternative to min-max normalization is z-score normalization. This technique transforms the data so that the mean becomes 0 and the standard deviation 1.
For every feature with mean and standard deviation , every value is transformed into:
After this transformation:
- The mean of all values is 0
- The standard deviation is 1
- Values can be negative (below the mean) or positive (above the mean)
This method works better than min-max when your data contains outliers, because it is less sensitive to extreme values (which can distort the maximum and the minimum).
If you apply that normalization to the fruit weight example, the decision boundaries stay the same, whether you measure in grams or in kilograms.
🏷️ Converting categorical features
So far you have only worked with numerical features such as height and width. But suppose the fruit-sorting machine also has a color sensor that detects the color of the fruit: 🔴 red, 🟢 green or 🟡 yellow. Now you have three features: width (numerical), height (numerical) and color (categorical). How do you calculate the "distance" between two colors? Red and green are not numbers, so you cannot simply take their difference.
🔢 Binary distance (0/1)
The simplest approach is the binary distance: if two values are equal, the distance is 0; if they differ, the distance is 1.
- 🔴 red and 🔴 red: distance = 0
- 🔴 red and 🟡 yellow: distance = 1
- 🟢 green and 🟡 yellow: distance = 1
You simply include that distance in the total Euclidean distance, alongside the numerical features.
Sounds simple, but there is an important problem hidden here. Suppose you want to classify a new red piece of fruit with a width of 75 mm and a height of 80 mm. Compare it with two points from the dataset: a yellow orange close by and a red apple further away.
| 📏 Width | 📏 Height | 🎨 Color | 🍎 Fruit | |
|---|---|---|---|---|
| Test point | 75 | 80 | 🔴 red | ? |
| Point A | 73 | 77 | 🟡 yellow | 🍊 Orange |
| Point B | 57 | 63 | 🔴 red | 🍎 Apple |
Without color (only width and height):
- Distance to A: mm
- Distance to B: mm
So orange A is much closer (3.6 mm versus 24.8 mm).
With color (binary distance, without normalization):
- Distance to A: mm
- Distance to B: mm
The color difference adds only 1 under the square root, while the width and height vary by tens of millimeters. So the color hardly affects the classification.
With color and min-max normalization: After normalization, width and height lie between 0 and 1. But the binary color distance is also 0 or 1. Now the color suddenly counts just as heavily as the full range of the width or the height!
- Distance to A (normalized): . The color dominates!
- Distance to B (normalized): . Same color, so 0.
Now the distant apple B is suddenly closer (0.47) than the nearby orange A (1.00), purely because of the color. The color dominates the prediction, and the differences in width and height hardly count anymore.
Try it out: the table below shows the fruit dataset with color. Set the distance metric at the top right to Euclidean, as in the calculations above, and then switch between no normalization and min-max normalization: see how the color affects the result. Also change the color of the test point, to see how strongly that one property changes the prediction.
🤔 What can you do?
In practice there are no perfect solutions, but there are a few strategies:
- Assigning weights to the features, so that categorical features weigh less
- Shrinking the categorical distance by dividing the binary distance by a factor
- Adding many numerical features, so that the few categorical features have proportionally less influence
- Accepting that categorical features are simply less suited to distance-based methods such as k-nearest neighbors, and considering another algorithm that handles them better (such as decision trees or naive Bayes)
🔧 Strengths and weaknesses
Like the naive Bayes algorithm, the k-nearest neighbors algorithm is often used as a baseline: a simple algorithm to compare against. If a more complex algorithm does not perform better than k-nearest neighbors, the extra complexity is probably not worth it.
✅ Strengths
- 🎯 Simple: easy to understand and to implement
- ⚡ No training phase: start predicting right away
- 🆕 Flexible with new data: simply add it to the dataset, no retraining needed
- 🔍 Good at local patterns: finds fine structure in the data
- 📏 Works well with numerical, comparable features: distances are meaningful then
❌ Weaknesses
- 🐌 Slow predictions: every prediction requires calculating the distances to all the training data. With millions of points this becomes slow (although there are efficient data structures that calculate good approximations)
- 💾 Needs a lot of memory: all the training data has to be kept
- 🔢 Struggles with many features: distances become unreliable in many dimensions (the curse of dimensionality (external link))
- 🌊 Sensitive to noise: errors and outliers in the data disturb the predictions
- ⚖️ Sensitive to scale: without normalization, the feature with the largest numbers dominates
- 🔤 Awkward with categorical features: "red" and "blue" have no natural distance.
😴 Lazy learner
An important characteristic of k-nearest neighbors is that it does not actually "learn" anything in the traditional sense. Most AI algorithms (such as neural networks) have a heavy training phase: they study the data to learn a model from it. K-nearest neighbors simply stores the dataset. Only when a question comes in ("What is this new point?") does it start working: calculating distances, sorting, counting. This is called a lazy learner, as opposed to an eager learner.
Compare it with studying for an exam:
- 📚 Eager learner (e.g. a neural network): studies for weeks and summarizes everything in notes and formulas. At the exam, it writes down the answers from memory.
- 💤 Lazy learner (e.g. nearest neighbors): does nothing during the semester. At the exam, it brings the whole textbook along and, for every question, leafs through the entire book looking for similar questions.
This explains the strengths (no training, flexible with new data) and the weaknesses (slow predictions, lots of memory needed) of the algorithm.
🎓 Practical applications
You come across the nearest-neighbor principle in quite a few fields, even far beyond computer science:
- ⚖️ Law: in case-based reasoning you look at earlier cases that resemble the current one. Judges and lawyers look for precedents whose features most resemble the current case, and base their arguments on the outcome of those similar cases. Exactly the nearest-neighbor principle.
- 🖼️ Image recognition: classifying scaled-down images based on their pixel values
- 🎵 Music recommendations: recommending songs that resemble what you liked before
- 🏥 Medical diagnosis: comparing patients with earlier cases with a known diagnosis
- 💳 Fraud detection: comparing transactions with known fraudulent patterns
- 🛒 Product recommendations: "customers who bought this also bought..."
Netflix uses a complex recommender system to recommend films. You can already build a baseline for such a system with an approach along the lines of k-nearest neighbors. Imagine a profile as a data point that holds a rating for every film in the Netflix library:
- "disliked"
- "mediocre"
- "not watched"
- "liked"
- "loved"
You can convert these five levels into numbers (from -2 to +2, with 0 for "not watched") and so build a row of features for your profile. The system looks for users with a similar profile (your "neighbors") by calculating the distance between your profile and that of every other user. Next, it looks at films those users rated highly but that you have not seen yet. The system can then recommend those films to you.
Below you can try this yourself with a simplified example. Every row is a user with film ratings from -2 ("disliked") to +2 ("loved"), and 0 for films they have not seen yet. Fill in your own ratings at the bottom. The algorithm looks for the nearest neighbor: the user with the most similar profile. In the columns on the right you see the name of that nearest neighbor and the distance to it (the table is wide: scroll horizontally or open the demo in full screen). Then look at which films that person rated highly that you have at 0: those are your recommendations.
🕹️ Demos
Experiment further with the full simulators and demos featured above.
🗣️ Feedback
Just like machine learning algorithms, we also love learning from your feedback to improve the course.
Let us know how informative and how difficult you found this chapter, and where it could be better.


