Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Multiplying a list of vectors by a list of matrices as a single matrix operation

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?

like image 407
anon Avatar asked Oct 12 '25 10:10

anon


1 Answers

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]
like image 181
Divakar Avatar answered Oct 15 '25 05:10

Divakar