在 Python 中獲取陣列與標量的內積


若要獲取陣列與標量的內積,請在 Python 中使用 numpy.inner() 方法。對於 1-D 陣列的普通向量內積,在更高維度上,對上一個軸進行求和乘積。引數是 1 和 b,兩個向量。如果 a 和 b 為非標量,則其最後一個維度必須匹配。

步驟

首先,匯入所需的庫-

import numpy as np

使用 numpy.eye() 建立陣列。此方法返回一個 2-D 陣列,其中對角線為 1,其他位置為 0 −

arr = np.eye(5)

val 是標量 −

val = 2

檢查資料型別 −

print("\nDatatype of Array...\n",arr.dtype)

檢查維度 −

print("\nDimensions of Array...\n",arr.ndim)

檢查形狀 −

print("\nShape of Array...\n",arr.shape)

若要獲取陣列與標量的外積,請在 Python 中使用 numpy.outer() 方法 −

print("\nResult (Outer Product)...\n",np.outer(arr, val))

若要獲取陣列與標量的內積,請在 Python 中使用 numpy.inner() 方法 −

print("\nResult (Inner Product)...\n",np.inner(arr, val))

示例

import numpy as np

# Create an array using numpy.eye(). This method returns a 2-D array with ones on the diagonal and zeros elsewhere.
arr = np.eye(5)

# The val is the scalar
val = 2

# Display the array
print("Array...\n",arr)

# Check the datatype
print("\nDatatype of Array...\n",arr.dtype)

# Check the Dimension
print("\nDimensions of Array...\n",arr.ndim)

# Check the Shape
print("\nShape of Array...\n",arr.shape)

# To get the Inner product of an array and a scalar, use the numpy.inner() method in Python
print("\nResult (Inner Product)...\n",np.inner(arr, val))

輸出

Array...
[[1. 0. 0. 0. 0.]
[0. 1. 0. 0. 0.]
[0. 0. 1. 0. 0.]
[0. 0. 0. 1. 0.]
[0. 0. 0. 0. 1.]]

Datatype of Array...
float64

Dimensions of Array...
2

Shape of Array...
(5, 5)

Result (Inner Product)...
[[2. 0. 0. 0. 0.]
[0. 2. 0. 0. 0.]
[0. 0. 2. 0. 0.]
[0. 0. 0. 2. 0.]
[0. 0. 0. 0. 2.]]

更新於:2022 年 2 月 25 日

172 次瀏覽

啟動您的 事業

完成課程即可獲得認證

開始
廣告
© . All rights reserved.