我想在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