Python: Multiplying a list of vectors by a list of

2019-03-01 15:40发布

问题:

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 (i.e. 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?

回答1:

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]