使用 Python 中的 NumPy 計算向量(多維陣列)的內積


內積是線性代數中最重要的一種運算,它接收兩個向量作為輸入,並輸出一個標量值。它也稱為點積或標量積。兩個向量的內積如下所示。

a . b = ||a|| ||b|| cos(Ø)

其中:

  • ||a|| 和 ||b|| 分別是向量 a 和 b 的大小

  • Ø 是向量 a 和 b 之間的夾角

  • a . b 是 a 和 b 的點積

計算內積

如果要計算陣列的內積或點積,則將其計算為陣列各個元素乘積之和。讓我們取兩個陣列 a 和 b 如下所示。

a = [a1, a2, a3]
b = [b1, b2, b3]

以下是用於計算內積的陣列的數學表示式。

a . b = a1 * b1 + a2 * b2 + a3 * b3

使用 NumPy 計算內積

我們可以使用 NumPy 庫中的 `dot()` 函式來計算陣列的點積。

語法

以下是使用 `dot()` 函式計算兩個陣列元素內積的語法。

np.dot(arr1, arr2)

其中:

  • NumPy 是庫的名稱

  • np 是庫的別名

  • dot 是查詢內積的函式

  • arr1arr2 是輸入陣列

示例

在此示例中,當我們將兩個一維陣列作為輸入引數傳遞給 `dot()` 函式時,將返回標量積或內積作為輸出。

import numpy as np
a = np.array([12,30,45])
b = np.array([23,89,50])
inner_product = np.dot(a,b)
print("The Inner product of the two 1-d arrays:", inner_product)

輸出

The Inner product of the two 1-d arrays: 5196

示例

以下是如何使用 `dot()` 函式計算一維陣列內積的示例。

import numpy as np
a = np.array([34,23,98,79,90,34,23,67])
b = np.array([22,1,95,14,91,5,24,12])
inner_product = np.dot(a,b)
print("The Inner product of the two 2-d arrays:",inner_product)

輸出

The Inner product of the two 2-d arrays: 20903

示例

`dot()` 函式只接受方陣作為其引數。如果嘗試傳遞非方陣的值,它將引發錯誤。

import numpy as np
a = np.array([[34,23,98,79],[90,34,23,67]])
b = np.array([[22,1,95,14],[91,5,24,12]])
inner_product = np.dot(a,b)
print("The Inner product of the two 2-d arrays:",inner_product)

錯誤

Traceback (most recent call last):
  File "/home/cg/root/64d07b786d983/main.py", line 4, in <module>
inner_product = np.dot(a,b)
  File "<__array_function__ internals>", line 200, in dot
ValueError: shapes (2,4) and (2,4) not aligned: 4 (dim 1) != 2 (dim 0)

示例

在下面的示例中,我們嘗試使用 `dot()` 函式計算二維陣列的內積。

import numpy as np
a = np.array([[34,23],[90,34]])
b = np.array([[22,1],[91,5]])
inner_product = np.dot(a,b)
print("The Inner product of the two 2-d arrays:", inner_product)

輸出

The Inner product of the two 2-d arrays: [[2841  149][5074  260]]

示例

現在讓我們嘗試透過將三維陣列作為引數傳遞給 `dot()` 函式來計算向量的內積。

import numpy as np
a = np.array([[[34,23],[90,34]],[[43,23],[10,34]]])
b = np.array([[[22,1],[91,5]],[[22,1],[91,5]]])
inner_product = np.dot(a,b)
print("The Inner product of the two 3-d arrays:", inner_product)

輸出

The Inner product of the two 3-d arrays: [[[[2841  149]
   [2841  149]]

  [[5074  260]
   [5074  260]]]


 [[[3039  158]
   [3039  158]]

  [[3314  180]
   [3314  180]]]]

更新於:2023年8月7日

瀏覽量:137

啟動您的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.