我想在numpy中做两个二维数组的元素明智的外积。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
一个天真的实现可以如下。
tmp = []
for i in range(len(A):
outer_product = np.outer(A[i], B[i])
tmp.append(outer_product)
C = np.array(tmp)
来自堆栈溢出的更好解决方案。
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循环的矢量化实现。 有没有人有想法? 谢谢!
对于它的价值,'np.multiply.outer(A,B)'是'到不同np.outer ',赋予形状'100,3,100,5' – Eric