余弦相似度与余弦距离公式关系



谁能解释一下这两个公式?他们有什么关系吗?

def _cosine_distance(a, b, data_is_normalized=False):
if not data_is_normalized:
a = np.asarray(a) / np.linalg.norm(a, axis=1, keepdims=True)
b = np.asarray(b) / np.linalg.norm(b, axis=1, keepdims=True)
return 1. - np.dot(a, b.T)
def findCosineSimilarity(source_representation, test_representation):
a = np.matmul(np.transpose(source_representation), test_representation)
b = np.sum(np.multiply(source_representation, source_representation))
c = np.sum(np.multiply(test_representation, test_representation))
return 1 - (a / (np.sqrt(b) * np.sqrt(c)))```

关于你的评论,形状为2 x 5的两个矩阵的余弦距离本质上包括在每个数组中查找向量之间的成对的余弦距离。假设您正在处理行向量(通常使用NumPy时应该这样做),预期的输出应该由2 * 2 = 4元素组成。如果您正在处理列向量,那么5 * 5 = 25元素是有意义的。

_cosine_distance看起来不错

对于a in N^{n x l}b in N^{m x l}的所有情况,_cosine_distance函数的命名和实现一般都是正确的。

对于1D数组使用_cosine_distance,你可以简单地在0轴上添加一个单维,例如_cosine_distance(a[np.newaxis], b[np.newaxis])

findcosinessimilarity看起来很糟糕

findCosineSimilarity在命名上是不正确的(它计算余弦距离),如果您有一维数组,则实现有效。将此用于除1D数组以外的任何东西将失败,因为它将根据余弦距离的定义计算不正确的。此外,转置source_representation(左矩阵)暗示该函数适用于列向量,这与_cosine_distance不同,并不是说findCosineSimilarity无论如何都适用于矩阵。

通过使用n x n矩阵很容易创建一个列/行向量不可知的测试用例:

1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1

如果我们计算矩阵中每个向量的两两余弦距离,我们应该得到全0,因为向量是相同的。

import numpy as np
def findCosineSimilarity(source_representation, test_representation):
a = np.matmul(np.transpose(source_representation), test_representation)
b = np.sum(np.multiply(source_representation, source_representation))
c = np.sum(np.multiply(test_representation, test_representation))
return 1 - (a / (np.sqrt(b) * np.sqrt(c)))
def _cosine_distance(a, b, data_is_normalized=False):
if not data_is_normalized:
a = np.asarray(a) / np.linalg.norm(a, axis=1, keepdims=True)
b = np.asarray(b) / np.linalg.norm(b, axis=1, keepdims=True)
return 1. - np.dot(a, b.T)
a = np.array([
[1,1,1,1],
[1,1,1,1],
[1,1,1,1],
[1,1,1,1]
])
print(findCosineSimilarity(a,a))
print(_cosine_distance(a, a))

输出:

[[0.75 0.75 0.75 0.75]
[0.75 0.75 0.75 0.75]
[0.75 0.75 0.75 0.75]
[0.75 0.75 0.75 0.75]]
[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]

我们看到findCosineSimilarity失败了,而_cosine_distance是正确的。

最新更新