k-Nearest Neighbors in Pure Python, Step by Step
k-nearest neighbors (k-NN) is one of the oldest and easiest machine learning methods to understand, which makes it a great first algorithm to build yourself. Its idea fits in one sentence: to classify a new point, look at the k closest training points and take a vote.
The algorithm
- Store all training samples with their labels. That is the whole "training" step.
- For a new sample, compute its distance to every training sample.
- Keep the k nearest.
- Predict the label that appears most often among them.
For points with numeric features, the usual distance is Euclidean distance, the straight-line distance you would measure with a ruler. For two features it is sqrt((x1 - x2)**2 + (y1 - y2)**2), and Python's math.dist computes it for any number of features.
A complete classifier
The example uses a tiny made-up dataset of fruit, described by two features: weight in grams and a "roundness" score from 1 to 10. Lemons and oranges overlap a little, as real data does.
Expected output
(15.5, 9.0) -> orange (k=1) orange (k=3) (10.5, 6.0) -> lemon (k=1) lemon (k=3) (12.8, 7.8) -> orange (k=1) lemon (k=3) neighbor (13.0, 8.0) orange distance 0.28 neighbor (12.5, 8.0) lemon distance 0.36 neighbor (12.0, 6.5) lemon distance 1.53
The predict function is the entire algorithm: sorted with a key orders the training points by distance, slicing keeps the first k, and Counter.most_common(1) takes the vote. The last lines show the neighbors the model consulted for one prediction, which is one of k-NN's strengths: you can always explain a prediction by pointing at similar examples.
Choosing k
- k = 1 copies the label of the single nearest point. It follows the training data exactly, noise included, which is the memorizer from the overfitting chapter.
- Larger k smooths out noise, but if k gets too big, the vote is dominated by whichever class is most common overall.
- An odd k avoids ties between two classes.
The right k is found by trying several values on validation data, never on the test set.
Practical notes
- Scale your features. If one feature is in grams (hundreds) and another is a 1-to-10 score, the grams dominate every distance. Libraries offer scalers that put features on comparable ranges; our fruit example uses features with similar spreads to keep it short.
- Prediction is slow on big data, because every prediction compares against every stored sample. Libraries use tree structures to speed this up.
- In scikit-learn the same model is
KNeighborsClassifier(n_neighbors=3).
Summary
- k-NN stores the training data and votes among the k closest samples.
- Euclidean distance (
math.dist) is the common choice for numeric features. - Choose k on validation data, and scale features first.
Quiz: k-nearest neighbors