Python中的Numpy matmul()方法

Numpy matmul()方法用于找出两个数组的矩阵乘积。对于2D矩阵,将返回规则矩阵乘积。如果提供的矩阵的维数大于2,则将其视为驻留在最后两个索引中的一堆矩阵,然后进行相应广播。同样,如果两个数组中的任何一个都是一维的,则通过在其维上附加1来将其提升为矩阵,然后在执行矩阵乘法后,删除相加的1。

句法

numpy.matmul(arr1, arr2, out=None)

参量

matmul()函数最多采用三个参数:

arr1:array_like,第一个输入数组

arr2:array_like,第二个输入数组

out:ndarray,它是一个可选参数。

它是一个n维数组,必须将输出存储到其中。假设arr1的形状为(m,k),而arr2的形状为(k,n),则它们的形状必须为(m,n)。如果未提供此参数或无,则返回新分配的数组。

返回值

matmul()方法返回输入数组的矩阵乘积。仅当arr1和arr2均为一维矢量时才产生标量。

编程范例

程序显示在通常的二维矩阵情况下numpy.matmul()方法的工作:

请参阅以下代码。

# importing the numpy module
import numpy as np

# first 2-D array arr1
arr1 = np.array([[2, 4], [6, 8]])
print("first array is :")
print(arr1)
print("Shape of first array is: ", arr1.shape)

# second 2-D array arr1
arr2 = np.array([[1, 3], [5, 7]])
print("second array is :")
print(arr2)
print("Shape of second array is: ", arr2.shape)

# calculating matrix product
res = np.matmul(arr1, arr2)
print("Resultant array is :")
print(res)
print("Shape of resultant array is: ", res.shape)

输出量

first array is :
[[2 4]
 [6 8]]
Shape of first array is:  (2, 2)
second array is :
[[1 3]
 [5 7]]
Shape of second array is:  (2, 2)
Resultant array is :
[[22 34]
 [46 74]]
Shape of resultant array is:  (2, 2)

说明

在上面的程序中,我们获取了两个名为arr1和arr2的二维输入数组,然后通过显示两个数组的矩阵乘积来显示输出。所得数组还将具有(2,2)的形状。

为了更深入地了解产品,可以将其显示为:

numpy matmul()

程序显示numpy.matmul()方法的工作情况(如果任何矩阵为一维矩阵)

请参阅以下代码。

# importing the numpy module
import numpy as np

# first 2-D array arr1
arr1 = np.array([[3, 0], [0, 4]])
print("first array is :")
print(arr1)
print("Shape of first array is: ", arr1.shape)

# second 2-D array arr1
arr2 = np.array([1, 2])
print("second array is :")
print(arr2)
print("Shape of second array is: ", arr2.shape)

# calculating matrix product
res = np.matmul(arr1, arr2)
print("Resultant array is :")
print(res)
print("Shape of resultant array is: ", res.shape)

输出量

first array is :
[[3 0]
 [0 4]]
Shape of first array is:  (2, 2)
second array is :
[1 2]
Shape of second array is:  (2,)
Resultant array is :
[3 8]
Shape of resultant array is:  (2,)

说明

在上面的程序中,我们采用了一个名为arr1的二维输入数组和另一个名为arr2的一维矢量。然后,我们通过显示两个数组的矩阵乘积来显示输出。结果数组的形状也将为(2,)。

要更深入地了解产品,可以将其理解为:

由于arr2是一维向量,因此通过将1附加到矩阵上将其提升为矩阵,可以将其显示为: [[11], [2,1]]。现在,像往常一样计算转换矩阵乘积后,将获得如下结果: [ [3,3], [8, 4] ],但附加的列将再次被删除,因此最终结果将是 [3,8] 具有形状(2,)。

最后,Python教程中的Numpy matmul()方法结束了。

也可以看看

numpy convolve()

numpy related()

numpy polyfit()

numpy linalg det()

numpy arange()

资讯来源:由0x资讯编译自APPDIVIDEND,版权归作者Ankit Lathiya所有,未经许可,不得转载
你可能还喜欢