獲取 Python 中兩個一維陣列的內積
若要獲取兩個陣列的內積,在 Python 中使用 numpy.inner() 方法。對於一維陣列,向量的普通內積;在高維度中,對最後一個軸執行總和積。引數為兩個向量 a 和 b。如果 a 和 b 是非標量,它們的最後一個維度必須匹配。
步驟
首先,匯入必要的庫。
import numpy as np
使用 array() 方法建立兩個 numpy 一維陣列。
arr1 = np.array([5, 10, 15]) arr2 = np.array([20, 25, 30])
顯示陣列。
print("Array1...\n",arr1)
print("\nArray2...\n",arr2)檢查兩個陣列的維度。
print("\nDimensions of Array1...\n",arr1.ndim)
print("\nDimensions of Array2...\n",arr2.ndim)檢查兩個陣列的形狀。
print("\nShape of Array1...\n",arr1.shape)
print("\nShape of Array2...\n",arr2.shape)若要獲取兩個陣列的內積,在 Python 中使用 numpy.inner() 方法。
print("\nResult (Inner Product)...\n",np.inner(arr1, arr2))示例
import numpy as np
# Creating two numpy One-Dimensional array using the array() method
arr1 = np.array([5, 10, 15])
arr2 = np.array([20, 25, 30])
# Display the arrays
print("Array1...\n",arr1)
print("\nArray2...\n",arr2)
# Check the Dimensions of both the arrays
print("\nDimensions of Array1...\n",arr1.ndim)
print("\nDimensions of Array2...\n",arr2.ndim)
# Check the Shape of both the arrays
print("\nShape of Array1...\n",arr1.shape)
print("\nShape of Array2...\n",arr2.shape)
# To get the Inner product of two arrays, use the numpy.inner() method in Python
# Ordinary inner product of vectors for 1-D arrays, in higher dimensions a sum product over the last axes.
print("\nResult (Inner Product)...\n",np.inner(arr1, arr2))輸出
Array1... [ 5 10 15] Array2... [20 25 30] Dimensions of Array1... 1 Dimensions of Array2... 1 Shape of Array1... (3,) Shape of Array2... (3,) Result (Inner Product)... 800
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP