沒有任何款項,減少參與,一個簡單的broadcasting
將與np.newaxis/None
延伸b
到3D
後真正有效 -
a*b[:,None,:] # or simply a*b[:,None]
運行測試 -
In [531]: a = np.arange(10*4*3).reshape((10,4,3))
...: b = np.arange(30).reshape((10,3))
...:
In [532]: %timeit np.einsum('ijk,ik->ijk', a, b) #@Brad Solomon's soln
...: %timeit a*b[:,None]
...:
100000 loops, best of 3: 1.79 µs per loop
1000000 loops, best of 3: 1.66 µs per loop
In [525]: a = np.random.rand(100,100,100)
In [526]: b = np.random.rand(100,100)
In [527]: %timeit np.einsum('ijk,ik->ijk', a, b)
...: %timeit a*b[:,None]
...:
1000 loops, best of 3: 1.53 ms per loop
1000 loops, best of 3: 1.08 ms per loop
In [528]: a = np.random.rand(400,400,400)
In [529]: b = np.random.rand(400,400)
In [530]: %timeit np.einsum('ijk,ik->ijk', a, b)
...: %timeit a*b[:,None]
...:
10 loops, best of 3: 128 ms per loop
10 loops, best of 3: 94.8 ms per loop
@BradSolomon這是正確的。增加了時間來確認這些。 – Divakar