K-Nearest Neighbours (K-NN) classifies a new data point by finding the most similar labelled examples in the training data and assigning the class that occurs most frequently among them.
K-NN is a supervised learning algorithm because it learns from a labelled training dataset. It is also described as an instance-based or “lazy” learning algorithm: it stores the training examples rather than constructing a model during training.
The classification process is:
- Choose a value for , the number of neighbours considered.
- Calculate the distance from the unclassified point to each labelled training point.
- Sort the training points from smallest to largest distance.
- Select the nearest points.
- Count the class labels among those neighbours.
- Assign the most frequent class to the new point.
For numerical features, Euclidean distance is commonly used. For two points and :
Suppose the four nearest training examples have the following distances and labels: (A), (B), (A), and (B). If , the selected labels are A, B, and A, so the new point is classified as A by majority voting.
| Choice of | Likely effect |
|---|---|
| Small | More sensitive to noise and may overfit |
| Large | Produces smoother boundaries but may underfit |
| Even | Can create voting ties, especially with two classes |
Features should usually be normalized so that a feature with large numerical values does not dominate the distance calculation.
Categorical features require an appropriate distance measure or numerical encoding. If majority voting produces a tie, the implementation should apply a stated rule, such as choosing the class of the closest neighbour. Validation data can help select by comparing classification accuracy.
In an IB Computer Science HL A4.3 response, describe the ordered algorithm and explain how , distance, and majority voting affect classification. A common misconception is that K-NN calculates an average label; classification uses the most frequent class, while averaging is associated with K-NN regression.