问题
import numpy as np
mat1 = np.random.rand(2,3)
mat2 = np.random.rand(2,5)
I wish to get a 2x3x5 tensor, where each layer is the 3x5 outer product achieved by multiplying 3x1 transposed row of mat1 by 1x5 row of mat2.
Can it be done with numpy matmul?
回答1:
You can simply use broadcasting after extending their dimensions with np.newaxis/None -
mat1[...,None]*mat2[:,None]
This would be the most performant, as there's no sum-reduction
needed here to warrant services from np.einsum
or np.matmul
.
If you still want to drag in np.matmul, it would be basically same as with the broadcasting
one :
np.matmul(mat1[...,None],mat2[:,None])
With np.einsum, it might be look a bit more tidy than others, if you are familiar with its string notation -
np.einsum('ij,ik->ijk',mat1,mat2)
# 23,25->235 (to explain einsum's string notation using axes lens)
来源:https://stackoverflow.com/questions/44141966/numpy-operator-for-multiple-outer-products