当前位置: 首页 > 工具软件 > NumPy > 使用案例 >

Python Numpy矩阵乘法

东门宜
2023-12-01

In this tutorial we will see python matrix multiplication using numpy (Numerical Python) library.

在本教程中,我们将看到使用numpy(Numerical Python)库的python矩阵乘法

For using numpy you must install it first on your computer, you can use package manager like pip for installing numpy.

要使用numpy,必须先将其安装在计算机上,然后可以使用软件包管理器(如pip)安装numpy。

Numpy provide array data structure which is almost the same as python list but have faster access for reading and writing resulting in better performance. We will use numpy arrays to represent matrices.

Numpy提供的数组数据结构与python列表几乎相同,但具有更快的读写访问权限,从而提高了性能。 我们将使用numpy数组来表示矩阵。

To perform matrix multiplication of matrices a and b , the number of columns in a must be equal to the number of rows in b otherwise we cannot perform matrix multiplication.

为了执行矩阵AB的矩阵乘法, 列数必须等于b中的行否则就不能执行矩阵乘法的数量。

We must check this condition otherwise we will face runtime error.

我们必须检查这种情况,否则我们将面临运行时错误。

There is * operator for numpy arrays but that operator will not do matrix multiplication instead it will multiply the matrices element by element.

numpy数组有*运算符,但该运算符不会进行矩阵乘法,而是将矩阵元素逐元素相乘。

Here is an example with * operator:

这是带有*运算符的示例:

# Import numpy 
import numpy as np
 
def printMatrix(a):
    
    # Printing matrix
    for i in range(0,len(a)):
        for j in range(0,len(a[0])):
            print(a[i][j],end = " ")
        print()
 
def main():
    
    # Declaring our matrices using arrays in numpy
    a = np.array([[1,2,3],[3,4,5],[5,6,7]])
    b = np.array([[1,2,3]])
    
    print("Matrix a :")
    printMatrix(a)
    print()
    
    print("Matrix b : ")
    printMatrix(b)
    print()
    
    # Using * operator to multiply
    c = a*b
    
    # Printing Result
    print("Result of a*b : ")
    printMatrix(c)
 
main()

Output:

输出:

Matrix a : 1 2 3 3 4 5 5 6 7

矩阵a: 1 2 3 3 4 5 5 6 7

Matrix b : 1 2 3

矩阵b: 1 2 3

Result of a*b : 1 4 9 3 8 15 5 12 21

a * b的结果: 1 4 9 3 8 15 5 12 21

Python Numpy矩阵乘法 (Python Numpy Matrix Multiplication)

We can see in above program the matrices are multiplied element by element. So for doing a matrix multiplication we will be using the dot function in numpy.

我们可以在上面的程序中看到矩阵乘以一个元素。 因此,为了进行矩阵乘法,我们将在numpy中使用点函数。

We can either write

我们可以写

  • np.dot(a,b)

    np.dot(a,b)
  • a.dot(b)

    点(b)

for matrix multiplication here is the code:

对于矩阵乘法,下面是代码:

# Import numpy 
import numpy as np
 
def printMatrix(a):
    
    # Printing matrix
    for i in range(0,len(a)):
        for j in range(0,len(a[0])):
            print(a[i][j],end = " ")
        print()
    
    
 
def main():
    
    # Taking rows and columns of a 
    m = int(input("Enter rows in a : "))
    n = int(input("Enter columns in a : "))
    
    # Taking rows and columns of b
    p = int(input("Enter rows in b : "))
    q = int(input("Enter columns in b : "))
    
    # Checking necessary condition for matrix multiplication
    if n!= p:
        print("Number of columns in b must be equal to rows in b")
        exit()
    
    # Initializing a and b list
    a = [ [0 for i in range(0,n)] for j in range(0,m) ]
    b = [ [0 for i in range(0,q)] for j in range(0,p) ]
    
    # Taking input list a
    print("Enter matrix a : ")
    for i in range(0,m):
        for j in range(0,n):
            a[i][j] = int(input("Enter element a[" + str(i) + "][" + str(j) + "] : "))
    
    # Taking input list b
    print("Enter matrix b : ")
    for i in range(0,p):
        for j in range(0,q):
            b[i][j] = int(input("Enter element b[" + str(i) + "][" + str(j) + "] : "))
    
    
    # Converting python list in numpy array
    a = np.array(a)
    b = np.array(b)
    
    print("Matrix a :")
    printMatrix(a)
    print()
    
    print("Matrix b : ")
    printMatrix(b)
    print()
    
    # Using dot operator to multiply
    c = a.dot(b)
    
    # Printing Result
    print("Result of a*b : ")
    printMatrix(c)
 
 
main()

Output:

输出:

Enter rows in a : 2 Enter columns in a : 3 Enter rows in b : 3 Enter columns in b : 2 Enter matrix a : Enter element a[0][0] : 2 Enter element a[0][1] : 3 Enter element a[0][2] : 4 Enter element a[1][0] : 1 Enter element a[1][1] : 2 Enter element a[1][2] : 3 Enter matrix b : Enter element b[0][0] : 4 Enter element b[0][1] : 5 Enter element b[1][0] : 1 Enter element b[1][1] : 6 Enter element b[2][0] : 9 Enter element b[2][1] : 7 Matrix a : 2 3 4 1 2 3

输入a中的行:2 输入a中的列:3 输入b中的行:3 输入b中的列:2 输入矩阵a: 输入元素a [0] [0]:2 输入元素a [0] [1]:3 输入元素a [0] [2]:4 输入元素a [1] [0]:1 输入元素a [1] [1]:2 输入元素a [1] [2]:3 输入矩阵b: 输入元素b [0] [0]:4 输入元素b [0] [1]:5 输入元素b [1] [0]:1 输入元素b [1] [1]:6 输入元素b [2] [0 ]:9 输入元素b [2] [1]:7 矩阵a: 2 3 4 1 2 3

Matrix b : 4 5 1 6 9 7

矩阵b: 4 5 1 6 9 7

Result of a*b : 47 56 33 38

a * b的结果: 47 56 33 38

Here the output is different because of the dot operator. Alternatively we can use the numpy matrices method to first convert the arrays into matrices and then use * operator to do matrix multiplication as below:

由于点运算符,此处的输出是不同的。 或者,我们可以使用numpy矩阵方法首先将数组转换为矩阵,然后使用*运算符进行矩阵乘法,如下所示:

# Using * operator to multiply
c = np.matrix(a)*np.matrix(b)

Comment below if you have any queries related to python numpy matrix multiplication.

如果您有任何有关python numpy矩阵乘法的查询,请在下面评论。

翻译自: https://www.thecrazyprogrammer.com/2019/08/python-numpy-matrix-multiplication.html

 类似资料: