TetSharing
AI basics tutorial · 10 chapters
  1. What machine learning is
  2. Features and labels
  3. Train, test and validation data
  4. Overfitting
  5. Accuracy, precision, recall
  6. k-nearest neighbors
  7. LLMs, tokens and context
  8. Prompt basics
  9. Embeddings and similarity
  10. Responsible AI (NIST AI RMF)

Final AI basics quiz

Chapter 6 of 10 · By Ethan Cole · Updated November 21, 2026

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

  1. Store all training samples with their labels. That is the whole "training" step.
  2. For a new sample, compute its distance to every training sample.
  3. Keep the k nearest.
  4. 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.

Python 3 · editable

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

1. What does k-NN do during training?

All the work happens at prediction time, comparing against stored samples.

2. With k = 3, the nearest neighbors are labeled orange, lemon, orange. What is predicted?

The majority label among the three neighbors wins.

3. Why scale features before using k-NN?

Distances add up differences, so large-range features overwhelm small ones.

Official docs

Written under the pen name Ethan Cole with AI-assisted drafting. Every code example on this page is executed by our test suite before publishing. Found a mistake? Tell us.