Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy Dot Product of two 2-d arrays in numpy to get 3-d array

Sorry for the badly explained title. I am trying to parallelise a part of my code and got stuck on a dot product. I am looking for an efficient way of doing what the code below does, I'm sure there is a simple linear algebra solution but I'm very stuck:

puy = np.arange(8).reshape(2,4)
puy2 = np.arange(12).reshape(3,4)

print puy, '\n'
print puy2.T

zz = np.zeros([4,2,3])

for i in range(4):
    zz[i,:,:] = np.dot(np.array([puy[:,i]]).T,
                np.array([puy2.T[i,:]]))
like image 415
user3235916 Avatar asked Feb 14 '16 21:02

user3235916


People also ask

How do you take the dot product of two NumPy arrays?

dot() This function returns the dot product of two arrays. For 2-D vectors, it is the equivalent to matrix multiplication.

Can you multiply two NumPy arrays?

multiply() function is used when we want to compute the multiplication of two array. It returns the product of arr1 and arr2, element-wise.


2 Answers

One way would be to use np.einsum, which allows you to specify what you want to happen to the indices:

>>> np.einsum('ik,jk->kij', puy, puy2)
array([[[ 0,  0,  0],
        [ 0, 16, 32]],

       [[ 1,  5,  9],
        [ 5, 25, 45]],

       [[ 4, 12, 20],
        [12, 36, 60]],

       [[ 9, 21, 33],
        [21, 49, 77]]])
>>> np.allclose(np.einsum('ik,jk->kij', puy, puy2), zz)
True
like image 172
DSM Avatar answered Oct 04 '22 01:10

DSM


Here's another way with broadcasting -

(puy[None,...]*puy2[:,None,:]).T
like image 41
Divakar Avatar answered Oct 02 '22 01:10

Divakar