简体   繁体   English

计算两个矩阵的余弦相似度

[英]Calculate cosine similarity of two matrices

I have defined two matrices like following:我定义了两个矩阵,如下所示:

from scipy import linalg, mat, dot
a = mat([-0.711,0.730])
b = mat([-1.099,0.124])

Now, I want to calculate the cosine similarity of these two matrices .现在,我想计算这两个矩阵的余弦相似度。 What is the wrong with following code.以下代码有什么问题。 It gives me an error of objects are not aligned它给了我一个objects are not aligned的错误

c = dot(a,b)/np.linalg.norm(a)/np.linalg.norm(b)

You cannot multiply 1x2 matrix by 1x2 matrix.您不能将 1x2 矩阵乘以 1x2 矩阵。 In order to calculate dot product between their rows the second one has to be transposed.为了计算它们的行之间的点积,必须转置第二个。

from scipy import linalg, mat, dot
a = mat([-0.711,0.730])
b = mat([-1.099,0.124])

c = dot(a,b.T)/linalg.norm(a)/linalg.norm(b)

also:还:

import numpy as np
import scipy.spatial.distance as distance
a = np.array([0.1, 0.2])
b = np.array([0.3,0.4])
c = 1 - distance.cosine(a, b)

see: https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cosine.html#scipy.spatial.distance.cosine参见: https : //docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cosine.html#scipy.spatial.distance.cosine

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM