简体   繁体   English

Numpy - 矩阵向量与标量向量的点积

[英]Numpy - Dot Product of a Vector of Matrices with a Vector of Scalars

I have a 3 dimensional data set that I am trying to manipulate in the following way.我有一个 3 维数据集,我试图以下列方式操作。

data.shape = (643, 2890, 10)
vector.shape = (643,)

I would like numpy to see data as a 643 length 1-D array of 2890x10 matrices and calculate a dot product (sum-product?) between data and vector.我希望 numpy 将数据视为 2890x10 矩阵的 643 长度一维数组,并计算数据和向量之间的点积(和积?)。 I can do this with a loop, but would really like to find a way to do this using a primitive (this will be run many times across parallel nodes).我可以用循环来做到这一点,但真的很想找到一种使用原语来做到这一点的方法(这将在并行节点上运行多次)。

The equivalent loop (I believe):等效循环(我相信):

a = numpy.zeros ((2890, 10))
for i in range (643):
   a += vector[i]*data[i]

Thanks very much!非常感谢! Sorry if this is a repost, I've searched far and wide, and ended up making an account to ask you guys.抱歉,如果这是转帖,我已经搜索了很多地方,最后还是创建了一个帐户来询问你们。

   a = numpy.array ([[[1,1,1,1],[2,2,2,2],[3,3,3,3]], [[3,3,3,3],[4,4,4,4],[5,5,5,5]]])
   b = numpy.array ([10,20])
# Thus, 
   a.shape = (2,3,4)
   b.shape = (2,)
# Want an operation . such that:
   a . b = [[10,10,10,10],[20,20,20,20],[30,30,30,30]] + [[60,60,60,60],[80,80,80,80],[100,100,100,100]]
         = [[70,70,70,70],[100,100,100,100],[130,130,130,130]]

If your NumPy is new enough (1.6 or better), you could use numpy.einsum :如果您的 NumPy 足够新(1.6 或更好),您可以使用numpy.einsum

result = np.einsum('ijk,i -> jk', data, vector)

In [36]: data = np.array ([[[1,1,1,1],[2,2,2,2],[3,3,3,3]], [[3,3,3,3],[4,4,4,4],[5,5,5,5]]])

In [37]: vector = np.array ([10,20])

In [38]: np.einsum('ijk,i -> jk', data, vector)
Out[38]: 
array([[ 70,  70,  70,  70],
       [100, 100, 100, 100],
       [130, 130, 130, 130]])

Or, without np.einsum , you could add extra axes to vector and take advantage of broadcasting to perform the multiplication:或者,如果没有np.einsum ,您可以向vector添加额外的轴并利用 广播来执行乘法:

In [64]: (data * vector[:,None,None]).sum(axis=0)
Out[64]: 
array([[ 70,  70,  70,  70],
       [100, 100, 100, 100],
       [130, 130, 130, 130]])

The previous answer uses the right numpy function, however it doesn't give the result asked.上一个答案使用了正确的 numpy 函数,但是它没有给出所要求的结果。

It should be:它应该是:

np.einsum('i, ijk -> ijk', vector, data)

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

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