numpy逐元素外积 [英] numpy elementwise outer product
问题描述
我想在numpy中做两个2d数组的元素外部乘积.
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)
我正在寻找摆脱了for循环的矢量化实现. 有人有主意吗? 谢谢!
I'm looking for a vectorized implementation that gets rid the for loop. Does anyone have an idea? Thank you!
推荐答案
将A
和B
扩展为3D
,以保持其第一轴对齐,并分别使用 None/np.newaxis
,然后彼此相乘.这将允许 broadcasting
参与矢量化解决方案.
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.
因此,一个实现将是-
A[:,:,None]*B[:,None,:]
我们可以使用 ellipsis
将其缩短一点表示A::,:
,并跳过用B
列出剩余的最后一个轴,就像这样-
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]
作为另一种矢量化方法,我们还可以使用 np.einsum
,一旦我们跳过了字符串表示法的语法,并认为这些表示法是天真的循环实现中涉及的迭代器的代表,它可能会更直观,
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)
这篇关于numpy逐元素外积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!