I have a list of 100 N-dimensional
vectors and a list of 100 MxN
matrices. So you can think of the two data structures as a 100xN
list (or numpy array) and a 100xMxN
list (or numpy array).
What I want to do is take the dot product of each vector and its corresponding matrix, such that the output should be 100 M-dimensional
matrices (ie a 100xM
list or numpy array).
However, I'm not really sure how to do this. I don't want to do it iteratively, for obvious reasons about efficiency. I also know it's not basic matrix multiplication. I think I might want to use np.einsum
, but I'm not overly familiar with it.
Anyone care to help?
You can use np.einsum
like so -
np.einsum('ij,ikj->ik',a,b)
Sample run -
In [42]: M,N = 3,4
In [43]: a = np.random.rand(100,N)
In [44]: b = np.random.rand(100,M,N)
In [45]: np.einsum('ij,ikj->ik',a,b).shape
Out[45]: (100, 3)
You can also use np.matmul
or @
operator (Python 3.x) though it seems marginally slower than einsum
-
np.matmul(a[:,None],b.swapaxes(1,2))[:,0]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.