使用NumPy透過奇異值分解計算給定陣列的因子
奇異值分解 (SVD) 是一種矩陣分解技術,它將矩陣分解為三個部分:左奇異矩陣、對角奇異矩陣和右奇異矩陣。
SVD 是線性代數中一個強大的工具,在資料分析、機器學習和訊號處理中有很多應用。它主要用於計算矩陣的秩,以及執行線性方程組求解、影像壓縮等等操作。
計算奇異值分解
如果我們組成一個大小為 m x n 的實數或複數矩陣 A,則奇異值分解計算以下分解。
A = U * S * V ^T
其中
U 是大小為 m x m 的正交矩陣,包含 A 的左奇異向量。
S 是大小為 m x n 的對角矩陣,包含 A 的奇異值。
VT 是大小為 n x n 的正交矩陣,包含 A 的右奇異向量。
奇異向量 U 和 VT 是正交的,即它們具有單位長度並且彼此垂直。奇異值按降序排列在 S(對角矩陣)的對角線上。
NumPy 中的奇異值分解
Python 中的 NumPy 庫提供了 linalg 模組。該模組提供了許多函式,其中一個函式 SVD() 用於計算給定矩陣的奇異值分解。
語法
以下是用於計算給定矩陣的奇異值分解的語法。
import numpy as np np.linalg.svd(matrix)
其中:
numpy 是庫的名稱。
np 是 numpy 的別名。
linalg 是模組。
svd 是用於計算奇異值分解的函式。
matrix 是輸入矩陣。
示例
當我們想要計算奇異值分解 (SVD) 時,我們必須將矩陣作為輸入引數傳遞給 svd() 函式。
import numpy as np matrix = np.arange(4,8).reshape(2,2) singular_v_d = np.linalg.svd(matrix) print("The singular value decomposition of the given 2x2 square matrix:",singular_v_d)
輸出
執行以上程式碼時,將顯示以下輸出,我們可以觀察到三個陣列,第一個陣列是左奇異陣列,第二個是對角奇異值,最後一個數組是右奇異矩陣。
The singular value decomposition of the given 2x2 square matrix: (array([[-0.57035846, -0.8213959 ], [-0.8213959 , 0.57035846]]), array([11.22355763, 0.17819662]), array([[-0.64238181, -0.76638477], [ 0.76638477, -0.64238181]]))
示例
讓我們看另一個使用 linalg 模組的 svd() 函式計算奇異值分解的示例。
import numpy as np matrix = np.array([[1,23,4],[5,34,56]]) singular_v_d = np.linalg.svd(matrix) print("The singular value decomposition of the given matrix:",singular_v_d)
輸出
The singular value decomposition of the given 2x2 square matrix: (array([[-0.24361576, 0.96987183], [-0.96987183, -0.24361576]]), array([67.60877519, 17.08957337]), array([[-0.07533009, -0.5706183 , -0.8177531 ], [-0.01452389, 0.82062411, -0.57128375], [-0.99705287, 0.0311579 , 0.07010528]]))
示例
讓我們看另一個使用 svd() 函式計算給定矩陣的奇異值分解的示例。
import numpy as np matrix = np.array([[[12,34,23],[23,54,34]],[[10,23,24],[56,68,34]]]) singular_v_d = np.linalg.svd(matrix) print("The singular value decomposition of the given matrix:",singular_v_d)
輸出
The singular value decomposition of the given matrix: (array([[[-0.53294435, -0.84615029], [-0.84615029, 0.53294435]], [[-0.32001136, -0.94741371], [-0.94741371, 0.32001136]]]), array([[80.14845114, 2.49515114], [99.54423363, 14.55834985]]), array([[[-0.32261121, -0.79617538, -0.5118855 ], [ 0.84320202, 0.0039616 , -0.53758224], [ 0.43003763, -0.60505294, 0.67005863]], [[-0.56512848, -0.7211306 , -0.40074987], [ 0.58018245, -0.00204301, -0.81448398], [ 0.58653059, -0.69279613, 0.41954188]]]))
廣告