NumPy - 點積



什麼是點積?

點積,也稱為標量積,是一種數學運算,它接受兩個等長數字序列(通常是向量)並返回單個數字。

在矩陣的上下文中,點積用於執行矩陣乘法,這是許多數學、物理和工程領域的基本運算。

兩個向量ab的點積定義為:

a . b = a1b1 + a2b2 + ... + anbn

其中,aibi分別是向量ab的分量,n是維數。

使用點積進行矩陣乘法

在矩陣乘法中,點積用於將第一個矩陣的行乘以第二個矩陣的列。這會產生一個新矩陣,其中每個元素都是對應行和列向量的點積。

考慮兩個矩陣AB

A = [[a11, a12],
         [a21, a22]]

B = [[b11, b12],
         [b21, b22]]

乘積C = A . B為:

C = [[a11b11 + a12b21, a11b12 + a12b22],
         [a21b11 + a22b21, a21b12 + a22b22]]

使用 NumPy 進行點積

NumPy 提供了一種方便的方法來使用dot()函式執行點積。此函式可用於向量點積和矩陣乘法。

示例

在下面的示例中,點積計算為 (1 * 4) + (2 * 5) + (3 * 6) = 32:

import numpy as np

# Define two vectors
vector_1 = np.array([1, 2, 3])
vector_2 = np.array([4, 5, 6])

# Compute dot product
dot_product = np.dot(vector_1, vector_2)
print(dot_product)

以下是獲得的輸出:

32

矩陣點積

要計算兩個矩陣的點積,我們使用相同的dot()函式。

示例

在這個例子中,兩個矩陣的點積計算如下:

[[1*5 + 2*7, 1*6 + 2*8],
 [3*5 + 4*7, 3*6 + 4*8]]
import numpy as np

# Define two matrices
matrix_1 = np.array([[1, 2], [3, 4]])
matrix_2 = np.array([[5, 6], [7, 8]])

# Compute dot product
matrix_product = np.dot(matrix_1, matrix_2)
print(matrix_product)

以下是獲得的輸出:

[[19 22]
 [43 50]]

更高維陣列的點積

NumPy 的dot()函式也可以處理更高維的陣列。在這種情況下,該函式計算第一個陣列的最後一個軸和第二個陣列的倒數第二個軸上的點積。

示例

在這個例子中,為每一對子陣列計算點積,得到一個新的三維陣列:

import numpy as np

# Define two 3-dimensional arrays
array_1 = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
array_2 = np.array([[[1, 0], [0, 1]], [[1, 1], [1, 0]]])

# Compute dot product
array_product = np.dot(array_1, array_2)
print(array_product)

以下是獲得的輸出:

[[[[ 1  2]
   [ 3  1]]

  [[ 3  4]
   [ 7  3]]]


 [[[ 5  6]
   [11  5]]

  [[ 7  8]
   [15  7]]]]

使用 @ 運算子進行點積

在 Python 3.5 及更高版本中,@運算子可以用作矩陣乘法的dot()函式的替代方法。這使得程式碼更易讀且更簡潔。

示例

以下示例的結果與使用dot()函式相同,但語法更簡潔:

import numpy as np

# Define two matrices
matrix_1 = np.array([[1, 2], [3, 4]])
matrix_2 = np.array([[5, 6], [7, 8]])

# Using @ operator for matrix multiplication
matrix_product = matrix_1 @ matrix_2
print(matrix_product)

以下是獲得的輸出:

[[19 22]
 [43 50]]

點積的應用

點積是一個基本運算,在各個領域都有很多應用:

  • 機器學習:點積用於計算向量之間的相似度,這在支援向量機和神經網路等演算法中至關重要。
  • 物理學:點積用於計算力所做的功以及在不同方向上投影向量。
  • 計算機圖形學:點積用於著色計算以及確定表面和光源之間的角度。
  • 線性代數:點積是求解線性方程組和變換的基礎。

示例:在機器學習中使用點積

在機器學習中,點積通常用於計算神經網路中的權重和偏差。

在這個例子中,點積計算輸入特徵的加權和,這是計算神經網路輸出的重要步驟:

import numpy as np

# Define input vector (features)
input_vector = np.array([0.5, 1.5, -1.0])

# Define weight vector (weights)
weights = np.array([2.0, -1.0, 0.5])

# Compute the weighted sum (dot product)
output = np.dot(input_vector, weights)
print(output)

以下是獲得的輸出:

-1.0
廣告