Skip to main content

K-Nearest Neighbors (KNN)

K-Nearest Neighbors Voting

The Most Intuitive Algorithm

Imagine you move to a new city and want to know if a neighborhood is safe. What do you do? You look at nearby neighborhoods. If 4 out of 5 nearby neighborhoods are safe → probably safe. If 4 out of 5 nearby neighborhoods are unsafe → probably unsafe. That’s KNN. To predict something, find the K most similar examples and use their labels. KNN is often called a “lazy learner” — not because it’s poorly designed, but because it does zero work during training. It just memorizes all the data and waits. All the computation happens at prediction time, when it searches for neighbors. This is the opposite of models like linear regression, which do all their work upfront during training and then predict instantly.
Movie Recommendation with KNN

The Movie Recommendation Problem

You just watched “The Matrix” and loved it. What should you watch next?

Finding Similar Movies

Output:
Recommendation: Watch Terminator or Inception next!

The KNN Algorithm

For Classification

For Regression

Instead of voting, average the values:

Real Example: Iris Classification


Choosing K: The Magic Number

K=1: Use only the closest neighbor
  • Very sensitive to noise
  • Can overfit
K=large: Use many neighbors
  • Smoother predictions
  • Can underfit
Rule of thumb: Start with k = sqrt(n) where n is training size. Also, use an odd number for K in binary classification to avoid ties (a 2-2 split has no winner, but 3-2 always does).

The Scaling Problem

KNN uses distance. If features have different scales, large-scale features dominate:
Solution: Scale your features!
Always scale your data before using KNN! Distance-based algorithms are sensitive to feature scales. Without scaling, a feature measured in thousands (like salary) will completely drown out a feature measured in single digits (like years of experience). The distance calculation will act as if only salary exists.This applies to KNN, SVM, and any algorithm that uses distances. Tree-based models (Decision Trees, Random Forest, XGBoost) are immune to this problem because they split on one feature at a time.See Feature Engineering for more on scaling strategies.

Distance Metrics

Euclidean isn’t the only option:
Math Connection: Distance metrics come from linear algebra concepts. See Vectors for more on measuring similarity.

Weighted KNN

Not all neighbors are equal! Closer neighbors should have more influence:

Pros and Cons

Advantages

  • Simple and intuitive
  • No training phase (lazy learner)
  • Works with any number of classes
  • Naturally handles multi-label
  • Non-parametric (no assumptions about data)

Disadvantages

  • Slow prediction (checks all training data)
  • Sensitive to irrelevant features
  • Sensitive to feature scaling
  • Struggles in high dimensions (curse of dimensionality)
  • Memory intensive (stores all data)

When to Use KNN

Good for:
  • Small to medium datasets
  • When you need interpretability (“these are the similar cases”)
  • Recommendation systems
  • Baseline model to beat
Avoid for:
  • Large datasets (slow prediction — it must scan every training point for each query)
  • High-dimensional data (100+ features) — the “curse of dimensionality” makes all points roughly equidistant, destroying the notion of “nearest”
  • When fast prediction is critical (consider tree-based models instead)
  • When you need to explain why the model made a decision (KNN says “these neighbors voted” but not what feature patterns drive the prediction)

Key Takeaways

Find Neighbors

Predict based on the K most similar examples

Vote or Average

Classification = majority vote, Regression = average

Scale Features

Distance-based algorithms need scaled data

Choose K Wisely

Use cross-validation to find the best K

What’s Next?

Now that you understand classification with both logistic regression and KNN, let’s learn about decision trees - a completely different approach!

Continue to Module 5: Decision Trees

Learn how trees make decisions - just like you do