我有一个代码来计算两个矩阵之间的余弦相似度:

def cos_cdist_1(matrix, vector):
    v = vector.reshape(1, -1)
    return sp.distance.cdist(matrix, v, 'cosine').reshape(-1)


def cos_cdist_2(matrix1, matrix2):
    return sp.distance.cdist(matrix1, matrix2, 'cosine').reshape(-1)

list1 = [[1,1,1],[1,2,1]]
list2 = [[1,1,1],[1,2,1]]

matrix1 = np.asarray(list1)
matrix2 = np.asarray(list2)

results = []
for vector in matrix2:
    distance = cos_cdist_1(matrix1,vector)
    distance = np.asarray(distance)
    similarity = (1-distance).tolist()
    results.append(similarity)


dist_all = cos_cdist_2(matrix1, matrix2)
results2 = []
for item in dist_all:
    distance_result = np.asarray(item)
    similarity_result = (1-distance_result).tolist()
    results2.append(similarity_result)
results
[[1.0000000000000002, 0.9428090415820635],
                     [0.9428090415820635, 1.0000000000000002]]

但是,results2[1.0000000000000002, 0.9428090415820635, 0.9428090415820635, 1.0000000000000002]
我的理想结果是 results ,这意味着结果包含相似值列表,但我想保留两个矩阵之间的计算而不是向量和矩阵,有什么好主意吗?

最佳答案

In [75]: import scipy.spatial as sp
In [76]: 1 - sp.distance.cdist(matrix1, matrix2, 'cosine')
Out[76]:
array([[ 1.        ,  0.94280904],
       [ 0.94280904,  1.        ]])

因此,您可以消除 for-loops 并将其全部替换为
results2 = 1 - sp.distance.cdist(matrix1, matrix2, 'cosine')

关于python - 两个矩阵之间的余弦相似度计算,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30152599/

10-16 12:04