numpy elementwise outer product

一世执手 提交于 2019-12-17 07:53:38

问题


I want to do the element-wise outer product of two 2d 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 can the following.

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

A better solution inspired from stack overflow.

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'm looking for a vectorized implementation that gets rid the for loop. Does anyone have an idea? Thank you!


回答1:


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

Thus, an implementation would be -

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

We could shorten it a bit by using ellipsis for A's : :,: and skip listing the leftover last axis with B, like so -

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

As another vectorized approach we could also use np.einsum, which might be more intuitive once we get past the string notation syntax and consider those notations being representatives of the iterators involved in a naive loopy implementation, like so -

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


来源:https://stackoverflow.com/questions/42378936/numpy-elementwise-outer-product

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!