欧式距离、曼哈顿距离、余弦相似度(python代码)

欧式距离/欧几里得度量(Euclidean Distance)

欧氏距离就是两点之间最短的直线距离
(1)二维空间里A、B两点间的欧式距离:
S A B = ( x A − x B ) 2 + ( y A − y B ) 2 S_{AB}= \sqrt{\def\bar#1{#1^2} \bar{(x_A-x_B)}+\def\bar#1{#1^2} \bar{(y_A-y_B)}} SAB=(xAxB)2+(yAyB)2
(2)推广到 n n n维空间内的两点 P 、 Q P、Q PQ
P = ( x 1 P , x 2 P , . . . , x n P ) , Q = ( x 1 Q , x 2 Q , . . . , x n Q ) P=(x_1^P,x_2^P,...,x_n^P),Q=(x_1^Q,x_2^Q,...,x_n^Q) P=(x1P,x2P,...,xnP),Q=(x1Q,x2Q,...,xnQ)
P 、 Q P、Q PQ点间的欧式距离:
S P Q = ( x 1 P − x 1 Q ) 2 + ( x 2 P − x 2 Q ) 2 + . . . + ( x n P − x n Q ) 2 S_{PQ}= \sqrt{\def\bar#1{#1^2} \bar{(x_1^P-x_1^Q)}+\def\bar#1{#1^2} \bar{(x_2^P-x_2^Q)}+...+\def\bar#1{#1^2} \bar{(x_n^P-x_n^Q)}} SPQ=(x1Px1Q)2+(x2Px2Q)2+...+(xnPxnQ)2
用向量形式 x P 、 x Q \bold{x^P}、\bold{x^Q} xPxQ表示两个点,两点之间的距离可用L2范数表示:
S P Q = ∥ x P − x Q ∥ S_{PQ}=\|\bold{x^P}-\bold{x^Q}\| SPQ=xPxQ
欧式距离的计算代码:

import numpy as np

x1=[1,1]
x2=[2,2]
x1_np = np.array(x1)
x2_np = np.array(x2)

# 直接用公式计算
dist1 = np.sqrt(np.sum((x1_np-x2_np)**2))

# 使用内置范数函数计算
dist2 = np.linalg.norm(x1_np,x2_np)

print(f"d1={dist1},d2={dist2}\n")

曼哈顿距离(Manhattan Distance)

如果乘坐出租车从曼哈顿街头的A路口到B路口,行进距离必须按照路网规则进行移动,而不可能直接穿行。

所以与两点间的直线距离不同,曼哈顿距离指的是“导航距离”。可以用L1范数来表示。

(1)二维空间里 A ( x 1 , y 1 ) 、 B ( x 2 , y 2 ) A(x_1,y_1)、B(x_2,y_2) A(x1,y1)B(x2,y2)两点间的曼哈顿距离:
S A B = ∣ x 1 − x 2 ∣ + ∣ y 1 − y 2 ∣ S_{AB}=|x_1-x_2|+|y_1-y_2| SAB=x1x2+y1y2
(2)推广到 n n n维空间内的两点 P 、 Q P、Q PQ
S P Q = ∑ i = 1 n ∣ x i P − x i Q ∣ S_{PQ}=\sum_{i=1}^n|x_i^P-x_i^Q| SPQ=i=1nxiPxiQ
计算代码:

import numpy as np

x1=[1,2]
x2=[5,6]
x1_np = np.array(x1)
x2_np = np.array(x2)

dist3 = np.sum(np.abs(x1_np-x2_np))
print(f"d3={dist3}\n")

余弦相似度

余弦夹角一般用来测量两个样本之间的相似性。常用于图像特征向量之间的相似度比对。

数学上可以通过向量的点积计算两个向量之间的余弦夹角:
cos ⁡ θ = A ⋅ B ∣ A ∣ ∣ B ∣ = x 1 x 2 + y 1 y 2 x 1 2 + y 1 2 x 2 2 + y 2 2 \cos{\theta}=\frac{\bold{A}\sdot\bold{B}}{|\bold{A}||\bold{B}|} = \frac{x_1 x_2+y_1 y_2}{\sqrt{x_1^2+y_1^2}\sqrt{x_2^2+y_2^2}} cosθ=ABAB=x12+y12 x22+y22 x1x2+y1y2
拓展到 n n n维空间的 P 、 Q P、Q PQ向量:
cos ⁡ θ = x P T x Q x P T x P x Q T x Q \cos{\theta}=\frac{\bold{x_P}^T \bold{x_Q}}{\sqrt{\bold{x_P}^T \bold{x_P}}\sqrt{\bold{x_Q}^T \bold{x_Q}}} cosθ=xPTxP xQTxQ xPTxQ
计算代码:

from __future__ import division#使除法变为精确除法
import numpy as np

x1=[1,2,3,4]
x2=[2,3,4,6]
x1_np = np.array(x1)
x2_np = np.array(x2)

# 直接用公式计算
result1 = np.dot(x1_np,x2_np)/(np.sqrt(x1_np,x1_np)*np.dot(x2_np,x2_np))

# 直接用np内置函数计算
result2 = np.dot(x1_np,x2_np)/(np.linalg.norm(x1_np)*np.linalg.norm(x2_np))

# 计算夹角大小
theta = np.arccos(result1)

print(f"result1={result1},result2={result2},theta={theta}\n")

猜你喜欢

转载自blog.csdn.net/Bit_Coders/article/details/115840560