[英]Numpy: Dotproduct of all vectors in a list
Say I have a list of 800 vectors and every vector consists of 1440 scalars.假设我有一个包含 800 个向量的列表,每个向量由 1440 个标量组成。
List = [(1, 2, 3, ... , 1440),
(1, 2, 3, ... , 1440),
(1, 2, 3, ... , 1440),
...]
How can I calculate the dot product of every vector to each other vector in the fastest way with python and numpy?如何使用 python 和 numpy 以最快的方式计算每个向量与其他向量的点积?
If you want the symmetric matrix where x_ij
is the dot product of a_i
with a_j
, then:如果您想要
x_ij
是a_i
与a_j
的点积的对称矩阵,则:
a = np.array(List)
x = a @ a.T
You can use np.triu_indices
or np.tril_indices
to avoid computing the second half of the matrix.您可以使用
np.triu_indices
或np.tril_indices
来避免计算矩阵的后半部分。 This won't affect the complexity of the computation, but may save some time for a sufficient number of long vectors:这不会影响计算的复杂性,但可以为足够数量的长向量节省一些时间:
a = np.array(x)
n = a.shape[0]
r, c = np.triu_indices(n)
result = np.empty((n, n))
result[r, c] = result[c, r] = np.sum(a[r] * a[c], axis=1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.