Machine Learning 📂 Supervised Learning · 15 of 19 161 min read

Distance Metrics — Euclidean, Manhattan, Minkowski & Hamming

Master the four essential distance metrics powering machine learning — learn when to use straight-line Euclidean, city-grid Manhattan, generalised Minkowski, and bit-difference Hamming distances, with intuitive stories, step-by-step calculations, visual diagrams, and Python code.

🌐
SectionSection第 01 节

The Story That Explains Distance Metricsवह कहानी जो Distance Metrics समझाती है一个解释 Distance Metrics 的故事

Four Ways to Measure the Same Journeyएक ही सफ़र को मापने के चार तरीके测量同一段旅程的四种方法
Four explorers stand at City A. They all want to reach City B. Each one measures distance in a different way.

Euclid takes out a ruler. He draws a straight line from A to B. "This is the true distance," he says. It is the path a bird would fly. 5 km.

Manny comes from Manhattan. He shakes his head. "That line goes through buildings. I can only walk along streets. 3 blocks east, then 4 blocks north." 7 km.

Minka has a formula with a dial. The dial is called p. "Set it to 1 and I walk like Manny. Set it to 2 and I fly like Euclid." She is the general case.

Hamm does not care about maps. He compares DNA, passwords and binary codes. "My distance counts how many positions are different," he says.

Same two points. Four valid answers. The right one depends on what your data means.
चार explorers City A पर खड़े हैं। सभी को City B तक जाना है। हर कोई distance को अलग तरीके से मापता है।

Euclid एक ruler निकालता है। वह A से B तक एक सीधी line खींचता है। "यही असली distance है," वह कहता है। यह वह रास्ता है जिस पर पक्षी उड़ता है। 5 km.

Manny Manhattan से आया है। वह सिर हिलाता है। "यह line इमारतों के बीच से जाती है। मैं सिर्फ़ सड़कों पर चल सकता हूँ। 3 block पूर्व, फिर 4 block उत्तर।" 7 km.

Minka के पास एक formula है जिसमें एक dial है। इस dial का नाम p है। "इसे 1 पर रखो तो मैं Manny की तरह चलती हूँ। 2 पर रखो तो Euclid की तरह उड़ती हूँ।" वह general case है।

Hamm को नक्शों से मतलब नहीं। वह DNA, passwords और binary codes की तुलना करता है। "मेरी distance गिनती है कि कितनी positions अलग हैं," वह कहता है।

वही दो points. चार सही जवाब। सही metric इस पर निर्भर करता है कि आपका data क्या दर्शाता है।
四位 explorer 站在 City A,都想去 City B。每个人测量距离的方法都不一样。

Euclid 拿出一把尺子,从 A 到 B 画一条直线。"这才是真正的距离,"他说。这是鸟飞过去的路线。5 km。

Manny 来自 Manhattan。他摇摇头:"这条线穿过了大楼。我只能沿着街道走:先向东 3 个街区,再向北 4 个街区。"7 km。

Minka 有一个带旋钮的公式,旋钮叫 p。"调到 1,我像 Manny 一样走;调到 2,我像 Euclid 一样飞。"她代表 general case。

Hamm 不关心地图。他比较 DNA、密码和 binary code。"我的距离只数有多少个位置不同,"他说。

同样两个点,四个正确答案。选哪一个,取决于你的数据代表什么。
LIVELIVE互动The Race: Crow vs Taxi vs Chess Kingदौड़: कौआ vs Taxi vs शतरंज का राजा比赛:乌鸦 vs 出租车 vs 国际象棋的王

Three travellers go from A to B at the same time. Watch how each one counts its distance.

तीन यात्री एक साथ A से B जाते हैं। देखिए हर कोई अपनी distance कैसे गिनता है।

三位旅行者同时从 A 出发去 B。看看每个人是怎样计算距离的。

🐦 Crow
Euclidean
🐦 कौआ
Euclidean
🐦 乌鸦
Euclidean
0
🚕 Taxi
Manhattan
🚕 Taxi
Manhattan
🚕 出租车
Manhattan
0
♚ King
Chebyshev
♚ राजा
Chebyshev
♚ 王
Chebyshev
0

The crow flies straight (5.00). The taxi follows streets (7 blocks). The chess king can step diagonally, so it needs only 4 moves.

कौआ सीधा उड़ता है (5.00)। Taxi सड़कों पर चलती है (7 blocks)। शतरंज का राजा तिरछा भी चल सकता है, इसलिए उसे सिर्फ़ 4 moves चाहिए।

乌鸦直线飞行(5.00)。出租车沿街道走(7 个街区)。国际象棋的王可以斜着走,所以只需要 4 步。

📐
Why Distance Metrics Matter in Machine LearningMachine Learning में Distance Metrics क्यों ज़रूरी हैं为什么 Distance Metrics 在 Machine Learning 中很重要

Distance is the backbone of KNN, K-Means, DBSCAN, hierarchical clustering and similarity search. All of them ask one question: "How far apart are these two points?" Pick the wrong metric and you get the wrong neighbours and the wrong clusters. Good tuning cannot fix that.

Distance KNN, K-Means, DBSCAN, hierarchical clustering और similarity search की नींव है। ये सभी एक ही सवाल पूछते हैं: "ये दो points कितनी दूर हैं?" गलत metric चुनेंगे तो गलत neighbours और गलत clusters मिलेंगे। अच्छी tuning भी इसे ठीक नहीं कर सकती।

距离是 KNN、K-Means、DBSCAN、hierarchical clustering 和 similarity search 的基础。它们都在问同一个问题:"这两个点相距多远?"选错 metric,就会找到错误的 neighbour 和错误的 cluster。再好的调参也救不回来。


SectionSection第 02 节

Euclidean Distance — The Straight LineEuclidean Distance — सीधी LineEuclidean Distance — 直线距离

The Crow's Flightकौए की उड़ान乌鸦的飞行
A crow flies from nest A to nest B. It ignores roads, rivers and city blocks. It flies in a perfectly straight line. Euclidean distance is the length of that line. It is the shortest possible path between two points. It is what we usually mean when we say "how far apart".
एक कौआ घोंसले A से घोंसले B तक उड़ता है। वह सड़कों, नदियों और blocks की परवाह नहीं करता। वह बिल्कुल सीधी line में उड़ता है। Euclidean distance उसी line की लंबाई है। यह दो points के बीच सबसे छोटा रास्ता है। जब हम कहते हैं "कितनी दूर", तो आमतौर पर यही मतलब होता है।
一只乌鸦从鸟巢 A 飞到鸟巢 B。它不管道路、河流和街区,只沿一条笔直的线飞。Euclidean distance 就是这条线的长度。它是两点之间最短的路径,也是我们平时说"相距多远"时的意思。
Euclidean Distance — 2DEuclidean Distance — 2DEuclidean Distance — 二维
d = √((x₂−x₁)² + (y₂−y₁)²)
The Pythagorean theorem. d is the hypotenuse of the right triangle formed by the two differences.
Pythagoras theorem. d उस right triangle का hypotenuse है जो दोनों differences से बनता है।
就是勾股定理。d 是由两个差值构成的直角三角形的斜边。
Euclidean Distance — n DimensionsEuclidean Distance — n DimensionsEuclidean Distance — n 维
d = √Σᵢ (aᵢ − bᵢ)²
Square the difference in every dimension, add them, then take the square root. Also called the L2 norm.
हर dimension का difference square करें, जोड़ें, फिर square root लें। इसे L2 norm भी कहते हैं।
把每个维度的差值平方后相加,再开平方。也叫 L2 norm。

Let us work through an example. Point A = (1, 2) and Point B = (4, 6).

एक उदाहरण देखें। Point A = (1, 2) और Point B = (4, 6).

来看一个例子:Point A = (1, 2),Point B = (4, 6)。

📐 Euclidean Distance — Step by StepEuclidean Distance — Step by StepEuclidean Distance — 逐步计算
PlotPlot画点
A is at (1, 2). B is at (4, 6). The gaps form the two legs of a right triangle.A (1, 2) पर है। B (4, 6) पर है। दोनों gaps एक right triangle की दो भुजाएँ बनाते हैं।A 在 (1, 2),B 在 (4, 6)。两个差值构成直角三角形的两条直角边。
Δx
Horizontal gap: 4 − 1 = Horizontal gap: 4 − 1 = 水平差:4 − 1 = 3
Δy
Vertical gap: 6 − 2 = Vertical gap: 6 − 2 = 垂直差:6 − 2 = 4
SquareSquare平方
3² + 4² = 9 + 16 = 25
√
√25 = 5.00 — the length of the straight line — सीधी line की लंबाई — 直线的长度
📐 EUCLIDEAN DISTANCE — STRAIGHT LINE ON A GRIDEUCLIDEAN DISTANCE — GRID पर सीधी LINEEUCLIDEAN DISTANCE — 坐标网格上的直线
Euclidean distance A at (1,2), B at (4,6). Straight line of length 5, legs 3 and 4. 1 1 2 2 3 3 4 4 5 5 6 6 7 7 x y Δx = 3 Δy = 4 d = 5.00 A (1,2) B (4,6) Euclidean (hypotenuse) Δx (horizontal leg) Δy (vertical leg) d = √(Δx² + Δy²) = √(9 + 16) = √25 = 5
⚠️
Euclidean Distance Is Very Sensitive to ScaleEuclidean Distance, Scale के प्रति बहुत sensitive हैEuclidean Distance 对 Scale 非常敏感

If one feature ranges over [0, 100,000] (salary) and another over [20, 60] (age), salary will dominate the distance. Age will barely count. Always apply StandardScaler or MinMaxScaler before KNN, K-Means or PCA. Try it below.

अगर एक feature की range [0, 100,000] (salary) है और दूसरे की [20, 60] (age), तो salary पूरी distance पर हावी हो जाएगी। Age लगभग गिनी ही नहीं जाएगी। KNN, K-Means या PCA से पहले हमेशा StandardScaler या MinMaxScaler लगाएँ। नीचे खुद आज़माएँ।

如果一个 feature 的范围是 [0, 100,000](salary),另一个是 [20, 60](age),salary 会主导整个距离,age 几乎不起作用。在 KNN、K-Means 或 PCA 之前,一定要先用 StandardScaler 或 MinMaxScaler。下面亲自试一试。

LIVELIVE互动Feature Scaling SimulatorFeature Scaling SimulatorFeature Scaling 模拟器

Who is most similar to person A? The bars show how much each feature adds to the Euclidean distance. Press the button to scale the features.

Person A से सबसे ज़्यादा मिलता-जुलता कौन है? Bars दिखाते हैं कि हर feature Euclidean distance में कितना योगदान देता है। Features को scale करने के लिए button दबाएँ।

谁和 A 最相似?条形图显示每个 feature 对 Euclidean distance 的贡献。点击按钮对 feature 做 scaling。

PersonPerson人agesalary (₹)
A2550,000
B6052,000
C2660,000
A → B   d =
A → C   d =
MinMax: age ÷ 40 (range 20–60), salary ÷ 80,000 (range 20k–100k)

Properties of Euclidean DistanceEuclidean Distance की PropertiesEuclidean Distance 的性质

PropertyProperty性质ValueValue表达式What It Meansमतलब含义
Non-negativityd(A,B) ≥ 0Distance is never negativeDistance कभी negative नहीं होती距离永远不为负
Identityd(A,A) = 0A point is at distance zero from itselfPoint की खुद से distance zero है一个点到自身的距离为 0
Symmetryd(A,B) = d(B,A)A to B equals B to AA से B = B से AA 到 B 等于 B 到 A
Triangle Inequalityd(A,C) ≤ d(A,B) + d(B,C)A detour through a third point is never shorterतीसरे point से घूमकर जाना कभी छोटा नहीं होता绕道经过第三个点永远不会更短
Outlier sensitivityOutlier sensitivityOutlier 敏感度HighSquaring makes big gaps even biggerSquare करने से बड़े gaps और बड़े हो जाते हैं平方会把大的差值放得更大

SectionSection第 03 节

Manhattan Distance — The City GridManhattan Distance — शहर का GridManhattan Distance — 城市网格

The Manhattan Taxi DriverManhattan का Taxi DriverManhattan 的出租车司机
You are in a New York taxi. You go from 1st Avenue & 42nd Street to 4th Avenue & 46th Street. A crow overhead flies 5 blocks in a straight line. But your taxi cannot drive through buildings. It goes 3 blocks east, then 4 blocks north. Total: 7 blocks.

That is Manhattan distance. You add the absolute gaps on each axis. It is also called taxicab distance, city block distance or the L1 norm.
आप New York की taxi में हैं। आपको 1st Avenue & 42nd Street से 4th Avenue & 46th Street जाना है। ऊपर उड़ता कौआ सीधी line में 5 blocks तय करता है। पर taxi इमारतों के बीच से नहीं जा सकती। वह 3 blocks पूर्व, फिर 4 blocks उत्तर जाती है। कुल: 7 blocks.

यही Manhattan distance है। हर axis का absolute gap जोड़ दें। इसे taxicab distance, city block distance या L1 norm भी कहते हैं।
你坐在纽约的出租车里,从 1st Avenue & 42nd Street 去 4th Avenue & 46th Street。头顶的乌鸦直线飞 5 个街区。但出租车不能穿过大楼,只能先向东 3 个街区,再向北 4 个街区,一共 7 个街区。

这就是 Manhattan distance:把每个坐标轴上的绝对差值加起来。它也叫 taxicab distance、city block distance 或 L1 norm。
Manhattan Distance — 2D
d = |x₂ − x₁| + |y₂ − y₁|
Add the absolute gaps on each axis. No squaring, so outliers are not amplified as much.
हर axis के absolute gaps जोड़ें। Square नहीं होता, इसलिए outliers का असर कम बढ़ता है।
把每个轴上的绝对差值相加。没有平方,所以 outlier 的影响不会被放大那么多。
Manhattan Distance — n Dimensions
d = Σᵢ |aᵢ − bᵢ|
Also called the L1 norm. Used in LASSO regression, robust statistics and high-dimensional data.
इसे L1 norm भी कहते हैं। LASSO regression, robust statistics और high-dimensional data में उपयोग होता है।
也叫 L1 norm。用于 LASSO regression、robust statistics 和高维数据。
🏙️ Manhattan Distance — Step by StepManhattan Distance — Step by StepManhattan Distance — 逐步计算
Grid
Same points: A = (1, 2), B = (4, 6). You cannot cut diagonally. Every move is horizontal or vertical.वही points: A = (1, 2), B = (4, 6)। आप तिरछा नहीं जा सकते। हर move horizontal या vertical है।同样的点:A = (1, 2),B = (4, 6)。不能斜着走,每一步只能横走或竖走。
East →
|4 − 1| = 3 blocks
North ↑
|6 − 2| = 4 blocks
Total
3 + 4 = 7.00 — always ≥ Euclidean (5.00) — हमेशा Euclidean (5.00) से ≥ — 总是 ≥ Euclidean(5.00)
NoteNote注意
There are exactly 35 shortest routes (choose which 3 of the 7 moves go east: C(7,3) = 35). All have length 7.ठीक 35 सबसे छोटे रास्ते हैं (7 moves में से कौन-से 3 पूर्व जाएँ: C(7,3) = 35)। सभी की लंबाई 7 है।一共恰好有 35 条最短路线(从 7 步中选 3 步向东:C(7,3) = 35)。每条长度都是 7。
🏙️ MANHATTAN DISTANCE — CITY GRID ROUTESMANHATTAN DISTANCE — शहर के GRID पर रास्तेMANHATTAN DISTANCE — 城市网格路线
Manhattan distance City grid. Three routes from A(1,2) to B(4,6), each 7 blocks. Straight line 5 shown for comparison. 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 A (1,2) B (4,6) Route 1: right, then up Route 2: up, then right Route 3: staircase Euclidean d = 5 (compare) Manhattan = |Δx| + |Δy| = 3 + 4 = 7.00 Every shortest route = 7 blocks
LIVELIVE互动Taxi Route SimulatorTaxi Route Simulator出租车路线模拟器

Set where B is. Then drive random routes. Every route looks different, but the length never changes.

B की जगह चुनें। फिर random रास्ते चलाएँ। हर रास्ता अलग दिखता है, पर लंबाई कभी नहीं बदलती।

设置 B 的位置,然后随机开几条路线。每条路线看起来都不同,但长度从不改变。

Manhattan
Euclidean
Shortest routes C(Δx+Δy, Δx)सबसे छोटे रास्ते C(Δx+Δy, Δx)最短路线数 C(Δx+Δy, Δx)
Routes drivenचलाए गए रास्ते已开路线

🛡️
Manhattan Distance Is More Robust to OutliersManhattan Distance, Outliers के प्रति ज़्यादा Robust हैManhattan Distance 对 Outlier 更稳健

Manhattan uses absolute differences, not squares. A big outlier has a linear effect, not a quadratic one. In LASSO regression, the L1 penalty gives sparse solutions: many coefficients become exactly zero. The L2 penalty (Ridge) does not do this.

Manhattan absolute differences इस्तेमाल करता है, squares नहीं। बड़े outlier का असर linear होता है, quadratic नहीं। LASSO regression में L1 penalty sparse solutions देती है: कई coefficients बिल्कुल zero हो जाते हैं। L2 penalty (Ridge) ऐसा नहीं करती।

Manhattan 使用绝对差值而不是平方。大的 outlier 只产生线性影响,而不是平方影响。在 LASSO regression 中,L1 penalty 会产生 sparse solution:很多系数会变成正好为 0。L2 penalty(Ridge)做不到这一点。

Manhattan vs Euclidean — Key DifferencesManhattan vs Euclidean — मुख्य अंतरManhattan vs Euclidean — 主要区别

Aspectपहलू方面Euclidean (L2)Manhattan (L1)
FormulaFormula公式√Σ(aᵢ−bᵢ)²Σ|aᵢ−bᵢ|
Path typeरास्ता路径Straight lineसीधी line直线Axis-aligned stepsAxis के साथ steps沿坐标轴的台阶
Result (A→B)Result (A→B)结果 (A→B)5.007.00
Outlier sensitivityOutlier sensitivityOutlier 敏感度High — squares gapsHigh — gaps को square करता है高 — 对差值求平方Lower — linear gapsकम — linear gaps较低 — 线性差值
High-dimensional dataHigh-dimensional data高维数据Loses contrast fasterContrast जल्दी खोता है区分度下降更快Keeps more contrastज़्यादा contrast बचाता है保留更多区分度
Best forBest for适用于Continuous, low-dimensional dataContinuous, low-dimensional data连续、低维数据High-dimensional, noisy, sparse dataHigh-dimensional, noisy, sparse data高维、有噪声、稀疏数据
Used inUsed in用于KNN, K-Means, PCA, SVM (RBF)LASSO, robust KNN, image processing, NLP

SectionSection第 04 节

Minkowski Distance — The Unifying FormulaMinkowski Distance — सबको जोड़ने वाला FormulaMinkowski Distance — 统一公式

Minkowski distance is not a new metric. It is a family of metrics with one dial, p. Manhattan and Euclidean are two settings of that dial.

Minkowski distance कोई नया metric नहीं है। यह एक dial p वाला metrics का परिवार है। Manhattan और Euclidean उसी dial की दो settings हैं।

Minkowski distance 不是新的 metric,而是一个带有旋钮 p 的 metric 家族。Manhattan 和 Euclidean 只是这个旋钮的两个档位。

Minkowski Distance
d = (Σᵢ |aᵢ − bᵢ|ᵖ)^(1/p)
The general Lp norm. Any p ≥ 1 gives a true metric.
General Lp norm. कोई भी p ≥ 1 एक true metric देता है।
通用的 Lp norm。任何 p ≥ 1 都是 true metric。
Chebyshev (p → ∞)
d = max |aᵢ − bᵢ|
As p grows, only the largest gap matters. This is the L∞ distance. A chess king moves this way.
p बढ़ने पर सिर्फ़ सबसे बड़ा gap मायने रखता है। यह L∞ distance है। शतरंज का राजा इसी तरह चलता है।
p 越大,只有最大的差值才起作用。这就是 L∞ distance。国际象棋的王就是这样走的。
pNameनाम名称FormulaFormula公式Result (A→B)Result (A→B)结果 (A→B)Unit ball shapeUnit ball का आकारUnit ball 形状
p = 1Manhattan / L1Σ|aᵢ−bᵢ|7.00DiamondDiamond (हीरा)菱形
p = 2Euclidean / L2√Σ(aᵢ−bᵢ)²5.00CircleCircle圆
p = 3Minkowski L3(Σ|aᵢ−bᵢ|³)^(1/3)4.50Between circle and squareCircle और square के बीच介于圆和正方形之间
p = 4Minkowski L4(Σ|aᵢ−bᵢ|⁴)^(1/4)4.28Rounded squareगोल कोनों वाला square圆角正方形
p → ∞Chebyshev / L∞max|aᵢ−bᵢ|4.00SquareSquare正方形
🧮 Minkowski — A=(1,2) to B=(4,6) for different pMinkowski — अलग-अलग p के लिए A=(1,2) से B=(4,6)Minkowski — 不同 p 下 A=(1,2) 到 B=(4,6)
Δ
|4−1| = 3 and |6−2| = 4 (same for every p)|4−1| = 3 और |6−2| = 4 (हर p के लिए वही)|4−1| = 3,|6−2| = 4(对所有 p 都一样)
p = 1
3 + 4 = 7.00 → Manhattan
p = 2
(9 + 16)^½ = 25^½ = 5.00 → Euclidean
p = 3
(27 + 64)^⅓ = 91^⅓ = 4.50
p = 4
(81 + 256)^¼ = 337^¼ = 4.28
p → ∞
max(3, 4) = 4.00 → Chebyshev
⭕ MINKOWSKI UNIT BALLS — SHAPE CHANGES WITH pMINKOWSKI UNIT BALLS — p के साथ आकार बदलता हैMINKOWSKI UNIT BALLS — 形状随 p 变化
Minkowski unit balls Unit balls for p = 1, 2, 4, 10 and infinity: diamond, circle, rounded square, near square, square. p = 1 Manhattan p = 2 Euclidean p = 4 p = 10 p → ∞ Chebyshev All shapes: points at distance exactly 1 from the centre A=(1,2) → B=(4,6): 7.00 → 5.00 → 4.28 → 4.02 → 4.00
LIVELIVE互动Minkowski p-Dial SimulatorMinkowski p-Dial SimulatorMinkowski p 旋钮模拟器

Turn the p dial. The green shape shows all points at distance 1. Dashed outlines: p = 1 (red), p = 2 (amber), p = ∞ (purple). Try p below 1 too.

p dial घुमाएँ। हरा आकार वे सभी points दिखाता है जिनकी distance 1 है। Dashed outlines: p = 1 (लाल), p = 2 (पीला), p = ∞ (बैंगनी)। p को 1 से कम भी करके देखें।

转动 p 旋钮。绿色形状是所有距离为 1 的点。虚线轮廓:p = 1(红)、p = 2(橙)、p = ∞(紫)。也试试 p 小于 1。

Distance A=(1,2) → B=(4,6)Distance A=(1,2) → B=(4,6)距离 A=(1,2) → B=(4,6):
d
0
Weight of the largest gap (4)सबसे बड़े gap (4) का weight最大差值 (4) 的权重
0

Watch the purple bar. As p grows, the largest gap takes over. That is why d falls from 7 toward 4.

बैंगनी bar देखें। p बढ़ने पर सबसे बड़ा gap हावी हो जाता है। इसीलिए d, 7 से घटकर 4 की ओर जाती है।

看紫色条。p 越大,最大的差值越占主导,所以 d 从 7 降到接近 4。

📉
Key Insight — As p Increases, Distance Decreasesमुख्य बात — p बढ़ने पर Distance घटती है关键点 — p 越大,距离越小

Manhattan (p = 1) always gives the largest distance. As p increases, the result shrinks toward Chebyshev (p = ∞), the biggest single gap. Higher p gives more weight to the largest gap and less to the small ones.

Manhattan (p = 1) हमेशा सबसे बड़ी distance देता है। p बढ़ने पर result घटकर Chebyshev (p = ∞) यानी सबसे बड़े single gap की ओर जाता है। ज़्यादा p, सबसे बड़े gap को ज़्यादा weight और छोटे gaps को कम weight देता है।

Manhattan(p = 1)总是给出最大的距离。p 增大时,结果会缩小,趋近 Chebyshev(p = ∞),也就是最大的单个差值。p 越大,最大差值的权重越高,小差值的权重越低。

The Unit Ball — What Each p Looks LikeUnit Ball — हर p कैसा दिखता हैUnit Ball — 每个 p 的样子

🔷
p = 1 (Manhattan)
DiamondDiamond菱形
Points at distance 1 form a diamond with sharp corners on the axes. LASSO uses this shape to push coefficients to zero.
Distance 1 वाले points एक diamond बनाते हैं, जिसके नुकीले कोने axes पर होते हैं। LASSO इसी आकार से coefficients को zero करता है।
距离为 1 的点组成一个菱形,尖角落在坐标轴上。LASSO 正是利用这个形状把系数压到 0。
⭕
p = 2 (Euclidean)
Circle / SphereCircle / Sphere圆 / 球
A perfect circle in 2D and a sphere in 3D. It treats all directions equally.
2D में पूरा circle और 3D में sphere। यह हर direction को बराबर मानता है।
二维是正圆,三维是球。它对所有方向一视同仁。
🔵
p = 3, 4, …
SuperellipseSuperellipse超椭圆
Above 2, the shape bulges out toward a square. It sits between the circle and the square. Rarely used directly.
2 से ऊपर आकार बाहर फूलकर square की ओर जाता है। यह circle और square के बीच है। सीधे बहुत कम इस्तेमाल होता है।
p 大于 2 时,形状向外鼓起,逐渐接近正方形,介于圆和正方形之间。实际中很少直接使用。
🟦
p → ∞ (Chebyshev)
Square / HypercubeSquare / Hypercube正方形 / 超立方体
A square in 2D. Only the single largest gap counts. A chess king moving one square in any direction follows this rule.
2D में square. सिर्फ़ सबसे बड़ा gap गिना जाता है। किसी भी दिशा में एक खाना चलने वाला शतरंज का राजा इसी नियम पर चलता है।
二维是正方形,只有最大的差值才算数。国际象棋的王向任意方向走一格,就遵循这个规则。

SectionSection第 05 节

Hamming Distance — Comparing SequencesHamming Distance — Sequences की तुलनाHamming Distance — 比较序列

The DNA Analyst and the Network EngineerDNA Analyst और Network EngineerDNA 分析师和网络工程师
A DNA analyst lines up two genetic sequences. She counts the positions that differ:

Sequence 1: GAATTCGACT
Sequence 2: GAATCCGAGT

Position 5: T vs C, different. Position 9: C vs G, different. All other positions match. Hamming distance = 2.

A network engineer checks a data packet. He sent 10110101 and received 10010100. Bits 3 and 8 flipped. Hamming distance = 2. Any Hamming distance above 0 means at least one error happened.

Hamming distance only counts how many positions differ between two sequences of the same length. No geometry. No coordinates.
एक DNA analyst दो genetic sequences को लाइन में रखती है। वह अलग positions गिनती है:

Sequence 1: GAATTCGACT
Sequence 2: GAATCCGAGT

Position 5: T vs C, अलग। Position 9: C vs G, अलग। बाकी सब positions मेल खाती हैं। Hamming distance = 2.

एक network engineer data packet जाँचता है। उसने 10110101 भेजा और 10010100 मिला। Bits 3 और 8 पलट गए। Hamming distance = 2. Hamming distance 0 से ज़्यादा हो तो कम से कम एक error हुई है।

Hamming distance सिर्फ़ यह गिनती है कि बराबर लंबाई की दो sequences में कितनी positions अलग हैं। कोई geometry नहीं। कोई coordinates नहीं।
一位 DNA 分析师把两条基因序列对齐,数出不同的位置:

Sequence 1: GAATTCGACT
Sequence 2: GAATCCGAGT

第 5 位:T 对 C,不同。第 9 位:C 对 G,不同。其余位置都相同。Hamming distance = 2。

一位网络工程师检查数据包。他发送 10110101,收到 10010100。第 3 位和第 8 位翻转了。Hamming distance = 2。只要 Hamming distance 大于 0,就说明至少出了一个错误。

Hamming distance 只统计两个等长序列中有多少个位置不同。没有几何,没有坐标。
Hamming Distance (count)Hamming Distance (गिनती)Hamming Distance(计数)
d = #{i : aᵢ ≠ bᵢ}
Count the positions where a and b differ. Both must have the same length. Result is a whole number from 0 to n.
जहाँ a और b अलग हैं, वे positions गिनें। दोनों की लंबाई बराबर होनी चाहिए। Result 0 से n तक की पूर्ण संख्या है।
数出 a 和 b 不同的位置。两者长度必须相同。结果是 0 到 n 之间的整数。
Normalised Hamming DistanceNormalised Hamming Distance归一化 Hamming Distance
d = #{i : aᵢ ≠ bᵢ} / n
Divide by the length n to get a value in [0, 1]. 0 means identical. 1 means every position differs. scipy returns this version.
[0, 1] में value पाने के लिए length n से भाग दें। 0 मतलब एकदम same. 1 मतलब हर position अलग। scipy यही version देता है।
除以长度 n,得到 [0, 1] 之间的值。0 表示完全相同,1 表示每个位置都不同。scipy 返回的就是这个版本。
🧬 Hamming — "KAROLIN" vs "KATHRIN"Hamming — "KAROLIN" vs "KATHRIN"Hamming — "KAROLIN" vs "KATHRIN"
Pos 1
K vs K → ✓
Pos 2
A vs A → ✓
Pos 3
R vs T → ✗ (count: 1)
Pos 4
O vs H → ✗ (count: 2)
Pos 5
L vs R → ✗ (count: 3)
Pos 6
I vs I → ✓
Pos 7
N vs N → ✓
Result
Hamming = 3  |  Normalised = 3/7 = 0.429
🧬 HAMMING DISTANCE — POSITION-BY-POSITION COMPARISONHAMMING DISTANCE — हर POSITION की तुलनाHAMMING DISTANCE — 逐位比较
Hamming distance Three examples: KAROLIN vs KATHRIN (3), 10110101 vs 10010100 (2), GAATTCGACT vs GAATCCGAGT (2). Example 1: strings Seq A Seq B K K ✓ A A ✓ R T ✗ O H ✗ L R ✗ I I ✓ N N ✓ Hamming = 3 3 of 7 differ Normalised = 0.43 Example 2: binary transmission Sent Rcvd 1 1 ✓ 0 0 ✓ 1 0 ✗ 1 1 ✓ 0 0 ✓ 1 1 ✓ 0 0 ✓ 1 0 ✗ Hamming = 2 2 of 8 differ Normalised = 0.25 Example 3: DNA Seq 1 Seq 2 G G ✓ A A ✓ A A ✓ T T ✓ T C ✗ C C ✓ G G ✓ A A ✓ C G ✗ T T ✓ Hamming = 2 2 of 10 differ Normalised = 0.20
LIVELIVE互动Hamming Lab: Type, Compare, Add NoiseHamming Lab: Type करें, तुलना करें, Noise डालेंHamming 实验室:输入、比较、加噪声

Type two sequences, or pick a preset. Then send A through a noisy channel and watch errors appear.

दो sequences type करें या कोई preset चुनें। फिर A को noisy channel से भेजें और errors आते देखें।

输入两个序列,或选择一个预设。然后让 A 通过有噪声的信道,看看错误是怎么出现的。

A
B
💾 Hamming — Binary Error Detection (scipy example below)Hamming — Binary Error Detection (नीचे scipy example)Hamming — 二进制错误检测(下面的 scipy 示例)
Sentभेजा发送
1 0 1 1 1 0 1
Receivedमिला接收
1 0 0 1 0 0 1
Compareतुलना比较
Bit 1 ✓   Bit 2 ✓   Bit 3 1≠0 ✗   Bit 4 ✓   Bit 5 1≠0 ✗   Bit 6 ✓   Bit 7 ✓
Result
Hamming = 2 — two bits flipped in transmission — transmission में दो bits पलटे — 传输中有两个 bit 翻转
⚠️
Hamming Needs Equal-Length SequencesHamming के लिए बराबर Length ज़रूरी हैHamming 要求序列等长

Hamming distance is undefined for sequences of different lengths. For those, use Levenshtein (edit) distance, which allows insertions and deletions. For feature vectors, use Hamming only when features are binary or categorical, never continuous.

अलग लंबाई की sequences के लिए Hamming distance defined नहीं है। उनके लिए Levenshtein (edit) distance इस्तेमाल करें, जो insertions और deletions की अनुमति देता है। Feature vectors पर Hamming तभी लगाएँ जब features binary या categorical हों, continuous कभी नहीं।

长度不同的序列,Hamming distance 没有定义。这种情况请用 Levenshtein (edit) distance,它允许插入和删除。对 feature vector,只有当 feature 是 binary 或 categorical 时才用 Hamming,连续值绝对不要用。


SectionSection第 06 节

Side by Side — All Metrics on the Same Dataसाथ-साथ — एक ही Data पर सभी Metrics并排比较 — 同一数据上的所有 Metric

Apply every metric to the same two points: A = (1, 2, 3) and B = (4, 6, 3).

हर metric को एक ही दो points पर लगाएँ: A = (1, 2, 3) और B = (4, 6, 3).

把每个 metric 用在同样两个点上:A = (1, 2, 3) 和 B = (4, 6, 3)。

MetricCalculationCalculation计算ResultResult结果Norm
Euclidean√(3² + 4² + 0²) = √255.00L2
Manhattan3 + 4 + 07.00L1
Minkowski p=3(27 + 64 + 0)^(1/3)4.50L3
Chebyshevmax(3, 4, 0)4.00L∞
HammingPositions that are unequal: 2 of 3 (only to show the idea — not useful for continuous data)असमान positions: 3 में से 2 (सिर्फ़ idea दिखाने के लिए — continuous data के लिए उपयोगी नहीं)不相等的位置:3 个中有 2 个(仅用于演示 — 对连续数据没有意义)2/3 ≈ 0.67—
LIVELIVE互动Distance Playground — Drag the PointsDistance Playground — Points को खींचेंDistance 游乐场 — 拖动点

Drag A or B (or tap the grid). The dashed shapes are centred on A and all pass through B: the diamond (Manhattan), circle (Euclidean) and square (Chebyshev).

A या B को खींचें (या grid पर tap करें)। Dashed आकार A पर केंद्रित हैं और सभी B से गुज़रते हैं: diamond (Manhattan), circle (Euclidean) और square (Chebyshev)।

拖动 A 或 B(或点击网格)。虚线形状以 A 为中心,并且都经过 B:菱形(Manhattan)、圆(Euclidean)和正方形(Chebyshev)。

Euclidean
0
Manhattan
0
Chebyshev
0
Minkowski
0

Try putting B straight above A. All three metrics become equal. Then put B on a diagonal and see them spread apart.

B को A के ठीक ऊपर रखें। तीनों metrics बराबर हो जाते हैं। फिर B को diagonal पर रखें और उन्हें अलग होते देखें।

把 B 放在 A 的正上方,三个 metric 会相等。再把 B 放到对角线上,看它们如何拉开差距。

📊
The Order Is Always: Chebyshev ≤ Euclidean ≤ Manhattanक्रम हमेशा: Chebyshev ≤ Euclidean ≤ Manhattan顺序永远是:Chebyshev ≤ Euclidean ≤ Manhattan

For any two points in any dimension, Chebyshev ≤ Euclidean ≤ Manhattan. This is a mathematical fact. Chebyshev keeps only the largest gap (smallest result). Manhattan adds all gaps (largest result). Euclidean sits in between.

किसी भी dimension में किन्हीं भी दो points के लिए Chebyshev ≤ Euclidean ≤ Manhattan. यह गणित का नियम है। Chebyshev सिर्फ़ सबसे बड़ा gap रखता है (सबसे छोटा result)। Manhattan सभी gaps जोड़ता है (सबसे बड़ा result)। Euclidean बीच में है।

在任何维度中,对任意两个点都有 Chebyshev ≤ Euclidean ≤ Manhattan。这是数学事实。Chebyshev 只保留最大的差值(结果最小),Manhattan 把所有差值相加(结果最大),Euclidean 居中。


SectionSection第 07 节

Python ImplementationPython ImplementationPython 实现

All Distances — From Scratchसभी Distances — Scratch से所有距离 — 从零实现

import numpy as np

# ── Euclidean Distance (L2) ───────────────────────────────────
def euclidean(a, b):
    a, b = np.asarray(a, dtype=float), np.asarray(b, dtype=float)
    return np.sqrt(np.sum((a - b) ** 2))

# ── Manhattan Distance (L1) ───────────────────────────────────
def manhattan(a, b):
    a, b = np.asarray(a, dtype=float), np.asarray(b, dtype=float)
    return np.sum(np.abs(a - b))

# ── Minkowski Distance (Lp) ── p=1 Manhattan, p=2 Euclidean ──
def minkowski(a, b, p=2):
    a, b = np.asarray(a, dtype=float), np.asarray(b, dtype=float)
    if p == np.inf:
        return np.max(np.abs(a - b))          # Chebyshev
    return np.sum(np.abs(a - b) ** p) ** (1 / p)

# ── Hamming Distance ──────────────────────────────────────────
def hamming(a, b, normalise=False):
    if len(a) != len(b):
        raise ValueError("Sequences must be the same length")
    count = sum(x != y for x, y in zip(a, b))
    return count / len(a) if normalise else count

A = [1, 2, 3]
B = [4, 6, 3]

print(f"Euclidean    : {euclidean(A, B):.4f}")
print(f"Manhattan    : {manhattan(A, B):.4f}")
print(f"Minkowski p=1: {minkowski(A, B, p=1):.4f}")
print(f"Minkowski p=2: {minkowski(A, B, p=2):.4f}")
print(f"Minkowski p=3: {minkowski(A, B, p=3):.4f}")
print(f"Chebyshev    : {minkowski(A, B, p=np.inf):.4f}")

s1, s2 = "KAROLIN", "KATHRIN"
print(f"\nHamming (raw):        {hamming(s1, s2)}")
print(f"Hamming (normalised): {hamming(s1, s2, normalise=True):.4f}")
OUTPUT
Euclidean : 5.0000 Manhattan : 7.0000 Minkowski p=1: 7.0000 Minkowski p=2: 5.0000 Minkowski p=3: 4.4979 Chebyshev : 4.0000 Hamming (raw): 3 Hamming (normalised): 0.4286

Using scipy — Production-Grade Functionsscipy का उपयोग — Production-Grade Functions使用 scipy — 生产级函数

Note: scipy's hamming() returns the normalised value. Multiply by the length to get the raw count.

ध्यान दें: scipy का hamming() normalised value देता है। Raw count के लिए length से गुणा करें।

注意:scipy 的 hamming() 返回的是归一化的值。乘以长度才得到原始计数。

from scipy.spatial.distance import euclidean, cityblock, minkowski, chebyshev, hamming
import numpy as np

A = np.array([1, 2, 3], dtype=float)
B = np.array([4, 6, 3], dtype=float)

print(f"Euclidean  : {euclidean(A, B):.4f}")
print(f"Manhattan  : {cityblock(A, B):.4f}")
print(f"Minkowski 3: {minkowski(A, B, p=3):.4f}")
print(f"Chebyshev  : {chebyshev(A, B):.4f}")

b1 = np.array([1, 0, 1, 1, 1, 0, 1])
b2 = np.array([1, 0, 0, 1, 0, 0, 1])
print(f"Hamming    : {hamming(b1, b2):.4f}")          # normalised
print(f"Hamming raw: {hamming(b1, b2) * len(b1):.0f} positions differ")
OUTPUT
Euclidean : 5.0000 Manhattan : 7.0000 Minkowski 3: 4.4979 Chebyshev : 4.0000 Hamming : 0.2857 Hamming raw: 2 positions differ

Distance Matrix — All Pairs at OnceDistance Matrix — सभी Pairs एक साथDistance Matrix — 一次计算所有点对

Columns are age, weight-like value and BMI-like value. The data is not scaled, so the second column dominates every matrix.

Columns हैं age, एक weight जैसी value और एक BMI जैसी value. Data scaled नहीं है, इसलिए हर matrix पर दूसरा column हावी है।

三列分别是 age、类似体重的值和类似 BMI 的值。数据没有做 scaling,所以每个矩阵都被第二列主导。

import numpy as np
import pandas as pd
from scipy.spatial.distance import pdist, squareform

X = np.array([
    [25, 80,  22.0],
    [35, 150, 28.5],
    [45, 180, 33.0],
    [28, 90,  23.5],
    [50, 200, 35.5],
])
names = [f"P{i+1}" for i in range(len(X))]

for metric in ['euclidean', 'cityblock', 'chebyshev']:
    D = squareform(pdist(X, metric=metric))
    df = pd.DataFrame(D.round(1), index=names, columns=names)
    print(f"\n{metric.upper()} distance matrix:")
    print(df.to_string())
OUTPUT
EUCLIDEAN distance matrix: P1 P2 P3 P4 P5 P1 0.0 71.0 102.6 10.5 123.3 P2 71.0 0.0 31.9 60.6 52.7 P3 102.6 31.9 0.0 92.1 20.8 P4 10.5 60.6 92.1 0.0 112.8 P5 123.3 52.7 20.8 112.8 0.0 CITYBLOCK distance matrix: P1 P2 P3 P4 P5 P1 0.0 86.5 131.0 14.5 158.5 P2 86.5 0.0 44.5 72.0 72.0 P3 131.0 44.5 0.0 116.5 27.5 P4 14.5 72.0 116.5 0.0 144.0 P5 158.5 72.0 27.5 144.0 0.0 CHEBYSHEV distance matrix: P1 P2 P3 P4 P5 P1 0.0 70.0 100.0 10.0 120.0 P2 70.0 0.0 30.0 60.0 50.0 P3 100.0 30.0 0.0 90.0 20.0 P4 10.0 60.0 90.0 0.0 110.0 P5 120.0 50.0 20.0 110.0 0.0

Comparing Metrics in KNNKNN में Metrics की तुलना在 KNN 中比较 Metric

from sklearn.datasets import load_iris
from sklearn.model_selection import cross_val_score
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler

X, y = load_iris(return_X_y=True)

metrics = {
    'Euclidean':    dict(metric='euclidean'),
    'Manhattan':    dict(metric='manhattan'),
    'Minkowski p3': dict(metric='minkowski', p=3),
    'Chebyshev':    dict(metric='chebyshev'),
}

print(f"{'Metric':15s} {'CV Accuracy':>12} {'Std Dev':>10}")
print("-" * 40)
for name, kwargs in metrics.items():
    pipe = Pipeline([
        ('scaler', StandardScaler()),
        ('knn',    KNeighborsClassifier(n_neighbors=5, **kwargs)),
    ])
    scores = cross_val_score(pipe, X, y, cv=5, scoring='accuracy')
    print(f"{name:15s}  {scores.mean():.4f}       ±{scores.std():.4f}")
OUTPUT
Metric CV Accuracy Std Dev ---------------------------------------- Euclidean 0.9600 ±0.0249 Manhattan 0.9467 ±0.0400 Minkowski p3 0.9533 ±0.0340 Chebyshev 0.9333 ±0.0422

On the small, clean Iris dataset, the metrics score close to each other. Euclidean wins narrowly here. On other data the ranking can change, so always test.

छोटे और साफ़ Iris dataset पर सभी metrics के score पास-पास हैं। यहाँ Euclidean थोड़ा आगे है। दूसरे data पर ranking बदल सकती है, इसलिए हमेशा test करें।

在小而干净的 Iris 数据集上,各 metric 的分数很接近,这里 Euclidean 略胜。在其他数据上排名可能会变,所以一定要实际测试。


SectionSection第 08 节

Choosing the Right Distance Metricसही Distance Metric चुनना选择合适的 Distance Metric

📏
Use Euclidean When…Euclidean कब इस्तेमाल करें…何时使用 Euclidean…
Features are continuous. Dimensions are low (under ~20). Data is scaled. It is the default for KNN, K-Means and PCA.
Features continuous हों। Dimensions कम हों (~20 से कम)। Data scaled हो। यह KNN, K-Means और PCA का default है।
feature 是连续值,维度较低(约 20 以下),数据已做 scaling。它是 KNN、K-Means 和 PCA 的默认选择。
KNN · K-Means · PCA
🏙️
Use Manhattan When…Manhattan कब इस्तेमाल करें…何时使用 Manhattan…
Data is high-dimensional or sparse. Outliers are present. You want sparsity (LASSO uses the L1 penalty).
Data high-dimensional या sparse हो। Outliers मौजूद हों। आपको sparsity चाहिए (LASSO, L1 penalty इस्तेमाल करता है)।
数据是高维或稀疏的,存在 outlier,或者你需要稀疏性(LASSO 使用 L1 penalty)。
LASSO · sparse · high-d KNN
🎛️
Use Minkowski When…Minkowski कब इस्तेमाल करें…何时使用 Minkowski…
You want to tune the geometry. Treat p as a hyperparameter in GridSearchCV, next to K.
आप geometry को tune करना चाहते हैं। p को GridSearchCV में K के साथ hyperparameter मानें।
你想调整距离的几何形状。把 p 当作 hyperparameter,和 K 一起放进 GridSearchCV。
hyperparameter · KNN tuning
🧬
Use Hamming When…Hamming कब इस्तेमाल करें…何时使用 Hamming…
Features are binary or categorical. You compare DNA, binary codes or one-hot vectors. You detect transmission errors.
Features binary या categorical हों। आप DNA, binary codes या one-hot vectors की तुलना करें। Transmission errors पकड़ने हों।
feature 是 binary 或 categorical;比较 DNA、binary code 或 one-hot 向量;检测传输错误。
DNA · binary · categorical
♟️
Use Chebyshev When…Chebyshev कब इस्तेमाल करें…何时使用 Chebyshev…
The worst single gap matters most. Warehouse cranes, chess king moves, tolerance checks in manufacturing.
सबसे बड़ा single gap सबसे ज़्यादा मायने रखता हो। Warehouse cranes, शतरंज के राजा की चाल, manufacturing में tolerance checks.
最大的单个差值最重要时。仓库起重机、国际象棋王的走法、制造业中的公差检查。
logistics · games · QA
📐
Use Cosine When…Cosine कब इस्तेमाल करें…何时使用 Cosine…
Direction matters more than size. Two documents with the same word mix but different lengths should look similar. Standard for TF-IDF and embeddings.
Size से ज़्यादा direction मायने रखती हो। एक जैसे शब्दों वाले पर अलग लंबाई के दो documents मिलते-जुलते दिखने चाहिए। TF-IDF और embeddings के लिए standard.
方向比大小更重要时。用词比例相同但长度不同的两篇文档应该被视为相似。TF-IDF 和 embedding 的标准选择。
NLP · embeddings · recommendations
LIVELIVE互动KNN Metric ExplorerKNN Metric ExplorerKNN Metric 探索器

Drag the ★ query point. The dashed shape is the "neighbourhood" that holds the K nearest points. Its shape follows the metric. Find spots where the metrics give different predictions.

★ query point को खींचें। Dashed आकार वह "neighbourhood" है जिसमें K nearest points हैं। इसका आकार metric के हिसाब से बदलता है। ऐसी जगहें ढूँढें जहाँ metrics अलग prediction देते हैं।

拖动 ★ 查询点。虚线形状是包含 K 个最近点的"邻域",它的形状由 metric 决定。找一找各 metric 给出不同预测的位置。

0
0
0


SectionSection第 09 节

Complete Reference Tableपूरी Reference Table完整参考表

MetricFormulaFormula公式NormScale-sensitiveScale-sensitive对 Scale 敏感Outlier-sensitiveOutlier-sensitive对 Outlier 敏感Best feature typeBest feature type最适合的 feature 类型scipy
Euclidean√Σ(aᵢ−bᵢ)²L2Yesहाँ是Highज़्यादा高ContinuousContinuous连续值euclidean()
ManhattanΣ|aᵢ−bᵢ|L1Yesहाँ是Lowerकम较低Continuous, countsContinuous, counts连续值、计数cityblock()
Minkowski(Σ|aᵢ−bᵢ|ᵖ)^(1/p)LpYesहाँ是Grows with pp के साथ बढ़ता है随 p 增大Continuous (tune p)Continuous (p tune करें)连续值(调 p)minkowski()
Chebyshevmax|aᵢ−bᵢ|L∞Yesहाँ是Extremeबहुत ज़्यादा极高Worst-case checksWorst-case checks最坏情况检查chebyshev()
Hamming#{i: aᵢ≠bᵢ} / n—Noनहीं否Noनहीं否Binary, categorical, stringsBinary, categorical, stringsbinary、categorical、字符串hamming()
Cosine1 − a·b / (‖a‖‖b‖)—No (to length)नहीं (length से)否(对长度)Mediumमध्यम中等Text vectors, embeddingsText vectors, embeddings文本向量、embeddingcosine()

SectionSection第 10 节

Real-World Applicationsअसली दुनिया में उपयोग实际应用

Euclidean Distance
📏
  • KNN classification (default metric)KNN classification (default metric)KNN 分类(默认 metric)
  • K-Means cluster assignmentK-Means cluster assignmentK-Means 簇分配
  • PCA and dimensionality reductionPCA और dimensionality reductionPCA 和降维
  • Face recognition embeddingsFace recognition embeddings人脸识别 embedding
  • Short-range map distancesनक्शे पर छोटी दूरियाँ地图上的短距离
Manhattan Distance
🏙️
  • LASSO regularisation (L1 penalty)LASSO regularisation (L1 penalty)LASSO 正则化(L1 penalty)
  • Robust KNN on noisy dataNoisy data पर robust KNN有噪声数据上的稳健 KNN
  • Image reconstruction (L1 loss)Image reconstruction (L1 loss)图像重建(L1 loss)
  • Delivery routes on street gridsStreet grid पर delivery routes街道网格上的配送路线
  • Sparse signal recoverySparse signal recovery稀疏信号恢复
Hamming Distance
🧬
  • DNA sequence comparisonDNA sequence comparisonDNA 序列比较
  • Error detection and correction codesError detection और correction codes检错与纠错码
  • Comparing perceptual image hashesPerceptual image hashes की तुलना比较感知图像哈希
  • Near-duplicate detection (SimHash)Near-duplicate detection (SimHash)近似重复检测(SimHash)
  • Binary feature similarity (KNN)Binary feature similarity (KNN)binary feature 相似度(KNN)

SectionSection第 11 节

Golden RulesGolden Rules黄金法则

📐 Distance Metrics — Rules to RememberDistance Metrics — याद रखने के नियमDistance Metrics — 必记规则
1
Always scale features before Euclidean or Manhattan distance. Both depend on feature size. Salary in thousands will crush age in tens. Put StandardScaler or MinMaxScaler inside a Pipeline.
Euclidean या Manhattan distance से पहले हमेशा features scale करें। दोनों feature के size पर निर्भर हैं। हज़ारों में salary, दहाई में age को दबा देगी। StandardScaler या MinMaxScaler को Pipeline के अंदर रखें।
在计算 Euclidean 或 Manhattan distance 之前,一定要先对 feature 做 scaling。 两者都依赖 feature 的数值大小。以千计的 salary 会压倒以十计的 age。把 StandardScaler 或 MinMaxScaler 放进 Pipeline。
2
Prefer Manhattan when outliers are present. Euclidean squares the gaps, so one outlier grows quadratically. Manhattan grows linearly. It is often more stable on noisy data.
Outliers हों तो Manhattan को प्राथमिकता दें। Euclidean gaps को square करता है, इसलिए एक outlier quadratic रूप से बढ़ता है। Manhattan linear रूप से बढ़ता है। Noisy data पर यह अक्सर ज़्यादा stable होता है।
有 outlier 时优先考虑 Manhattan。 Euclidean 对差值求平方,一个 outlier 的影响会按平方增长;Manhattan 只是线性增长。在有噪声的数据上它通常更稳定。
3
Treat p in Minkowski as a hyperparameter. Do not default to p = 2 blindly. Search p ∈ {1, 1.5, 2, 3} in GridSearchCV together with K and weights.
Minkowski के p को hyperparameter मानें। बिना सोचे p = 2 न रखें। GridSearchCV में K और weights के साथ p ∈ {1, 1.5, 2, 3} search करें।
把 Minkowski 的 p 当作 hyperparameter。 不要盲目默认 p = 2。在 GridSearchCV 中把 p ∈ {1, 1.5, 2, 3} 和 K、weights 一起搜索。
4
Use Hamming only for equal-length binary or categorical data. On continuous values almost every position differs, and all size information is lost. For strings of different length, use Levenshtein.
Hamming सिर्फ़ बराबर length के binary या categorical data पर लगाएँ। Continuous values पर लगभग हर position अलग होती है और size की सारी जानकारी खो जाती है। अलग length की strings के लिए Levenshtein इस्तेमाल करें।
只在等长的 binary 或 categorical 数据上使用 Hamming。 在连续值上几乎每个位置都不同,大小信息全部丢失。长度不同的字符串请用 Levenshtein。
5
In high dimensions, test Manhattan or reduce dimensions first. As dimensions grow, Euclidean distances concentrate: all points look nearly equally far. Lower p (like 1) keeps more contrast. PCA before KNN also helps.
High dimensions में Manhattan test करें या पहले dimensions घटाएँ। Dimensions बढ़ने पर Euclidean distances सिमट जाती हैं: सभी points लगभग बराबर दूर लगते हैं। कम p (जैसे 1) ज़्यादा contrast बचाता है। KNN से पहले PCA भी मदद करता है।
高维时,试试 Manhattan,或先降维。 维度升高时,Euclidean 距离会"集中":所有点看起来几乎一样远。较小的 p(例如 1)能保留更多区分度。在 KNN 之前做 PCA 也有帮助。
6
For text, use cosine distance. Two documents with the same word mix but different lengths look far apart in Euclidean space. Cosine compares only the angle, which is what text needs.
Text के लिए cosine distance इस्तेमाल करें। एक जैसे शब्दों वाले पर अलग लंबाई के दो documents, Euclidean space में दूर दिखते हैं। Cosine सिर्फ़ angle की तुलना करता है, और text को यही चाहिए।
文本请使用 cosine distance。 用词比例相同但长度不同的两篇文档,在 Euclidean 空间里看起来很远。Cosine 只比较夹角,这正是文本需要的。
7
Make sure your metric is a true metric. A true metric is non-negative, zero only for identical points, symmetric, and obeys the triangle inequality. Minkowski with p < 1 breaks the triangle inequality. Fast neighbour search (KD-tree, Ball-tree) can then give wrong results.
पक्का करें कि आपका metric एक true metric है। True metric non-negative होता है, सिर्फ़ एक जैसे points के लिए zero, symmetric, और triangle inequality मानता है। p < 1 वाला Minkowski triangle inequality तोड़ता है। तब fast neighbour search (KD-tree, Ball-tree) गलत results दे सकता है।
确认你的 metric 是 true metric。 true metric 必须非负、只有相同的点距离才为 0、对称,并满足 triangle inequality。p < 1 的 Minkowski 违反 triangle inequality,此时快速近邻搜索(KD-tree、Ball-tree)可能给出错误结果。
8
Use scipy and vectorised code in production. pdist and cdist are written in C and are fast. For millions of vectors, use FAISS or ScaNN.
Production में scipy और vectorised code इस्तेमाल करें। pdist और cdist C में लिखे हैं और तेज़ हैं। लाखों vectors के लिए FAISS या ScaNN इस्तेमाल करें।
生产环境使用 scipy 和向量化代码。 pdist 和 cdist 用 C 实现,速度很快。对数百万个向量,请用 FAISS 或 ScaNN。