Concepts / KNeighborsClassifier Class

KNeighborsClassifier Class

The KNeighborsClassifier class contains both the algorithm that builds the model and the algorithm that makes predictions.

  • Programming

Predicting From the Nearest Examples

Suppose you have a collection of labeled examples and a new data point whose label is unknown. One simple way to guess that label is to look at the examples that are most similar to the new point and let them decide. The k-nearest neighbors classification algorithm works this way. It makes a prediction for a new data point by considering its closest neighbor or neighbors in the training set.

The word neighbor refers to a training example that is close to the new point. The number of neighbors considered is the k in the algorithm's name. This article follows one complete path: how the algorithm uses neighbors to predict, how the KNeighborsClassifier class carries out that work, and how the accuracy of the resulting model is measured on the test set.

What do you think happens?

A new point has three nearest training neighbors: two are labeled A and one is labeled B. If k is 3, what class does k-NN predict?

  • Class A

  • Class B

Reveal answer
Answer:

Class A

With $k = 3$, the three nearest neighbors vote. Two of the three carry the label A, so the majority vote is A.

Tracing One Prediction Step by Step

Follow a single prediction from start to finish. The new data point arrives first. The algorithm then measures how far that point is from each training example. From those distances it selects the k nearest training examples, which are the neighbors. Finally, it takes a majority vote among the labels of those neighbors, and that majority label is the predicted class.

New data pointlabel unknownMeasure distancesto every training pointSelect k nearestthe neighborsMajority voteamong neighbor labelsPredicted classreturned as the answercomparerank by distancek labelswinning label
What happens step by step, from receiving a new point to returning a predicted class?

Notice what the algorithm does not do. It does not first search for a rule that separates the classes. The training examples are consulted at the moment a new point arrives, and only the examples nearest to that point influence the decision.

The KNeighborsClassifier Class as a Container

In Python, the k-nearest neighbors algorithm is implemented in the KNeighborsClassifier class. This class contains two things: the algorithm that builds the model, and the algorithm that makes a prediction using that model. You do not write the neighbor search yourself. Instead, you create an object from the class and call its methods.

Think of the class as a toolkit with two jobs. One job turns training data into a model. The other job uses that model to label new points. Both jobs live inside the same object, so the model-building step and the prediction step are connected through that one object.

Building the Model With fit

The fit method builds the model from training data. It takes two inputs: X_train, which holds the training examples, and y_train, which holds their training outputs, meaning the class labels that go with each example.

Because k-nearest neighbors does not need a separating rule in advance, the training step is about preparing the examples so that neighbors can be found later when predictions are requested. The examples and their labels are what the prediction step will rely on.

Following the Data Through fit and score

The source describes a workflow in which training data goes into fit to produce a model, and then the test set goes into score, which reports accuracy. The diagram below shows how the data moves through that path. Watch which set feeds which step, and notice where the accuracy number comes from.

Full labeleddatasetTraining setX_train, y_trainFitted modelbuilt by fitAccuracyreported by scoreTest settest data and test labelstraining portiontest portionfitscore on test settest labels
How does the data flow from the full dataset into the training set and the test set, and which set does the accuracy come from?

The sequence below shows the order in which your program calls the methods. First you call fit with the training data. Then you ask the object to predict, and finally you call score with the test set data and test set labels.

Your programKNeighborsClassifierobjectholds both algorithms1. fit(X_train, y_train) builds the model2. predict(new point) labels a new point3. score(X_test, y_test) reports accuracy
In what order do fit, predict, and score call each other, and what does each one receive?

Reading the 97% Accuracy Figure

The score method computes the model's accuracy when applied to the test set data and the test set labels. It does this by using the fitted model to make predictions for the test examples and comparing them with the true labels. The accuracy is the share of test examples the model labeled correctly.

An accuracy of 97% therefore means that, on the test set, the model's predictions matched the true labels for about 97 out of every 100 test examples. The statement is about the test set. It does not claim that the model is 97% correct on every possible new point, and it does not describe how the model performed on the training examples it was built from.

Worked Example: Interpreting a Score of 97%

Worked example

Turning an accuracy value into counts

A KNeighborsClassifier model is built with fit on the training data. Then score is called with a test set of 200 examples and their true labels, and it returns an accuracy of 97%. How many test examples were labeled correctly, and how many were not?

  1. 1
    Identify the set

    The accuracy comes from score applied to the test set, so the denominator is the 200 test examples.

  2. 2
    Convert the percentage

    97% is the fraction 0.97 of the test examples.

  3. 3
    Count the correct predictions

    0.97 multiplied by 200 gives 194 examples labeled correctly.

  4. 4
    Count the errors

    200 minus 194 leaves 6 test examples that were labeled incorrectly.

Result

194 test examples were predicted correctly and 6 were not. The 97% describes only this test set of 200 examples.

Common Mistakes With fit and score

  • Common mistake

    Treating an accuracy from the training data as the test score

    What it looks like

    Calling score on X_train and y_train and then reporting the result as how the model performs on new data.

    Why it fails

    The score method computes accuracy on the test set data and test set labels. Training examples were used to build the model, so their accuracy does not show how the model handles examples it has not seen.

    Do this instead

    Pass the held-out test set data and test set labels to score, and report that accuracy.

  • Common mistake

    Expecting k-NN to have learned a separating formula

    What it looks like

    Looking for coefficients or a rule inside the model after fit and expecting them to explain each prediction.

    Why it fails

    The algorithm does not need to find a rule that separates the classes in advance. It looks at the training examples nearest to a new point when that point arrives.

    Do this instead

    Think of predictions as coming from the nearest neighbors of each new point, not from a stored equation.

  • Common mistake

    Mismatching training inputs and labels

    Why it fails

    fit builds the model from X_train and y_train together, so a label attached to the wrong example would feed wrong neighbor votes into later predictions.

    Do this instead

    Build X_train and y_train from the same labeled examples, keeping each row paired with its label.

Predict the Vote Before You Check

EASY

A new data point has its five nearest training neighbors. Their labels are red, red, blue, blue, and red. Using k equal to 5, which class does k-NN predict, and what would the model's score method need in order to report how often this kind of prediction is right?

Hints
  • Count how many neighbors carry each label.
  • The prediction is the majority label among the k neighbors.
  • The score method needs the test set data and the test set labels, not the training set.

Key Takeaways

  • k-nearest neighbors predicts a new point by looking at its closest training examples, selecting the k nearest, and taking a majority vote among their labels.
  • The KNeighborsClassifier class contains both the algorithm that builds the model and the algorithm that makes predictions, so you create an object and call its methods.
  • fit takes X_train and y_train to build the model, and score takes the test set data and test set labels to compute accuracy.
  • An accuracy of 97% means the model labeled about 97 of every 100 test examples correctly; it describes the test set, not the training data.

Related concepts

More concepts starting with K