Skip to content

Intermediate: machine learning · k-NN, decision trees and ensembles · topic 33 of 62 · 30 min

k-nearest neighbours

Explanation

k-nearest neighbours (k-NN) predicts by looking at the k most similar training examples: for classification it takes a vote of their labels, for regression it averages their values. "Similar" means close by a distance measure, so features must be on similar scales. It needs no training, but predictions get slow on big data.

The idea: you are like your neighbours

To guess whether a new customer will like a premium plan, look at the customers most similar to them. If most of those liked it, guess yes. That is the whole idea of k-nearest neighbours. It is one of the simplest ML methods and a good way to understand what "learning from examples" really means.

Think of it like this: When you move to a new city and want a good tea stall, you ask the people who live closest to you and share your taste. If three out of five recommend the same stall, you go there. k-NN does the same with data: k is how many neighbours you ask.

Measuring closeness

Each example is a point with one coordinate per feature. Euclidean distance is the straight-line distance: the square root of the sum of squared differences. Manhattan distance adds the absolute differences, like walking city blocks. For two customers described by (age, monthly spend in thousands), (25, 4) and (28, 8) have Euclidean distance √(3² + 4²) = 5.

python
import math

def euclidean(a, b):
    return math.sqrt(sum((x - y) ** 2 for x, y in zip(a, b)))

print(euclidean((25, 4), (28, 8)))
Shows 5.0. Python 3.8+ also has math.dist(a, b), which does the same.

The algorithm

  1. Store all training examples (there is no real training step; k-NN is a "lazy learner").
  2. For a new point, compute its distance to every training example.
  3. Take the k closest.
  4. Classification: return the most common label among them. Regression: return their average value.

Choosing k

A small k (like 1) follows every noisy point and overfits. A large k smooths too much and underfits, eventually just predicting the majority class. Try several values with cross-validation. For two classes, an odd k avoids exact ties in the vote; you still need a tie rule for more classes, such as "the label of the nearest neighbour wins".

Scaling matters a lot

If one feature is income in rupees (values like 6,00,000) and another is age in years (values like 30), the distance is almost entirely about income. Age barely counts. Always scale features (for example, standardise them to mean 0 and standard deviation 1) before k-NN. Module 8 covers scaling.

python
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

knn = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=5))
knn.fit(X_train, y_train)
print(knn.score(X_test, y_test))
The pipeline scales first, then runs k-NN. Shown only.

Strengths and weaknesses

  • Strengths: simple to explain ("these 5 similar cases"), no training time, works for odd-shaped class boundaries.
  • Weaknesses: prediction needs a distance to every stored example, so it is slow with millions of rows (special indexes help); it struggles with many features, where all points start to look equally far apart (the "curse of dimensionality"); it needs careful scaling.

Common mistakes

  • Forgetting to scale features. Fix: put a scaler in a pipeline.
  • Using k = 1 and trusting a perfect training score; with k = 1, every training point is its own neighbour.
  • Using k-NN on huge datasets that need fast answers without an index.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

k-nearest neighbours · 1/6

k-NN

k-nearest neighbours predicts by asking the most similar examples.

Prefer a video by a teacher? Find free videos on “k nearest neighbors algorithm explained knn” on YouTube ↗

In real life: "Customers like you also bought"

A simple recommendation idea on a shopping site is neighbour-based: find shoppers whose past purchases are most similar to yours, and suggest what they bought that you have not. Large companies use more advanced methods today, but nearest-neighbour search over vectors (embeddings) is still at the heart of many recommendation and search systems, as you will see in module 10.

Practice (0/3 done)

Task 1 · Code · Python

Write euclidean(a, b) for two equal-length tuples of numbers, returning the straight-line distance rounded to 4 decimal places.

Task 2 · Code · Python

Write knn_predict(points, labels, query, k). Sort the training points by Euclidean distance to query (if two are equally far, the one with the smaller index comes first), take the first k, and return the most common label. If labels tie in the vote, return the tied label that appears FIRST in that sorted neighbour list.

Task 3 · Code · Python

k-NN regression: write knn_regress(points, values, query, k) that returns the AVERAGE of the values of the k nearest points (same distance and tie order as before), rounded to 2 decimal places.

Quick quiz

Question 1

1.How does k-NN classify a new point?

Question 2

2.Features are salary in rupees and age in years, unscaled. What goes wrong in k-NN?

Question 3

3.What happens with k = 1 on the training set itself?

Question 4

4.Why can k-NN be slow at prediction time?

Question 5

5.Why is k-NN called a "lazy learner"?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

How does k-NN classify a new point?

Answer: It takes a vote among the k closest training points

The k nearest neighbours vote.

Features are salary in rupees and age in years, unscaled. What goes wrong in k-NN?

Answer: Distance is dominated by salary, so age is almost ignored

Large-valued features swamp the distance. Scale first.

What happens with k = 1 on the training set itself?

Answer: Perfect accuracy, because each point is its own nearest neighbour

That perfect score says nothing about new data.

Why can k-NN be slow at prediction time?

Answer: It must compare the new point with every stored example

Without an index, each prediction scans all training data.

Why is k-NN called a "lazy learner"?

Answer: It does no real work at training time; it just stores the data

All the work happens when a prediction is requested.

A tree trained on flats priced ₹30–90 lakh is asked about a much bigger flat. What will it predict at most?Related

Answer: No more than the highest leaf average, around ₹90 lakh

Trees predict leaf averages, so they cannot go beyond the training range.

From Decision trees

Which model does NOT need feature scaling?Related

Answer: Random forest

Trees split one feature at a time on thresholds.

From Scaling and transforming numbers

Grouping shoppers into similar groups without any labels is…Related

Answer: Unsupervised learning (clustering)

No labels means unsupervised; grouping is clustering.

From What machine learning is

Why scale features before k-means?Related

Answer: So a feature with big numbers does not dominate the distances

Distances depend on units.

From Clustering with k-means

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 4 more topics in “k-NN, decision trees and ensembles” before its exam: Decision trees, Random forests and bagging, Gradient boosting, Choosing and explaining a model.
  2. Module 7 exam: k-NN, decision trees and ensembles · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Clustering, dimensionality reduction and feature engineering. 62 topics left in the course before the final exam.

← Previous: Cross-validation and tuning hyperparameters