edSlash Labs  /  Machine Learning Lab  /  Supervised Learning  /  K-Nearest Neighbours
Algorithm 04 · Supervised learning · Classification and regression

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.

Beginner friendly

What does it do?

It learns from the examples closest to the new point.

Find neighbours → Count votes → PredictK means the number of nearby examples we look at

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

Input

Features such as study hours and attendance.

Output

A class or a number, depending on the task.

Learning style

Supervised: it uses labelled examples.

Special feature

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.

New pointFeature 1Feature 2
Class AClass BNew exampleNeighbour area (illustration)

Four simple steps

Choose K

Decide how many neighbours should vote.

Measure distance

Calculate how far each known example is from the new one.

Find the closest K

Keep only the K examples with the smallest distances.

Make the prediction

Use the majority class, or average their values for regression.

Remember: K=3 means the three closest examples get a vote. It does not mean three classes.

2. Live KNN Playground

Move the new example and change K. Watch the closest neighbours and prediction update.

Interactive experiment

Feature space

Each dot is a labelled example. The star is the new example.

Class AClass BNew exampleSelected neighbours

Experiment controls

Use the sample data or create a new set of examples.

Prediction—Majority vote
Neighbours5Chosen K
Class A votes—Among neighbours
Class B votes—Among neighbours
Generate a dataset to begin. Then move the new point or change K.
The graph uses two simple classes so you can see how neighbour voting works.

3. The mathematics behind KNN

KNN mainly needs a way to measure distance between examples.

Euclidean distance

d = √[(x₂−x₁)² + (y₂−y₁)²]Straight-line distance between two points

For more than two features, square each feature difference, add them, and take the square root.

Classification vote

Predicted class = most common labelCount the labels of the K nearest examples

For K=5, if 3 neighbours are A and 2 are B, the prediction is class A.

Regression prediction

Prediction = average of K valuesUsed when the target is a number

If the neighbours' house prices are 20, 22, and 24 lakh, the predicted price is 22 lakh.

Feature scaling

z = (x − mean) / standard deviationOne common way to standardise a feature

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.

Important: KNN is sensitive to feature scales. In many real tasks, scale numeric features before using KNN.

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).

Step 1: Calculate distances
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
Step 2: Count the votes
Class A: 2 votes
Class B: 1 vote

Step 3: Predict
Class A wins the majority vote.
Final prediction: Class A. The new point takes the class that appears most often among its three nearest neighbours.

5. How do we evaluate KNN?

Test it on examples it did not use as neighbours during training.

For classification

Accuracy

Share of predictions that are correct.

Precision and recall

Useful when one class is more important or less common.

Confusion matrix

Shows which classes the model mixes up.

Choosing a good K

Very small K

Can be affected by noise and individual unusual points.

Very large K

Can smooth away local patterns and favour the largest class.

Try several values

Use validation data or cross-validation to choose K.

Remember: K is a setting you choose. There is no one perfect K for every dataset. Test different values on data set aside for validation.

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.

Strengths: simple, intuitive, and useful for small or medium-sized datasets. Limitations: prediction can be slow on large datasets, distance can be misleading without scaling, and irrelevant features can hurt results.

8. Knowledge check

Answer all 10 questions, then submit to see your score and explanations.

0 of 10 answered