NumPy 矩阵乘法

NumPy 矩阵的倍增可以通过以下三种方法进行。

  1. 倍增():元素式矩阵倍增
  2. matmul():两个序列的矩阵产品 3.点():两个序列的点产品

NumPy 矩阵倍增元素 智慧

如果您想要元素式矩阵倍增,则可以使用 multiply() 函数。

 1import numpy as np
 2
 3arr1 = np.array([[1, 2],
 4                 [3, 4]])
 5arr2 = np.array([[5, 6],
 6                 [7, 8]])
 7
 8arr_result = np.multiply(arr1, arr2)
 9
10print(arr_result)

输出:

1[[ 5 12]
2 [21 32]]

下面的图像显示了执行的倍率操作,以获得结果矩阵。

Numpy Matrix Multiply

二、两个NumPy Arrays的矩阵产品

如果您想要两个数组的矩阵产品,请使用 matmul() 函数。

 1import numpy as np
 2
 3arr1 = np.array([[1, 2],
 4                 [3, 4]])
 5arr2 = np.array([[5, 6],
 6                 [7, 8]])
 7
 8arr_result = np.matmul(arr1, arr2)
 9
10print(f'Matrix Product of arr1 and arr2 is:\n{arr_result}')
11
12arr_result = np.matmul(arr2, arr1)
13
14print(f'Matrix Product of arr2 and arr1 is:\n{arr_result}')

输出:

1Matrix Product of arr1 and arr2 is:
2[[19 22]
3 [43 50]]
4Matrix Product of arr2 and arr1 is:
5[[23 34]
6 [31 46]]

下图解释了结果数组中的每个索引的矩阵产品操作。为了简化,请从第一个数组中取行,然后从每个索引的第二个数组中取列。

Numpy Matrix Product

两个数组的矩阵产物取决于参数位置,所以matmul(A,B)可能与matmul(B,A)不同。

3、两个NumPy Arrays的点产品

numpy dot() 函数返回两个数组的点产品,结果与单维和两维数组的 matmul() 函数相同。

 1import numpy as np
 2
 3arr1 = np.array([[1, 2],
 4                 [3, 4]])
 5arr2 = np.array([[5, 6],
 6                 [7, 8]])
 7
 8arr_result = np.dot(arr1, arr2)
 9
10print(f'Dot Product of arr1 and arr2 is:\n{arr_result}')
11
12arr_result = np.dot(arr2, arr1)
13
14print(f'Dot Product of arr2 and arr1 is:\n{arr_result}')
15
16arr_result = np.dot([1, 2], [5, 6])
17print(f'Dot Product of two 1-D arrays is:\n{arr_result}')

输出:

1Dot Product of arr1 and arr2 is:
2[[19 22]
3 [43 50]]
4Dot Product of arr2 and arr1 is:
5[[23 34]
6 [31 46]]
7Dot Product of two 1-D arrays is:
817

推荐阅读:

参考

Published At
Categories with 技术
Tagged with
comments powered by Disqus