余弦距离在计算类似度的应用中常常使用,好比:html
下面是余弦类似度的计算公式(图来自wikipedia):机器学习
可是,余弦类似度和经常使用的欧式距离的有所区别。学习
欧式距离用于类似度检索更符合直觉。所以在使用时,须要将余弦类似度转化成相似欧氏距离的余弦距离。spa
维基页面中给出的角距离计算公式以下(图来自wikipedia):3d
因为在计算图片或者文本类似度时,提取的特征没有负值,余弦类似度的取值为0~1,所以采用更简便的方法,直接定义为:code
余弦距离 = 1- 余弦类似度orm
根据输入数据的不一样,分为两种模式处理。htm
1 import numpy as np
2 def cosine_distance(a, b): 3 if a.shape != b.shape: 4 raise RuntimeError("array {} shape not match {}".format(a.shape, b.shape)) 5 if a.ndim==1: 6 a_norm = np.linalg.norm(a) 7 b_norm = np.linalg.norm(b) 8 elif a.ndim==2: 9 a_norm = np.linalg.norm(a, axis=1, keepdims=True) 10 b_norm = np.linalg.norm(b, axis=1, keepdims=True) 11 else: 12 raise RuntimeError("array dimensions {} not right".format(a.ndim)) 13 similiarity = np.dot(a, b.T)/(a_norm * b_norm) 14 dist = 1. - similiarity 15 return dist
6~7 行 , np.linalg.norm 操做是求向量的范式,默认是L2范式,等同于求向量的欧式距离。blog
9~10行 ,设置参数 axis=1 。对于归一化二维向量时,将数据按行向量处理,至关于单独对每张图片特征进行归一化处理。图片
13行,np.dot 操做能够支持两种模式的运算,来自官方文档的解释:
numpy.
dot
(a, b, out=None)Dot product of two arrays. Specifically,
If both a and b are 1-D arrays, it is inner product of vectors (without complex conjugation).
If both a and b are 2-D arrays, it is matrix multiplication, but using
matmul
ora @ b
is preferred.
为了保持一致性,都使用了转置操做。以下图所示,矩阵乘法按线性代数定义,必须是 行 × 列才能完成乘法运算。举例 32张128维特征进行运算,则应该是 32x128 * 128x32 才行。