K-Nearest Neighbours (KNN)
KNN predicts a new example by looking at the examples closest to it. Nearby examples get a vote. The most common class wins in classification; the average value is used in regression.
What does it do?
It learns from the examples closest to the new point.
Imagine a new student whose result is unknown. KNN finds students with similar study hours and attendance, then uses their known results to make a prediction.
Quick facts
Features such as study hours and attendance.
A class or a number, depending on the task.
Supervised: it uses labelled examples.
It stores training examples instead of learning a simple formula first.
1. How does KNN work?
The new point asks its closest neighbours for help.
Nearby points vote
The star is a new student. KNN looks for the nearest labelled students. Try changing K in the playground to see how the vote changes.
Four simple steps
Decide how many neighbours should vote.
Calculate how far each known example is from the new one.
Keep only the K examples with the smallest distances.
Use the majority class, or average their values for regression.
2. Live KNN Playground
Move the new example and change K. Watch the closest neighbours and prediction update.
Feature space
Each dot is a labelled example. The star is the new example.
Experiment controls
Use the sample data or create a new set of examples.
3. The mathematics behind KNN
KNN mainly needs a way to measure distance between examples.
Euclidean distance
For more than two features, square each feature difference, add them, and take the square root.
Classification vote
For K=5, if 3 neighbours are A and 2 are B, the prediction is class A.
Regression prediction
If the neighbours' house prices are 20, 22, and 24 lakh, the predicted price is 22 lakh.
Feature scaling
If one feature is measured in rupees and another from 0 to 10, the large-number feature can dominate distance. Scaling helps put features on a similar range.
4. Numerical worked example
Let's predict a class using three neighbours.
New point: (4, 4), with K = 3
Suppose the three closest labelled examples are A at (3, 4), B at (5, 4), and A at (4, 6).
To A (3,4): √[(4−3)²+(4−4)²] = 1
To B (5,4): √[(4−5)²+(4−4)²] = 1
To A (4,6): √[(4−4)²+(4−6)²] = 2
Class A: 2 votes
Class B: 1 vote
Step 3: Predict
Class A wins the majority vote.
5. How do we evaluate KNN?
Test it on examples it did not use as neighbours during training.
For classification
Share of predictions that are correct.
Useful when one class is more important or less common.
Shows which classes the model mixes up.
Choosing a good K
Can be affected by noise and individual unusual points.
Can smooth away local patterns and favour the largest class.
Use validation data or cross-validation to choose K.
6. Python implementation
Build a KNN classifier using scikit-learn.
Example code
Two numeric features are scaled before the model is trained.
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.metrics import accuracy_score, confusion_matrix
# Each row is one example: [feature X, feature Y]
X = np.array([
[1, 2], [2, 1], [2, 3], [3, 2], [3, 3],
[7, 8], [8, 7], [8, 9], [9, 8], [9, 9]
])
# Class labels: 0 = A, 1 = B
y = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1])
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=42, stratify=y
)
# Scaling and KNN are kept together in one pipeline
model = make_pipeline(
StandardScaler(),
KNeighborsClassifier(n_neighbors=3)
)
model.fit(X_train, y_train)
predictions = model.predict(X_test)
print("Accuracy:", accuracy_score(y_test, predictions))
print("Confusion matrix:\\n", confusion_matrix(y_test, predictions))
# Predict the class of a new point
new_point = np.array([[4, 4]])
print("Predicted class:", model.predict(new_point)[0])7. Real-life applications
KNN can help when similar examples often have similar outcomes.
Recommendation
Find users or items with similar features to suggest related choices.
Image recognition
Classify an image using nearby examples in a feature representation.
Customer grouping
Predict a category for a customer based on similar known customers.
Medical data research
Compare a case with similar labelled records as part of research or decision support.
8. Knowledge check
Answer all 10 questions, then submit to see your score and explanations.