np.dot()
不會給你想要的輸出,除非你涉及額外的步驟,可能會包括reshaping
。下面是使用np.einsum
做第一張是沒有任何額外的內存開銷一個vectorized
方法 -
Final_Product = np.einsum('ijk,lk->lij',A,Combinations)
對於完整性,在這裏與np.dot
和reshaping
是如前所述 -
M,N,R = A.shape
Final_Product = A.reshape(-1,R).dot(Combinations.T).T.reshape(-1,M,N)
運行測試和驗證輸出 -
In [138]: # Inputs (smaller version of those listed in question)
...: A = np.random.uniform(0,1, (374, 138, 3))
...: Combinations = np.random.randint(0,3, (30,3))
...:
In [139]: %timeit np.array([ np.sum(A*cb, axis=2) for cb in Combinations])
1 loops, best of 3: 324 ms per loop
In [140]: %timeit np.einsum('ijk,lk->lij',A,Combinations)
10 loops, best of 3: 32 ms per loop
In [141]: M,N,R = A.shape
In [142]: %timeit A.reshape(-1,R).dot(Combinations.T).T.reshape(-1,M,N)
100 loops, best of 3: 15.6 ms per loop
In [143]: Final_Product =np.array([np.sum(A*cb, axis=2) for cb in Combinations])
...: Final_Product2 = np.einsum('ijk,lk->lij',A,Combinations)
...: M,N,R = A.shape
...: Final_Product3 = A.reshape(-1,R).dot(Combinations.T).T.reshape(-1,M,N)
...:
In [144]: print np.allclose(Final_Product,Final_Product2)
True
In [145]: print np.allclose(Final_Product,Final_Product3)
True
謝謝!我還發現@ajcr的回答非常有幫助。使用張量我減半了'np.einsum'使用的時間 – Julien
@Julien我也喜歡ajcr的解決方案!我認爲這是'dot'在這裏做的簡潔版本。 – Divakar