在Python中使用 Numpy 在单行中将两个矩阵相乘
矩阵乘法是将两个矩阵作为输入并通过将第一个矩阵的行与第二个矩阵的列相乘来生成单个矩阵的运算。在矩阵乘法中,请确保第一个矩阵的列数应等于该数第二个矩阵的行数。
示例:两个大小为 3×3 的矩阵相乘。
Input:matrix1 = ([1, 2, 3],
[3, 4, 5],
[7, 6, 4])
matrix2 = ([5, 2, 6],
[5, 6, 7],
[7, 6, 4])
Output : [[36 32 32]
[70 60 66]
[93 74 100]]
Python中两个矩阵相乘的方法
1.使用显式for循环:这是一种简单的矩阵乘法技术,但对于较大的输入数据集来说是一种昂贵的方法。在这种情况下,我们使用嵌套的for循环来迭代每一行和每一列。
如果 matrix1 是一个nxm矩阵,而 matrix2 是一个mxl矩阵。
Python3
# input two matrices of size n x m
matrix1 = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
matrix2 = [[5,8,1],
[6,7,3],
[4,5,9]]
res = [[0 for x in range(3)] for y in range(3)]
# explicit for loops
for i in range(len(matrix1)):
for j in range(len(matrix2[0])):
for k in range(len(matrix2)):
# resulted matrix
res[i][j] += matrix1[i][k] * matrix2[k][j]
print (res)
Python3
# We need install numpy in order to import it
import numpy as np
# input two matrices
mat1 = ([1, 6, 5],[3 ,4, 8],[2, 12, 3])
mat2 = ([3, 4, 6],[5, 6, 7],[6,56, 7])
# This will return dot product
res = np.dot(mat1,mat2)
# print resulted matrix
print(res)
Python3
# same result will be obtained when we use @ operator
# as shown below(only in python >3.5)
import numpy as np
# input two matrices
mat1 = ([1, 6, 5],[3 ,4, 8],[2, 12, 3])
mat2 = ([3, 4, 6],[5, 6, 7],[6,56, 7])
# This will return matrix product of two array
res = mat1 @ mat2
# print resulted matrix
print(res)
输出:
[[114 160 60]
[ 74 97 73]
[119 157 112]]
在这个程序中,我们使用嵌套的 for 循环来计算结果,它将遍历矩阵的每一行和每一列,最后它会在结果中累积乘积之和。
2.使用 Numpy:使用 Numpy的乘法也称为向量化,其主要目的是减少或消除程序中对 for 循环的显式使用,从而使计算变得更快。
Numpy 是用于数组处理和操作的Python包中的构建。对于更大的矩阵运算,我们使用 numpy Python包,它比迭代方法快 1000 倍。
有关 Numpy 的详细信息,请访问链接
Python3
# We need install numpy in order to import it
import numpy as np
# input two matrices
mat1 = ([1, 6, 5],[3 ,4, 8],[2, 12, 3])
mat2 = ([3, 4, 6],[5, 6, 7],[6,56, 7])
# This will return dot product
res = np.dot(mat1,mat2)
# print resulted matrix
print(res)
输出:
[[ 63 320 83]
[ 77 484 102]
[ 84 248 117]]
使用numpy
Python3
# same result will be obtained when we use @ operator
# as shown below(only in python >3.5)
import numpy as np
# input two matrices
mat1 = ([1, 6, 5],[3 ,4, 8],[2, 12, 3])
mat2 = ([3, 4, 6],[5, 6, 7],[6,56, 7])
# This will return matrix product of two array
res = mat1 @ mat2
# print resulted matrix
print(res)
输出:
[[ 63 320 83]
[ 77 484 102]
[ 84 248 117]]