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]

更新於: 2022-02-07

347 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.