K-Nearest Neighbours (KNN) is the simplest classifier to understand: an instance is probably like its neighbours.
The Algorithm
KNN is a lazy learner or instance-based method: it does no training beyond storing the data. To classify a new instance, it (1) computes the distance to every training instance, (2) selects the k nearest, and (3) predicts the majority class among them. For regression it predicts the average of the neighbours' target values. The usual distance is Euclidean, d = √Σ(aᵢ − bᵢ)²; Manhattan distance Σ|aᵢ − bᵢ| is another choice.
Choosing k
A small k (such as 1) follows every detail of the data, so it is sensitive to noise and overfits. A large k smooths the decision and may underfit, as the neighbourhood includes distant points. For two classes k is made odd to avoid ties. The best k is found with a validation set or cross-validation.
Practical Points
Because distances are used, the features must be scaled to similar ranges, otherwise a feature measured in thousands dominates one measured in fractions. KNN is slow at prediction time for large datasets, since it examines all stored instances, and it suffers in very many dimensions (the curse of dimensionality). Its strengths are simplicity, no training and the ability to model complex boundaries.
Definition: K-Nearest Neighbours. A lazy, instance-based method that classifies a new instance by the majority class among its k closest training instances, using a distance measure.
Table 3.4: Effect of the value of k
| k | Behaviour | Risk |
|---|---|---|
| Small (1) | Very flexible boundary | Overfitting, noise sensitive |
| Medium | Balanced boundary | Best, found by validation |
| Large | Smooth boundary | Underfitting |
Example 3.4: Classifying with 1 and 3 neighbours
Problem: Training points: A(1, 1) Red, B(2, 1) Red, C(4, 5) Blue, D(5, 4) Blue, E(3, 3) Red. Classify the query Q(3, 4) for k = 1 and k = 3 using Euclidean distance.
Solution:
- Distances: to E = √(0 + 1) = 1; to C = √(1 + 1) = 1.414; to D = √(4 + 0) = 2; to B = √(1 + 9) = 3.162; to A = √(4 + 9) = 3.606.
- For k = 1 the nearest is E (Red), so the class is Red.
- For k = 3 the nearest are E (Red), C (Blue) and D (Blue). Blue has 2 votes against 1.
- So the answer changes with k.
Result: k = 1 gives Red; k = 3 gives Blue.
import math
from sklearn.neighbors import KNeighborsClassifier
pts = {"A": (1, 1), "B": (2, 1), "C": (4, 5), "D": (5, 4),
"E": (3, 3)}
cls = {"A": "Red", "B": "Red", "C": "Blue", "D": "Blue", "E": "Red"}
q = (3, 4)
dist = sorted((math.dist(p, q), n) for n, p in pts.items())
print([(n, round(d, 3)) for d, n in dist])
X = list(pts.values())
y = [cls[n] for n in pts]
for k in (1, 3):
m = KNeighborsClassifier(n_neighbors=k).fit(X, y)
print("k =", k, "->", m.predict([q])[0])
Output
[('E', 1.0), ('C', 1.414), ('D', 2.0), ('B', 3.162), ('A', 3.606)]
k = 1 -> Red
k = 3 -> Blue
Common mistakes
- Not scaling the features before using distances.
- Using an even k for two classes and getting ties.
- Choosing k = 1 and trusting the noisy boundary.
- Expecting fast predictions on very large datasets.
Key takeaways
- KNN stores data and classifies by the majority of the k nearest points.
- Small k overfits, large k underfits.
- Always scale the features first.
- For regression, average the neighbours' targets.
Practice questions
- Why is KNN called a lazy learner?
- Why scale features in KNN?
- What happens with k = 1?
Answers to the practice questions
- It does no training; it only stores the data and works at prediction time.
- So that features with large ranges do not dominate the distance.
- The model is flexible and may overfit noise.
Sources
- Official BCA syllabus Introduction to Machine Learning, course code 26BCA404DSE21, Unit III
