Thursday, September 19, 2024

How Manhattan Distance Works in KNN Machine Learning Algorithms

Manhattan Distance in KNN Explained Simply (With Examples)

Manhattan Distance in KNN (Super Simple Guide)

๐Ÿ“š Table of Contents


๐Ÿ“– What is KNN?

K-Nearest Neighbors (KNN) is a simple machine learning algorithm.

๐Ÿ’ก Idea: Find the closest points → use them to predict

If most nearby points belong to Class A → new point is also Class A.


๐Ÿ“ Why Distance Matters

KNN works completely based on distance.

๐Ÿ’ก No distance → no KNN Distance decides “who is closest”

Different distance methods can give different results.


๐Ÿ™ What is Manhattan Distance?

Manhattan Distance measures distance by moving only in straight lines.

No diagonal movement allowed.

Think of moving in a city:

  • Go left/right
  • Go up/down
  • No shortcuts
๐Ÿ’ก Like walking on roads, not flying across buildings

๐Ÿ“ Formula

Distance = sum of absolute differences

Distance = |x2 - x1| + |y2 - y1|

Distance should always be positive.

Absolute value removes negative signs.


๐Ÿ“Š Step-by-Step Example

Point A = (3, 5) Point B = (1, 9)

  1. |3 - 1| = 2
  2. |5 - 9| = 4
  3. Total = 2 + 4 = 6
๐Ÿ’ก Final Distance = 6

๐Ÿค– Manhattan Distance in KNN

Now let’s use this inside KNN.

New Point C = (2, 7)

  • X (1,5) → Class 1
  • Y (3,8) → Class 2
  • Z (4,6) → Class 1

C → X = 3 C → Y = 2 C → Z = 3

Closest = Y

If k = 2 → choose 2 closest → majority wins.


๐Ÿ’ป Code Example

from sklearn.neighbors import KNeighborsClassifier

X = [[1,5],[3,8],[4,6]]
y = [1,2,1]

model = KNeighborsClassifier(n_neighbors=2, metric='manhattan')
model.fit(X, y)

print(model.predict([[2,7]]))

๐Ÿ–ฅ CLI Output

[1]

Prediction = Class 1


๐Ÿ“Œ When to Use Manhattan Distance

  • Grid-based movement (maps, city routes)
  • When diagonal movement doesn’t make sense
  • High-dimensional data (sometimes better than Euclidean)

๐ŸŽฏ Key Takeaways

✔ KNN depends on distance ✔ Manhattan = straight-line movement only ✔ Easy to compute ✔ Works well for grid-like data


๐Ÿš€ Final Thought

Manhattan Distance is simple but powerful. It teaches an important idea: “How you measure distance changes your result.”

No comments:

Post a Comment

Featured Post

How HMT Watches Lost the Time: A Deep Dive into Disruptive Innovation Blindness in Indian Manufacturing

The Rise and Fall of HMT Watches: A Story of Brand Dominance and Disruptive Innovation Blindness The Rise and Fal...

Popular Posts