一、余弦距离
定义:
similarity
=
cos
(
θ
)
=
A
⋅
B
∥
A
∥
∥
B
∥
=
∑
i
=
1
n
A
i
B
i
∑
i
=
1
n
A
i
2
∑
i
=
1
n
B
i
2
,
\text { similarity }=\cos (\theta)=\frac{\mathbf{A} \cdot \mathbf{B}}{\|\mathbf{A}\|\|\mathbf{B}\|}=\frac{\sum_{i=1}^{n} A_{i} B_{i}}{\sqrt{\sum_{i=1}^{n} A_{i}^{2}} \sqrt{\sum_{i=1}^{n} B_{i}^{2}}},
similarity =cos(θ)=∥A∥∥B∥A⋅B=∑i=1nAi2∑i=1nBi2∑i=1nAiBi,
where
A
i
A_{i}
Ai and
B
i
B_{i}
Bi are components of vector
A
A
A and
B
B
B respectively.
简单来说,余弦相似度,就是计算两个向量间的夹角的余弦值。
余弦距离就是用1减去这个获得的余弦相似度。
余弦距离取值范围:
c
o
s
(
θ
)
cos (\theta)
cos(θ)的取值范围是[-1 1] ,余弦距离的取值范围为[0,2] ,这就满足了非负性的性质。
二、欧式距离
欧式距离就是空间中两点的距离
就是常用的距离计算公式:
d
=
∑
i
=
1
N
(
x
1
i
−
x
2
i
)
2
d=\sqrt{\sum_{i=1}^{N}\left(x_{1 i}-x_{2 i}\right)^{2}}
d=i=1∑N(x1i−x2i)2
举例说明:
A
=
(
1
,
3
)
B
=
(
1
,
2
)
C
=
(
2
,
4
)
A=(1,3) \quad B=(1,2) \quad C=(2,4)
A=(1,3)B=(1,2)C=(2,4)
向量A和B之间的夹角
θ
1
\theta_{1}
θ1,向量A和C之间的夹角
θ
2
\theta_{2}
θ2,并且
θ
1
=
θ
2
\theta_{1} = \theta_{2}
θ1=θ2
A和B之间的余弦相似度:
cos θ 1 = 1 + 6 9 + 1 ⋅ 1 + 4 = 7 10 5 = 7 50 = 0.9899494936611665 \cos \theta_{1}=\frac{1+6}{\sqrt{9+1} \cdot \sqrt{1+4}}=\frac{7}{\sqrt{10} \sqrt{5}}=\frac{7}{\sqrt{50}}=0.9899494936611665 cosθ1=9+1⋅1+41+6=1057=507=0.9899494936611665
cos θ 2 = 2 + 12 10 ⋅ 20 = 14 200 = 7 50 = 0.9899494936611665 \cos \theta_{2}=\frac{2+12}{\sqrt{10} \cdot \sqrt{20}}=\frac{14}{\sqrt{200}}=\frac{7}{\sqrt{50}}=0.9899494936611665 cosθ2=10⋅202+12=20014=507=0.9899494936611665
import numpy as np
A = np.array([1,3])
B = np.array([1,2])
C = np.array([2,4])
AngleSimiliaryAB = np.dot(A,B)/(np.linalg.norm(A)*np.linalg.norm(B))
AngleSimiliaryAC = np.dot(A,C)/(np.linalg.norm(A)*np.linalg.norm(C))
print('Angle similiarity between A and B : {}'.format(AngleSimiliaryAB))
print('Angle similiarity between A and C : {}'.format(AngleSimiliaryAC))
EuclideanDistanceAB = np.sqrt(np.sum(np.square(A-B)))
EuclideanDistanceAC = np.sqrt(np.sum(np.square(A-C)))
print('Euclidean Distance between A and B: {}'.format(EuclideanDistanceAB))
print('Euclidean Distance between A and C: {}'.format(EuclideanDistanceAC))
运行结果:
Angle similiarity between A and B : 0.9899494936611664
Angle similiarity between A and C : 0.9899494936611664
Euclidean Distance between A and B: 1.0
Euclidean Distance between A and C: 1.4142135623730951
三、两者之间的关系
当向量的模长是经过归一化的,此时欧氏距离与余弦距离有着单调的关系:
∥
A
−
B
∥
2
=
2
(
1
−
cos
(
A
,
B
)
)
\|A-B\|_{2}=\sqrt{2\left(1-\cos \left(A, B\right)\right)}
∥A−B∥2=2(1−cos(A,B))
在此场景下,如果选择距离最小(相似度最大)的近邻,那么使用余弦相似度和欧氏距离的结果是相同的。
四、什么时候用余弦距离什么时候用欧式距离呢?
总体来说,欧氏距离体现数值上的绝对差异,而余弦距离体现方向上的相对差异。
1)例如,统计两部剧的用户观看行为,用户A的观看向量为(0,1),用户B为(1,0);此时二者的余弦距很大,而欧氏距离很小;我们分析两个用户对于不同视频的偏好,更关注相对差异,显然应当使用余弦距离。
2)而当我们分析用户活跃度,以登陆次数(单位:次)和平均观看时长(单:分钟)作为特征时,余弦距离会认为(1,10)、(10,100)两个用户距离很近;但显然这两个用户活跃度是有着极大差异的,此时我们更关注数值绝对差异,应当使用欧氏距离。
总结:在日常使用中需要注意区分,余弦距离虽然不是一个严格意义上的距离度量公式,但是形容两个特征向量之间的关系还是有很大用处的。比如人脸识别,推荐系统等。