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

问题描述:

我有100个N-dimensional向量的列表和100 MxN矩阵的列表.因此,您可以将这两个数据结构视为100xN列表(或numpy数组)和100xMxN列表(或numpy数组).

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).

我想做的是取每个向量及其对应矩阵的点积,这样输出应该是100 M-dimensional矩阵(即100xM列表或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 (i.e. a 100xM list or numpy array).

但是,我不确定如何执行此操作.由于效率的明显原因,我不想重复进行此操作.我也知道这不是基本的矩阵乘法.我想我可能想使用np.einsum,但是我对此不太熟悉.

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.

有人愿意帮助吗?

您可以使用

You can use np.einsum like so -

np.einsum('ij,ikj->ik',a,b)

样品运行-

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)

您也可以使用np.matmul@运算符(Python 3.x),尽管它似乎比einsum-

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]