The Story That Explains Distance Metricsवह कहानी जो Distance Metrics समझाती है一个解释 Distance Metrics 的故事
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.
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 क्या दर्शाता है।
Euclid 拿出一把尺子,从 A 到 B 画一条直线。"这才是真正的距离,"他说。这是鸟飞过去的路线。5 km。
Manny 来自 Manhattan。他摇摇头:"这条线穿过了大楼。我只能沿着街道走:先向东 3 个街区,再向北 4 个街区。"7 km。
Minka 有一个带旋钮的公式,旋钮叫 p。"调到 1,我像 Manny 一样走;调到 2,我像 Euclid 一样飞。"她代表 general case。
Hamm 不关心地图。他比较 DNA、密码和 binary code。"我的距离只数有多少个位置不同,"他说。
同样两个点,四个正确答案。选哪一个,取决于你的数据代表什么。
Three travellers go from A to B at the same time. Watch how each one counts its distance.
तीन यात्री एक साथ A से B जाते हैं। देखिए हर कोई अपनी distance कैसे गिनता है।
三位旅行者同时从 A 出发去 B。看看每个人是怎样计算距离的。
Euclidean🐦 कौआ
Euclidean🐦 乌鸦
Euclidean
Manhattan🚕 Taxi
Manhattan🚕 出租车
Manhattan
Chebyshev♚ राजा
Chebyshev♚ 王
Chebyshev
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 步。
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。再好的调参也救不回来。
Euclidean Distance — The Straight LineEuclidean Distance — सीधी LineEuclidean Distance — 直线距离
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)。
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。下面亲自试一试。
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人 | age | salary (₹) |
|---|---|---|
| A | 25 | 50,000 |
| B | 60 | 52,000 |
| C | 26 | 60,000 |
Properties of Euclidean DistanceEuclidean Distance की PropertiesEuclidean Distance 的性质
| PropertyProperty性质 | ValueValue表达式 | What It Meansमतलब含义 |
|---|---|---|
| Non-negativity | d(A,B) ≥ 0 | Distance is never negativeDistance कभी negative नहीं होती距离永远不为负 |
| Identity | d(A,A) = 0 | A point is at distance zero from itselfPoint की खुद से distance zero है一个点到自身的距离为 0 |
| Symmetry | d(A,B) = d(B,A) | A to B equals B to AA से B = B से AA 到 B 等于 B 到 A |
| Triangle Inequality | d(A,C) ≤ d(A,B) + d(B,C) | A detour through a third point is never shorterतीसरे point से घूमकर जाना कभी छोटा नहीं होता绕道经过第三个点永远不会更短 |
| Outlier sensitivityOutlier sensitivityOutlier 敏感度 | High | Squaring makes big gaps even biggerSquare करने से बड़े gaps और बड़े हो जाते हैं平方会把大的差值放得更大 |
Manhattan Distance — The City GridManhattan Distance — शहर का GridManhattan Distance — 城市网格
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.
यही Manhattan distance है। हर axis का absolute gap जोड़ दें। इसे taxicab distance, city block distance या L1 norm भी कहते हैं।
这就是 Manhattan distance:把每个坐标轴上的绝对差值加起来。它也叫 taxicab distance、city block distance 或 L1 norm。
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 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.00 | 7.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 |
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 只是这个旋钮的两个档位。
| p | Nameनाम名称 | FormulaFormula公式 | Result (A→B)Result (A→B)结果 (A→B) | Unit ball shapeUnit ball का आकारUnit ball 形状 |
|---|---|---|---|---|
| p = 1 | Manhattan / L1 | Σ|aᵢ−bᵢ| | 7.00 | DiamondDiamond (हीरा)菱形 |
| p = 2 | Euclidean / L2 | √Σ(aᵢ−bᵢ)² | 5.00 | CircleCircle圆 |
| p = 3 | Minkowski L3 | (Σ|aᵢ−bᵢ|³)^(1/3) | 4.50 | Between circle and squareCircle और square के बीच介于圆和正方形之间 |
| p = 4 | Minkowski L4 | (Σ|aᵢ−bᵢ|⁴)^(1/4) | 4.28 | Rounded squareगोल कोनों वाला square圆角正方形 |
| p → ∞ | Chebyshev / L∞ | max|aᵢ−bᵢ| | 4.00 | SquareSquare正方形 |
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。
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。
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 的样子
Hamming Distance — Comparing SequencesHamming Distance — Sequences की तुलनाHamming Distance — 比较序列
Sequence 1:
GAATTCGACTSequence 2:
GAATCCGAGTPosition 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.
Sequence 1:
GAATTCGACTSequence 2:
GAATCCGAGTPosition 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 नहीं।
Sequence 1:
GAATTCGACTSequence 2:
GAATCCGAGT第 5 位:T 对 C,不同。第 9 位:C 对 G,不同。其余位置都相同。Hamming distance = 2。
一位网络工程师检查数据包。他发送
10110101,收到 10010100。第 3 位和第 8 位翻转了。Hamming distance = 2。只要 Hamming distance 大于 0,就说明至少出了一个错误。Hamming distance 只统计两个等长序列中有多少个位置不同。没有几何,没有坐标。
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 通过有噪声的信道,看看错误是怎么出现的。
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,连续值绝对不要用。
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)。
| Metric | CalculationCalculation计算 | ResultResult结果 | Norm |
|---|---|---|---|
| Euclidean | √(3² + 4² + 0²) = √25 | 5.00 | L2 |
| Manhattan | 3 + 4 + 0 | 7.00 | L1 |
| Minkowski p=3 | (27 + 64 + 0)^(1/3) | 4.50 | L3 |
| Chebyshev | max(3, 4, 0) | 4.00 | L∞ |
| Hamming | Positions 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 | — |
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)。
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 放到对角线上,看它们如何拉开差距。
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 居中。
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}")
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")
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())
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}")
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 略胜。在其他数据上排名可能会变,所以一定要实际测试。
Choosing the Right Distance Metricसही Distance Metric चुनना选择合适的 Distance 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 给出不同预测的位置。
Complete Reference Tableपूरी Reference Table完整参考表
| Metric | FormulaFormula公式 | Norm | Scale-sensitiveScale-sensitive对 Scale 敏感 | Outlier-sensitiveOutlier-sensitive对 Outlier 敏感 | Best feature typeBest feature type最适合的 feature 类型 | scipy |
|---|---|---|---|---|---|---|
| Euclidean | √Σ(aᵢ−bᵢ)² | L2 | Yesहाँ是 | Highज़्यादा高 | ContinuousContinuous连续值 | euclidean() |
| Manhattan | Σ|aᵢ−bᵢ| | L1 | Yesहाँ是 | Lowerकम较低 | Continuous, countsContinuous, counts连续值、计数 | cityblock() |
| Minkowski | (Σ|aᵢ−bᵢ|ᵖ)^(1/p) | Lp | Yesहाँ是 | Grows with pp के साथ बढ़ता है随 p 增大 | Continuous (tune p)Continuous (p tune करें)连续值(调 p) | minkowski() |
| Chebyshev | max|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() |
| Cosine | 1 − a·b / (‖a‖‖b‖) | — | No (to length)नहीं (length से)否(对长度) | Mediumमध्यम中等 | Text vectors, embeddingsText vectors, embeddings文本向量、embedding | cosine() |
Real-World Applicationsअसली दुनिया में उपयोग实际应用
- 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नक्शे पर छोटी दूरियाँ地图上的短距离
- 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稀疏信号恢复
- 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)
Golden RulesGolden Rules黄金法则
StandardScaler or MinMaxScaler inside a Pipeline.StandardScaler या MinMaxScaler को Pipeline के अंदर रखें।StandardScaler 或 MinMaxScaler 放进 Pipeline。GridSearchCV together with K and weights.GridSearchCV में K और weights के साथ p ∈ {1, 1.5, 2, 3} search करें।GridSearchCV 中把 p ∈ {1, 1.5, 2, 3} 和 K、weights 一起搜索。pdist and cdist are written in C and are fast. For millions of vectors, use FAISS or ScaNN.pdist और cdist C में लिखे हैं और तेज़ हैं। लाखों vectors के लिए FAISS या ScaNN इस्तेमाल करें।pdist 和 cdist 用 C 实现,速度很快。对数百万个向量,请用 FAISS 或 ScaNN。