Numpy - dot product of matrix vector with scalar vector

I have a three-dimensional data set that I am trying to manipulate as follows.

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

I would like numpy to see the data as an array of length 643 of length 1-D from 2890x10 matrices and calculate the point product (sum-product?) Between the data and the vector. I can do this with a loop, but I would really like to find a way to do this with a primitive (this will be done many times through parallel nodes).

Equivalent loop (I believe):

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

Thank you very much! Sorry if this is a repost, I searched around the world 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]] 
+4
source share
1 answer

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

Or, without np.einsum , you can add additional axes to vector and use broadcasting to do 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]]) 
+5
source

Source: https://habr.com/ru/post/1482287/


All Articles