对于较大的矩阵,下面的代码效率非常低。有没有更好的方法实现这一点?
我已经在网上搜索过这个here了。
import numpy as np
def cosine_similarity(x, y):
return np.dot(x, y) / (np.sqrt(np.dot(x, x)) * np.sqrt(np.dot(y, y)))
def compare(a, b):
c = np.zeros((a.shape[0], b.shape[0]))
for i, ai in enumerate(a):
for j, bj in enumerate(b):
c[i, j] = cosine_similarity(ai, bj)
return c
a = np.random.rand(100,2000)
b = np.random.rand(800,2000)
compare(a,b) # shape -> (100, 800)发布于 2019-07-09 01:40:06
在注释中,如果您想要取两个矩阵的乘积,那么numpy已经有了一个有效的实现,但对您来说可能太慢了(O(n^3))。
import numpy as np
a=np.array([3,2,1])
b=np.array([1,2,3])
c=a.dot(b)
print(c) #output = 10我在评论中看到你对向量之间的余弦距离感兴趣。对于余弦相似性,请考虑使用Scipy:
from scipy.spatial.distance import cosine
a=[1,0,1]
b=[0,1,0]
print(cosine(a,b)) #output = 1.0这可能会更快地满足您的需求。这是documentation。
发布于 2019-07-09 02:18:29
个人编辑
为了有效地计算余弦相似度,下面是我写的一个解决方案:
def compare(a, b):
x = np.atleast_2d(np.sqrt(np.sum(a*a, axis=1))).T
y = np.atleast_2d(np.sqrt(np.sum(b*b, axis=1))).T
return a.dot(b.T) / x.dot(y.T)https://stackoverflow.com/questions/56939272
复制相似问题