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