【发布时间】:2019-07-09 06:11:14
【问题描述】:
对于大型矩阵,下面的代码效率非常低。有没有更好的方法来实现这个?
我已经在网上搜索过这个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)
【问题讨论】:
-
a.dot(b.T)怎么样? -
@Divakar 不是
a@b.T? -
@Dan 应该是一样的。 @ 特定于 Python3.x。
-
@Divakar 很有趣,我没想到
dot会使用len(a.shape) != 1处理矩阵 -
这个函数为什么叫
compare()?这不就是矩阵乘法吗?