简体   繁体   English

向量列表乘以numpy einsum的一个矩阵

[英]List of vectors multiplied by one matrix with numpy einsum

I have a 3x3 matrix and I would like to multiply each vector in a list by this matrix. 我有一个3x3的矩阵,我想将此列表中的每个向量相乘。

This can be done easily with a loop: 这可以通过循环轻松完成:

import numpy as np

a = np.array([[0,1,0],[-1,0,0],[0,0,1]])
b = np.array([[1,2,3],[4,5,6]])

for elem in b:
   print(a.dot(elem))

To make it quicker I have tried using numpy.einsum but I am not able to do the correct formulation. 为了使其更快,我尝试使用numpy.einsum,但我无法执行正确的公式。

I have tried np.einsum('ij,ji->ij', a, b) but this results in ValueError: operands could not be broadcast together with remapped shapes [original->remapped]: (3,3)->(3,3) (2,3)->(3,2) 我已经尝试过np.einsum('ij,ji->ij', a, b)但这导致ValueError: operands could not be broadcast together with remapped shapes [original->remapped]: (3,3)->(3,3) (2,3)->(3,2)

Any advice ? 有什么建议吗?

In [489]: for elem in b:
     ...:     print(a.dot(elem))
     ...:     
[ 2 -1  3]
[ 5 -4  6]

first step - you are iterating the first dimension of b , and expecting that in the result as well: 第一步-您正在迭代b的第一个维度,并期望在结果中也是如此:

np.einsum(',i->i', a, b)

dot pairs the last dim of a with the only dim of elem, the 2nd dim of b - and sums them: dot a的最后a暗角与elem的唯一一个暗角, b的第二个暗角配对-并将它们相加:

np.einsum(' j,ij->i', a, b)

Now fill in the first dimension of a , which passes through as the last dim of the result: 现在填写a的第一个维度,该维度作为结果的最后一个模糊点通过:

In [495]: np.einsum('kj,ij->ik', a, b)
Out[495]: 
array([[ 2, -1,  3],
       [ 5, -4,  6]])

Switch the arguments around, and a regular 2d dot product appears: 切换参数,然后出现常规的二维点积:

In [496]: np.einsum('ij,kj->ik', b, a)
Out[496]: 
array([[ 2, -1,  3],
       [ 5, -4,  6]])
In [497]: b.dot(a.T)    # b@(a.T)
Out[497]: 
array([[ 2, -1,  3],
       [ 5, -4,  6]])

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

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