Building and Evaluating a k-Nearest Neighbors Model
Evaluation compares a model's predictions on a held-back test set against the known labels for those same flowers.
Try it: k-Nearest Neighbours
How a k-nearest-neighbours classifier labels a new point: measure its distance to every known point, take the K closest, and let them vote.
How it works
- Measure the straight-line (Euclidean) distance from the new point to every labelled point.
- Rank the points from nearest to farthest.
- Keep the K nearest.
- Count how many of them belong to each class; the class with the most votes is the prediction (a tie goes to the class of the nearest tied neighbour).
Default run (15 steps): 10 labelled points and a new query point at (5, 3.5). K = 3. … Prediction: class A — A has the most votes.
Simplified: Small 2-D educational dataset (at most 30 points, three classes). Real KNN uses many features and usually scales them first.
Loading the simulation…
Why a Model Needs Known Answers
A trained k-Nearest Neighbors model is only useful if we can say how often it is right. Instead of guessing, we check its predictions against answers we already know. This article follows one short piece of Python that does exactly that: it asks a model for predictions, then reports a single number that summarizes how well those predictions matched reality. The goal is to understand what that number means, where it comes from, and what it does not promise.
What do you think happens?
A model is given 4 test flowers and gets 3 of them right. What fraction of its predictions are correct?
Reveal answer
0.75
Accuracy is the fraction of predictions that were correct: 3 correct out of 4 total is 3/4, which is 0.75. Read as a percentage, that is 75 percent.
Where the Test Flowers Come From
The flowers used to evaluate the model are the test set that was set aside earlier. Those flowers were not used to build the model. That separation is what makes the evaluation meaningful: the model is being asked about flowers it has not already seen, and we know the correct species for each one because the labels were held back from the model during building.
Read the diagram from top to bottom. The full set of flowers with known species is split once. The training part is what the model stores; the test part is kept aside. The model is built from training examples only, then it is asked about the test inputs. Its predictions meet the known labels only at the final comparison. If the test examples had leaked into the building step, the score would describe flowers the model had already seen, and it would not measure performance on new data.
Comparing Predictions to Labels
The evaluation has two inputs that must line up. The first is the model's prediction for each test flower. The second is the known label for that same flower. Each prediction is compared against its own label, and the results are summarized. If predictions and labels were misaligned, the number would be meaningless even though the code ran without error.
The index map shows the comparison as it actually happens. Each position holds one prediction and one label for the same flower. Position 2 is the only mismatch, so it is the only one that does not count toward the score. The comparison step does not look at species names as a group; it checks each position on its own, and only then is the result summarized.
Accuracy is the fraction of flowers for which the right species was predicted. It is a proportion, so it lies between 0 and 1 and is often read as a percentage when multiplied by 100.
Accuracy for Four Test Flowers
A model predicts the species of 4 test flowers. Their predictions match the known labels as follows: correct, correct, incorrect, correct. What is the accuracy?
- 1Count the correct predictions
Three of the four comparisons are True, so there are 3 correct predictions.
- 2Count the test flowers
There are 4 test flowers, one prediction for each.
- 3Divide
Accuracy is $\frac{3}{4}$, which is 0.75.
- 4Convert to a percentage if needed
0.75 multiplied by 100 is 75 percent.
Accuracy is 0.75, meaning the model was right for 75 percent of these test flowers.
Reading the Evaluation Code
The source shows two ways to obtain the test set accuracy. The first builds the comparison by hand: it checks equality between the predicted labels and the known labels, then takes the mean of the resulting True and False values. The second calls the score method of the trained model object, which performs the same test set accuracy computation internally. Both produce 0.97 in the source, so they agree on this model and this test set.
knn.predict(X_test)produces one predicted label for each test flower- predictions ==
y_testcompares each prediction with the label for the same flower, giving True or False per position np.mean(correct)treats True as 1 and False as 0, so the mean is the fraction correct, which is the accuracyknn.score(X_test, y_test)performs the same test set accuracy computation internally
- 1Test inputs go into the model through predict, producing one predicted label per test flower.
- 2The predictions are compared element by element with the known test labels, producing True or False for each position.
- 3The True and False values are averaged with
np.mean, and that average is the single reported score.
What Accuracy Does and Does Not Promise
The source interprets a test set accuracy of about 0.97 as meaning the model made the right prediction for 97 percent of the irises in the test set. That statement is a direct description of the test set. Under some mathematical assumptions, the same figure is taken as an expectation that the model will be correct about 97 percent of the time on new irises. For the hobby botanist in the source, that level of accuracy suggests the model may be trustworthy enough to use.
The Nearest Neighbors Model
The Nearest Neighbors model looks at the stored examples closest to a new data point to reason about it.
The Nearest Neighbors model is one of the models you can choose from when you are deciding which machine learning approach fits a problem. Its name describes its core idea: to make a decision about a new data point, the model looks at the existing data points that are nearest to it. The name refers to that act of looking for neighbors, meaning the stored examples that sit closest to the new point. The letter k in k-Nearest Neighbors is the number of such neighbors that are consulted; the lookup in the next section uses only the single nearest one, which is the simplest case.
Nearest Lookup in Python
The example below is an original illustration, not taken from the source. It uses a tiny dataset of single numbers, each paired with a label, and finds the stored example closest to a new query value. Real problems usually involve many measurements per example, but the logic of comparing and picking the closest one is the same.
nearest value: 4.0, label: A- 1Line 1 stores four examples the model has learned from.
- 2Line 2 sets the new point we want to classify.
- 3Line 4 measures the distance from the query to every stored example.
- 4Line 5 selects the stored example with the smallest distance and unpacks its value and label.
- 5Line 6 reports which stored example was nearest and its label.
- stored holds the training examples as (value, label) pairs
abs(x - query)is the distance from each stored value to the new querymin(distances)picks the tuple with the smallest distance- The underscore discards the distance, which is no longer needed
Work through the lookup by hand to check the code. The query 3.4 is 2.4 away from 1.0, 0.9 away from 2.5, 0.6 away from 4.0, and 3.6 away from 7.0. The smallest distance is 0.6, which belongs to the stored example 4.0 with label A. That stored example is the nearest neighbor, and its label is the answer this lookup gives.
Why Small Datasets and Baselines Fit
The source identifies small datasets as the setting where this model is a good fit. When a dataset has relatively few examples, a model that works directly from those examples is practical to try, and it gives you a clear starting point before you commit to more complicated approaches. Keep in mind that the source states this suitability without giving a size threshold, so you should judge what counts as small for your own problem.
A baseline is a simple reference model. Its job is not necessarily to be the final choice, but to give you a point of comparison. If a more complex model cannot clearly beat a simple baseline, that is useful information about the problem and about the extra complexity. The source describes the Nearest Neighbors model as good as a baseline, which means it is a sensible first model to build and measure before you move on to others.
The idea behind the name is simple to describe to someone who has never studied machine learning. A new point is compared with the stored examples, and the ones closest to it are the ones that matter. Because the reasoning can be stated in one sentence, the model is easy to explain to colleagues, stakeholders, or anyone who needs to understand why a prediction was made. This explainability is one of the reasons the source recommends it as an early model.
Tracing an Unexpected Score
When a reported score is not what you expected, the flow from the earlier sections gives you a checklist. Work through the stages in order. Only after those checks does it make sense to question the model.
- 1Confirm that the predictions came from the test set and not the training set.
- 2Confirm that the labels being compared are the labels that belong to those same flowers.
- 3Look at the prediction array itself. It should contain one entry per test flower, so a length mismatch points to a problem earlier in the pipeline.
- 4Only then question the model itself.
Common mistake Scoring predictions on the training flowers
What it looks likeThe model is asked about the same flowers it stored, and the accuracy comes out unusually high.
Why it failsThose flowers were not new to the model, so the score does not measure performance on unseen data.
Do this insteadPredict on the held-back test set only, and check that the test inputs were kept separate from the training examples.
Common mistake Comparing predictions with labels from a different ordering
What it looks likeThe predictions are in one order, but the labels array has been shuffled or sorted differently.
Why it failsThe comparison checks each position against the label at the same position, so misaligned arrays produce a number that looks valid but means nothing.
Do this insteadKeep the labels aligned with the same test flowers used to produce the predictions.
Common mistake Reading 0.97 as a guarantee for every future flower
What it looks likeA test accuracy of 0.97 is treated as the exact success rate on any iris ever measured.
Why it failsThe score is a direct result for the test set. Extending it to new flowers depends on assumptions.
Do this insteadDescribe the score as the accuracy on the test set, and state any assumptions before applying it to new data.
Common mistake Assuming a lookup that prints a label has been evaluated; a single prediction is not an accuracy score until it is compared with many known labels
Practice Tracing the Score
A model predicts labels for 5 test flowers, and 4 of the predictions match their known labels. Compute the accuracy as a fraction and as a percentage, then explain what the number means for those 5 flowers.
Hints
- Accuracy is the number of correct predictions divided by the number of test flowers.
- Multiply the fraction by 100 to get a percentage.
Stored values are 1.0 (label A), 3.0 (label B), 5.5 (label A), and 6.0 (label B). Find the nearest stored example to the query 4.6 by computing each distance, and state which label the lookup returns.
Hints
- Distance here is the absolute difference between the stored value and the query.
- Compare the four distances and pick the smallest.
Key Takeaways
- Evaluation compares a model's predictions on a held-back test set against the known labels for those same flowers, and the comparison must line up position by position.
- Accuracy is the fraction of correct predictions, computed by hand with a mean of True and False values or by calling the model's score method.
- The Nearest Neighbors model reasons about a new point by looking at the stored examples closest to it, and it is considered suitable for small datasets, useful as a baseline, and easy to explain.
- When a score looks wrong, trace the flow from test inputs to predictions to the label comparison, and check that the test set was kept separate and that labels align before questioning the model.