Concepts / Building and Evaluating a k-Nearest Neighbors Model

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.

  • Programming
Interactive lab

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

  1. Measure the straight-line (Euclidean) distance from the new point to every labelled point.
  2. Rank the points from nearest to farthest.
  3. Keep the K nearest.
  4. 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.

Educational simulation

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?

  • 0.25

  • 0.75

  • 0.34

  • 3.0

Reveal answer
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.

Full datasetflowers with known labelsTraining examplesstored by the modelModel builtuses training examples onlyPredictionsone per test flowerCompare with knownlabelsproduces accuracyTest examplesset aside, labels held backsplitsplitbuildpredict on testinputsmatch each
How is the full dataset divided into the training examples the model stores and the test examples kept aside for scoring?

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.

Position 0predicted A | label APosition 1predicted B | label BPosition 2predicted A | label BPosition 3predicted C | label C
For each test flower, how does the predicted species line up with the true species, and which positions count as correct?

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.

Definition

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.

Rule

Worked example

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?

  1. 1
    Count the correct predictions

    Three of the four comparisons are True, so there are 3 correct predictions.

  2. 2
    Count the test flowers

    There are 4 test flowers, one prediction for each.

  3. 3
    Divide

    Accuracy is $\frac{3}{4}$, which is 0.75.

  4. 4
    Convert to a percentage if needed

    0.75 multiplied by 100 is 75 percent.

Result

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.

python
Notes on the code
  • knn.predict(X_test) produces one predicted label for each test flower
  • predictions == y_test compares 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 accuracy
  • knn.score(X_test, y_test) performs the same test set accuracy computation internally
  1. 1
    Test inputs go into the model through predict, producing one predicted label per test flower.
  2. 2
    The predictions are compared element by element with the known test labels, producing True or False for each position.
  3. 3
    The 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

Definition

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.

python
Output (expected)
nearest value: 4.0, label: A
Walk through it
  1. 1
    Line 1 stores four examples the model has learned from.
  2. 2
    Line 2 sets the new point we want to classify.
  3. 3
    Line 4 measures the distance from the query to every stored example.
  4. 4
    Line 5 selects the stored example with the smallest distance and unpacks its value and label.
  5. 5
    Line 6 reports which stored example was nearest and its label.
Notes on the code
  • stored holds the training examples as (value, label) pairs
  • abs(x - query) is the distance from each stored value to the new query
  • min(distances) picks the tuple with the smallest distance
  • The underscore discards the distance, which is no longer needed
Stored 1.0class A, distance 2.4Stored 2.5class B, distance 0.9Stored 4.0class A, distance 0.6Stored 7.0class B, distance 3.6second closest
When the query 3.4 arrives, what distance is computed against each stored example, and which one is selected as nearest?

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.

  1. 1
    Confirm that the predictions came from the test set and not the training set.
  2. 2
    Confirm that the labels being compared are the labels that belong to those same flowers.
  3. 3
    Look 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.
  4. 4
    Only then question the model itself.
  • Common mistake

    Scoring predictions on the training flowers

    What it looks like

    The model is asked about the same flowers it stored, and the accuracy comes out unusually high.

    Why it fails

    Those flowers were not new to the model, so the score does not measure performance on unseen data.

    Do this instead

    Predict 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 like

    The predictions are in one order, but the labels array has been shuffled or sorted differently.

    Why it fails

    The 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 instead

    Keep 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 like

    A test accuracy of 0.97 is treated as the exact success rate on any iris ever measured.

    Why it fails

    The score is a direct result for the test set. Extending it to new flowers depends on assumptions.

    Do this instead

    Describe 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

EASY

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.
MEDIUM

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.

Related concepts

More concepts starting with B