NumPy矩阵乘法
时间:2020-02-23 14:42:21 来源:igfitidea点击:
NumPy矩阵乘法可以通过以下三种方法完成。
multiple():逐元素矩阵乘法。
matmul():两个数组的矩阵乘积。
dot():两个数组的点积。
1. NumPy矩阵乘法元素明智
如果要逐元素矩阵相乘,可以使用multiple()函数。
import numpy as np arr1 = np.array([[1, 2], [3, 4]]) arr2 = np.array([[5, 6], [7, 8]]) arr_result = np.multiply(arr1, arr2) print(arr_result)
输出:
[[ 5 12] [21 32]]
下图显示了为获得结果矩阵而执行的乘法运算。
numpy矩阵乘法()
2.两个NumPy阵列的矩阵乘积
如果要两个数组的矩阵乘积,请使用matmul()函数。
import numpy as np arr1 = np.array([[1, 2], [3, 4]]) arr2 = np.array([[5, 6], [7, 8]]) arr_result = np.matmul(arr1, arr2) print(f'Matrix Product of arr1 and arr2 is:\n{arr_result}') arr_result = np.matmul(arr2, arr1) print(f'Matrix Product of arr2 and arr1 is:\n{arr_result}')
输出:
Matrix Product of arr1 and arr2 is: [[19 22] [43 50]] Matrix Product of arr2 and arr1 is: [[23 34] [31 46]]
下图说明了结果数组中每个索引的矩阵乘积运算。
为简单起见,为每个索引取第一个数组的行和第二个数组的列。
然后乘以相应的元素,然后将它们相加以达到矩阵乘积值。
块状矩阵产品
两个数组的矩阵乘积取决于参数位置。
因此,matmul(A,B)可能与matmul(B,A)不同。
3.两个NumPy阵列的点积
numpy dot()函数返回两个数组的点积。
结果与一维和二维数组的matmul()函数相同。
import numpy as np arr1 = np.array([[1, 2], [3, 4]]) arr2 = np.array([[5, 6], [7, 8]]) arr_result = np.dot(arr1, arr2) print(f'Dot Product of arr1 and arr2 is:\n{arr_result}') arr_result = np.dot(arr2, arr1) print(f'Dot Product of arr2 and arr1 is:\n{arr_result}') arr_result = np.dot([1, 2], [5, 6]) print(f'Dot Product of two 1-D arrays is:\n{arr_result}')
输出:
Dot Product of arr1 and arr2 is: [[19 22] [43 50]] Dot Product of arr2 and arr1 is: [[23 34] [31 46]] Dot Product of two 1-D arrays is: 17