Numpy operator for multiple external products… here is a solution to the problem.
Numpy operator for multiple external products
import numpy as np
mat1 = np.random.rand(2,3)
mat2 = np.random.rand(2,5)
I want to get a 2x3x5 tensor where each layer is a 3×5 outer product obtained by multiplying the 3×1 transpose row of mat by the 1×5 row of mat2.
Can it be done with numpy matmul?
Solution
You can simply use > broadcasting np.newaxis/none After
expanding their size-
mat1[...,None]*mat2[:,None]
This will be the highest performance because there is no need for sum-reduction
to guarantee service from np.einsum or np.matmul
If you also want to drag in< a href="https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.matmul.html" rel="noreferrer noopener nofollow">np.matmul
, it is the same as Broadcast
is basically the same:
np.matmul(mat1[...,None],mat2[:,None])
與 np.einsum
, If you’re familiar with its string notation, it may look cleaner than the others
np.einsum('ij,ik->ijk',mat1,mat2)
# 23,25->235 (to explain einsum's string notation using axes lens)