NumPy 中一维数组(第一个参数)与二维数组(第二个参数)的矩阵乘积
要查找二维数组和一维数组的矩阵乘积,请在 Python NumPy 中使用 **numpy.matmul()** 方法。如果第一个参数是一维的,则通过在其维度前添加 1 来将其提升为矩阵。矩阵乘法完成后,将删除前置的 1。
返回输入的矩阵乘积。仅当 x1、x2 都是一维向量时,此结果才是标量。out 是一个存储结果的位置。如果提供,它必须具有与签名 (n,k),(k,m)->(n,m) 匹配的形状。如果未提供或为 None,则返回一个新分配的数组。
步骤
首先,导入所需的库 -
import numpy as np
创建一个一维数组和一个二维数组 -
arr1 = np.array([25, 35]) arr2 = np.array([[5, 7], [10, 15]])
显示数组 -
print("Array 1 (Two Dimensional)...
", arr1) print("
Array 2 (One Dimensional)...
", arr2)
获取数组的类型 -
print("
Our Array 1 type...
", arr1.dtype) print("
Our Array 2 type...
", arr2.dtype)
获取数组的维度 -
print("
Our Array 1 Dimensions...
",arr1.ndim) print("
Our Array 2 Dimensions...
",arr2.ndim)
获取数组的形状 -
print("
Our Array 1 Shape...
",arr1.shape) print("
Our Array 2 Shape...
",arr2.shape)
要查找二维数组和一维数组的矩阵乘积,请在 Python NumPy 中使用 numpy.matmul() 方法。如果第一个参数是一维的,则通过在其维度前添加 1 来将其提升为矩阵。矩阵乘法完成后,将删除前置的 1 -
print("
Result (matrix product)...
",np.matmul(arr1, arr2))
示例
import numpy as np # Create a 1D and a 2D array arr1 = np.array([25, 35]) arr2 = np.array([[5, 7], [10, 15]]) # Display the arrays print("Array 1 (Two Dimensional)...
", arr1) print("
Array 2 (One Dimensional)...
", arr2) # Get the type of the arrays print("
Our Array 1 type...
", arr1.dtype) print("
Our Array 2 type...
", arr2.dtype) # Get the dimensions of the Arrays print("
Our Array 1 Dimensions...
",arr1.ndim) print("
Our Array 2 Dimensions...
",arr2.ndim) # Get the shape of the Arrays print("
Our Array 1 Shape...
",arr1.shape) print("
Our Array 2 Shape...
",arr2.shape) # To find the matrix product of a 2D and a 1D array, use the numpy.matmul() method in Python Numpy # If the first argument is 1-D, it is promoted to a matrix by prepending a 1 to its dimensions. # After matrix multiplication the prepended 1 is removed. print("
Result (matrix product)...
",np.matmul(arr1, arr2))
输出
Array 1 (Two Dimensional)... [25 35] Array 2 (One Dimensional)... [[ 5 7] [10 15]] Our Array 1 type... int64 Our Array 2 type... int64 Our Array 1 Dimensions... 1 Our Array 2 Dimensions... 2 Our Array 1 Shape... (2,) Our Array 2 Shape... (2, 2) Result (matrix product)... [475 700]
广告