Find point product of subarrays in numpy

In numpy, the numpy.dot() function can be used to calculate the matrix product of two 2D arrays. I have two 3D arrays X and Y (say), and I would like to calculate the matrix Z, where Z[i] == numpy.dot(X[i], Y[i]) for all i . Is it possible to do this in an inert manner?

+7
source share
1 answer

What about:

 from numpy.core.umath_tests import inner1d Z = inner1d(X,Y) 

For instance:

 X = np.random.normal(size=(10,5)) Y = np.random.normal(size=(10,5)) Z1 = inner1d(X,Y) Z2 = [np.dot(X[k],Y[k]) for k in range(10)] print np.allclose(Z1,Z2) 

returns True

Edit Fix, as I have not seen the 3D part of the question

 from numpy.core.umath_tests import matrix_multiply X = np.random.normal(size=(10,5,3)) Y = np.random.normal(size=(10,3,5)) Z1 = matrix_multiply(X,Y) Z2 = np.array([np.dot(X[k],Y[k]) for k in range(10)]) np.allclose(Z1,Z2) # <== returns True 

This works because (as indicated in the docstring) matrix_multiply provides

matrix_multiply (x1, x2 [, out]) matrix

multiplication by the last two dimensions

+7
source

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


All Articles