Numpy elementwise outdoor product

I want to do an elementary outer product of two 2-dimensional arrays in numpy.

A.shape = (100, 3) # A numpy ndarray B.shape = (100, 5) # A numpy ndarray C = element_wise_outer_product(A, B) # A function that does the trick C.shape = (100, 3, 5) # This should be the result C[i] = np.outer(A[i], B[i]) # This should be the result 

A naive implementation may be as follows.

 tmp = [] for i in range(len(A): outer_product = np.outer(A[i], B[i]) tmp.append(outer_product) C = np.array(tmp) 

Best stack overflow solution.

 big_outer = np.multiply.outer(A, B) tmp = np.swapaxes(tmp, 1, 2) C_tmp = [tmp[i][i] for i in range(len(A)] C = np.array(C_tmp) 

I am looking for a vectorized implementation that relieves the for loop. Does anyone have an idea? Thanks!

+5
source share
1 answer

Extend A and B to 3D , keeping your first axis aligned and introducing new axes along the third and second, respectively None/np.newaxis , and then multiply with each other. This will allow broadcasting to come into play for a vectorized solution.

So the implementation will be -

 A[:,:,None]*B[:,None,:] 

We could shorten it a bit using ellipsis for A:: :,: and skip listing the remaining last axis with B , for example -

 A[...,None]*B[:,None] 

As another vectorized approach, we could also use np.einsum , which can be more intuitive after we go through the syntax of string notation and consider those notations are representatives of iterators involved in a naive looping implementation, for example:

 np.einsum('ij,ik->ijk',A,B) 
+8
source

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


All Articles