简体   繁体   English

Python:将向量列表与矩阵列表相乘作为单个矩阵运算

[英]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. 我有一个100个N-dimensional向量的列表和一个100 MxN矩阵的列表。 So you can think of the two data structures as a 100xN list (or numpy array) and a 100xMxN list (or numpy array). 因此,您可以100xN两个数据结构视为一个100xN列表(或numpy数组)和一个100xMxN列表(或numpy数组)。

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). 我想做的是获取每个向量及其对应矩阵的点积,这样输出应为100 M-dimensional矩阵(即100xM列表或numpy数组)。

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. 我想我可能想使用np.einsum ,但是我对此不太熟悉。

Anyone care to help? 有人愿意帮助吗?

You can use np.einsum like so - 您可以像这样使用np.einsum

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@运算符(Python 3.x),尽管它似乎比einsum -

np.matmul(a[:,None],b.swapaxes(1,2))[:,0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM