简体   繁体   English

如何在 python 中将矩阵的特定行/列相乘?

[英]How to multiply specific rows/columns of matrices with each other in python?

I have to input matrices of shape我必须输入形状矩阵

m1: (n,3)
m2: (n,3)

I want to multiply each row (each n of size 3) with its correspondence of the other matrix, such that i get a (3,3) matrix for each row.我想将每一行(每个 n 大小为 3)与其对应的另一个矩阵相乘,这样我就得到了每一行的(3,3)矩阵。

When im trying to just use eg m1[0]@m2.T[0] the operation doesnt work, as m[0] delivers a (3,) list instead of a (3,1) matrix, on which i could use matrix operations.当我试图只使用例如m1[0]@m2.T[0]时,该操作不起作用,因为m[0]提供了一个(3,)列表而不是一个(3,1)矩阵,我可以在其上使用矩阵运算。

Is there a relatively easy or elegant way to get the desired (3,1) matrix for the matrix multiplication?是否有一种相对简单或优雅的方法来获得矩阵乘法所需的(3,1)矩阵?

Generally, I would recommend using np.einsum for most matrix operations as it very elegant.一般来说,我建议将np.einsum用于大多数矩阵运算,因为它非常优雅。 To obtain a the row-wise outer product of the vectors contained in m1 and m2 of shape (n, 3) you could do the following:要获得形状为(n, 3)m1m2中包含的向量的逐行外积,您可以执行以下操作:

import numpy as np
m1 = np.array([1, 2, 3]).reshape(1, 3)
m2 = np.array([1, 2, 3]).reshape(1, 3)
result = np.einsum("ni, nj -> nij", m1, m2)
print(result)
>>>array([[[1, 2, 3],
        [2, 4, 6],
        [3, 6, 9]]])

By default, numpy gets rid of the singleton dimension, as you have noticed.正如您所注意到的,默认情况下,numpy 摆脱了 singleton 维度。
You can use np.newaxis (or equivalently None . That is an implementation detail, but also works in pytorch) for the second axis to tell numpy to "invent" a new one.您可以使用np.newaxis (或等效的None 。这是一个实现细节,但也适用于 pytorch)作为第二个轴来告诉 numpy “发明”一个新轴。

import numpy as np
a = np.ones((3,3))
a[1].shape                 # this is (3,)
a[1,:].shape               # this is (3,)
a[1][...,np.newaxis].shape # this is (3,1)

However , you can also use dot or outer directly:但是,您也可以直接使用dotouter

>>> a = np.eye(3)
>>> np.outer(a[1], a[1])
array([[0., 0., 0.],
       [0., 1., 0.],
       [0., 0., 0.]])
>>> np.dot(a[1], a[1])
1.0

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

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