Concepts / Training a k-nearest neighbors classifier

Training a k-nearest neighbors classifier

A k-nearest neighbors classifier predicts a new point by looking at its closest training neighbor or neighbors.

  • 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…

Guessing From the Nearest Neighbors

Imagine you have a collection of past examples, each one labeled with its known class, and a new measurement arrives with no label. A natural way to guess its class is to look at the examples that are most similar to it and let them decide. That idea is the core of the k-nearest neighbors classification algorithm. Its prediction is local: it looks at the training points that lie closest to the new point and lets those neighbors inform the answer.

What do you think happens?

A new point's single closest training point belongs to class B, but four of its five nearest training points belong to class A. The model uses k equal to 1. Which class is predicted?

  • Class A

  • Class B

Reveal answer
Answer:

Class B

With k equal to 1, the prediction is driven by the single closest training point, so the other neighbors never get a vote. This is exactly why the choice of k matters, and it is explored below.

What Happens Inside a Prediction

The algorithm has no fixed formula to memorize in advance. Instead, the stored training data is what it consults each time it makes a prediction. The steps run in order: the algorithm receives a new measurement, measures how far that point is from each training point, selects the k closest training points, and then takes a majority vote among their known classes. The class that wins the vote is returned as the prediction.

New measurementMeasure distance toeach training pointSelect the k closestpointsMajority vote ontheir classesPredicted classcomparerank by distancek neighborswinning class
What steps happen, in order, from receiving a new measurement to returning a predicted class?

Because the stored training examples are needed every time a prediction is made, the training data must be supplied when the model is built. The model is not a compact summary that can be discarded after training. It is the examples themselves, together with the rule for consulting them.

Choosing the Value of k

The number of neighbors considered is controlled by a parameter usually written as k. When k equals 1, the prediction is driven entirely by the single closest training point. When k is larger, several nearby points contribute to the answer, and their classes are combined. The same new point can therefore receive a different predicted class depending on the value of k, which is why k is a setting you choose when you configure the model.

Closest trainingpointIts class is thepredictionSeveral nearbypointsTheir classes arecombineddecides alonecontribute together
How does the predicted class for the same point change when k is 1 versus a larger value such as 3 or 5?

Three Stages: Configure, Fit, and Score

In Python, the algorithm is provided by a class named KNeighborsClassifier. A single class of this kind holds two responsibilities: the procedure that builds the model from training data, and the procedure that uses the built model to make a prediction. You work with the class in three stages. First you create the object and set its parameters. Then you build the model by calling its fit method with the training inputs and training outputs. Finally you evaluate it by calling its score method with test inputs and test labels.

python
Notes on the code
  • Line 1 imports the KNeighborsClassifier class that implements the algorithm.
  • Line 3 creates the object and sets n_neighbors to 3, an illustrative choice for this example.
  • Line 4 calls fit with the training inputs X_train and the training outputs y_train to build the model.
  • Line 5 calls score with held-out test inputs X_test and test labels y_test and returns the accuracy.

Notice that fit does not return a prediction. Its job is only to build the model from the training pair. Evaluation and application are separate steps that come afterward. The same sequence can be read as a short pipeline in which the model is configured, built from training data, measured on test data, and then put to use if the measurement is satisfactory.

ConfigureKNeighborsClassifierfit with X_train andy_trainscore with X_test andy_testAccuracy estimateApply to newmeasurementsbuildtrained modelmeasuredif satisfactory
Which data goes into fit(), which goes into score(), and how does each step feed the next?

Worked Example: Building and Measuring a Model

Worked example

Building a kNN model and reading its score

You have labeled training examples, a separate set of labeled test examples the model never saw during training, and you want to build a kNN model with three neighbors and report how accurate it is. Assume for this example that the model is evaluated on 10 test examples.

  1. 1
    Create the object

    Instantiate KNeighborsClassifier with n_neighbors set to 3. This sets the parameter that controls how many neighbors are consulted.

  2. 2
    Fit on training data

    Call fit with X_train and y_train. The model is built from this pair, and the training examples are retained so they can be consulted later. fit returns no prediction.

  3. 3
    Score on test data

    Call score with X_test and y_test. The method predicts a class for each test input, compares each prediction with its true label, and reports the proportion that match.

  4. 4
    Compute the proportion

    Suppose 9 of the 10 test predictions match their true labels. Then the accuracy is $\frac{9}{10} = 0.9$. This number is the measured accuracy on the test set.

Result

The model's accuracy on this held-out test set is 0.9. This is a measurement of performance on the test examples, and it is the basis for deciding whether the model is good enough to use.

Scoring Accuracy on Held-Out Data

The score method computes the accuracy of the model. Accuracy is the proportion of predictions that match the true labels. To measure it honestly, you give score a set of data the model did not learn from, along with the correct labels for that data. This is the test set. Using a separate test set matters because a model is always tempted to look good on the examples it was built from. Training alone does not tell you whether the learned behavior is good; a model that looks reasonable on its own training examples may still fail on examples it has never seen.

Rule

Read this as a proportion. An accuracy of 0.9 means that nine out of every ten test predictions matched the true labels. The number answers the question of how often the model is right, but only on the data that was used to measure it. Model evaluation turns a trained model into a measured claim by asking two things: how often is it right, and on what data was that measured?

Mistakes Beginners Make With kNN Evaluation

  • Common mistake

    Scoring the model on the same examples used in fit

    What it looks like

    Calling knn.score(X_train, y_train) right after fitting and reporting that number as the model's accuracy.

    Why it fails

    The model was built from these examples, so it is tempted to look good on them. The result says little about behavior on examples it has never seen.

    Do this instead

    Hold out a separate test set and pass that set's inputs and labels to score.

  • Common mistake

    Expecting fit to return predictions

    What it looks like

    Writing predictions = knn.fit(X_train, y_train) and expecting a list of predicted classes.

    Why it fails

    fit builds the model from the training pair. Evaluation and application are separate steps that come afterward.

    Do this instead

    Call fit to build the model, then use the model's other methods to obtain predictions and score to obtain accuracy.

  • Common mistake

    Treating k as a fixed rule

    What it looks like

    Assuming k equal to 3 is always correct because it appeared in an example.

    Why it fails

    The source presents 3 as an illustrative choice. Different k values can change the predicted class for the same point.

    Do this instead

    Treat k as a setting to be chosen and checked against held-out data.

  • Common mistake

    Forgetting that the stored training data is needed at prediction time

What the Accuracy Estimate Does and Does Not Promise

Once the measured accuracy is acceptable, the model can be applied to new data. In the source example, the new data consists of fresh flower measurements, meaning measurements that were part of neither the training set nor the test set. The evaluation result is what gives confidence to take this step. The source states the expectation plainly: the model is expected to be correct about 97% of the time on such new data.

Applying the model means passing new, unlabeled measurements to the model and using the predicted class it returns. Because those measurements were never used for training or testing, the test accuracy is the best available reason to trust the model, but that trust remains tied to the conditions under which it was measured.

Checking Your Understanding With a Model Run

MEDIUM

You fit a kNN model on X_train and y_train with n_neighbors set to 5, then call score on X_test and y_test and get an accuracy of 0.8. A colleague proposes reporting score(X_train, y_train) instead because it gives 0.99. Explain which number is the honest measure of the model's accuracy, and why.

Hints
  • Ask which examples the model was built from, and which examples it has never seen.
  • Consider what a model is tempted to do on the examples it was built from.
  • The test set is the data that reveals behavior on unseen examples.

Key Takeaways

  • A kNN classifier predicts a new point by consulting its closest training neighbors; with k equal to 1, the single closest point decides, and with larger k, several neighbors contribute.
  • KNeighborsClassifier is configured, then built with fit(X_train, y_train), then evaluated with score(X_test, y_test); fit does not return predictions.
  • Accuracy is the proportion of predictions that match the true labels, and it is only trustworthy when measured on held-out data the model did not learn from.
  • The score-based accuracy is a measured estimate on one test set, not a guarantee; the source expects about 97% correctness on fresh flower measurements in its example, which applies only under similar conditions.

Related concepts

More concepts starting with T