Numpy-矩阵向量与标量向量的点积 [英] Numpy - Dot Product of a Vector of Matrices with a Vector of Scalars

查看:182
本文介绍了Numpy-矩阵向量与标量向量的点积的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个3维数据集,我正尝试通过以下方式进行操作.

I have a 3 dimensional data set that I am trying to manipulate in the following way.

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

我希望numpy将数据视为2890x10矩阵的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. 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).

等效循环(我相信):

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]]

推荐答案

如果您的NumPy足够新(1.6或更高),则可以使用

If your NumPy is new enough (1.6 or better), you could use 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]])


或者,如果没有np.einsum,则可以向vector添加额外的轴,并利用广播以执行乘法:


Or, without np.einsum, you could add extra axes to vector and take advantage of broadcasting to perform the multiplication:

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

这篇关于Numpy-矩阵向量与标量向量的点积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆