Intermediate: machine learning · k-NN, decision trees and ensembles · topic 33 of 62 · 30 min
k-nearest neighbours
Explanation
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.
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.
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)))The algorithm
- Store all training examples (there is no real training step; k-NN is a "lazy learner").
- For a new point, compute its distance to every training example.
- Take the k closest.
- 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.
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))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-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)
Write euclidean(a, b) for two equal-length tuples of numbers, returning the straight-line distance rounded to 4 decimal places.
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.
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
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Decision treesk-NN, decision trees and ensembles · same module
- Random forests and baggingk-NN, decision trees and ensembles · same module
- Gradient boostingk-NN, decision trees and ensembles · same module
- Scaling and transforming numbersClustering, dimensionality reduction and feature engineering
- Clustering with k-meansClustering, dimensionality reduction and feature engineering
- Linear regression and least squaresThe ML workflow, regression and classification
Questions people ask about this
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.
Grouping shoppers into similar groups without any labels is…Related
Answer: Unsupervised learning (clustering)
No labels means unsupervised; grouping is clustering.
Why scale features before k-means?Related
Answer: So a feature with big numbers does not dominate the distances
Distances depend on units.
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
- 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.
- Module 7 exam: k-NN, decision trees and ensembles · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Clustering, dimensionality reduction and feature engineering. 62 topics left in the course before the final exam.