简体   繁体   English

如何使用 Numpy 进行 N x M 和 1 x M 的矩阵乘法

[英]How to do matrix multiplication of N x M and 1 x M with Numpy

I want to do matrix multiplication of N x M and 1 x M matrix: Here is my Matrix:我想做 N x M 和 1 x M 矩阵的矩阵乘法:这是我的矩阵:

N=(A,[2,9])
M=[[2,3,4],[3,4,6]]

I want to multiply each element of the first row by 2 and the second row by 9 with the M list but I didn't get any idea, I know matrix multiplication.我想用 M 列表将第一行的每个元素乘以 2,将第二行的每个元素乘以 9,但我不知道,我知道矩阵乘法。 but with NumPy, I don't know.但是对于 NumPy,我不知道。

Note: M is a matrix and N is also a matrix.注意:M 是一个矩阵,N 也是一个矩阵。

For multiplying to matrices - A,B with dimensions mXn and pXq respectively you must have n=p.要乘以矩阵 - A,B,尺寸分别为 mXn 和 pXq,您必须具有 n=p。 In the given example you have a matrix M with dimensions 2x3 and another matrix with dimension 2x1 so matrix multiplication isn't possible.在给定的示例中,您有一个尺寸为 2x3 的矩阵 M 和另一个尺寸为 2x1 的矩阵,因此矩阵乘法是不可能的。

I want to multiply each element of the first row by 2 and the second row by 9 with the M list but I didn't get any idea, I know matrix multiplication.我想用 M 列表将第一行的每个元素乘以 2,将第二行的每个元素乘以 9,但我不知道,我知道矩阵乘法。 but with NumPy, I don't know.但是对于 NumPy,我不知道。

This can be done using numpy with the following code:这可以使用 numpy 和以下代码来完成:

import numpy as np
x = np.array([2,9])
M = np.array([[2,3,4],[3,4,6]])
for i in range(x.shape[0]):
    M[i] *= x[i]

and the output:和 output:

array([[ 4,  6,  8],
   [27, 36, 54]])

What you describe is not matrix multiplication, but simple row-wise multiplication.您描述的不是矩阵乘法,而是简单的逐行乘法。 You can do it conveniently in NumPy by using broadcasting.您可以使用广播在 NumPy 中方便地做到这一点。 For your example (ignoring A , which was not explained) this means that if you shape your first matrix as a one-column matrix with two rows and multiply it with your second matrix using the normal * operator, the first matrix will be expanded to the same shape as the second one by repeating its columns.对于您的示例(忽略A ,未解释),这意味着如果您将第一个矩阵塑造为具有两行的单列矩阵,并使用普通*运算符将其与第二个矩阵相乘,则第一个矩阵将扩展为通过重复其列,与第二个形状相同。 Then element-wise multiplication will be performed between the two matrices:然后将在两个矩阵之间执行逐元素乘法:

import numpy as np

m1 = np.array([[2], 
               [9]])
m2 = np.array([[2, 3, 4],
               [3, 4, 6]])

m1 * m2
array([[ 4,  6,  8],
       [27, 36, 54]])

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

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