使用 NumPy 通过奇异值分解计算给定数组的因子
奇异值分解意味着当arr是二维数组时,它被分解为u和vh ,其中u和vh是二维酉数组, s是 a 的奇异值的一维数组。 numpy.linalg.svd()函数用于通过奇异值分解计算数组的因子。
Syntax : numpy.linalg.svd(a, full_matrices=True, compute_uv=True, hermitian=False)
Parameters :
- a (…, M, N) array : A real or complex array with a.ndim >= 2.
- full_matrices(bool, optional) : If True (default), u and vh have the shapes (…, M, M) and (…, N, N), respectively. Otherwise, the shapes are (…, M, K) and (…, K, N), respectively, where K = min(M, N).
- compute_uv(bool, optional) : Whether or not to compute u and vh in addition to s. Its default value is True.
- hermitian(bool, optional) : If True, a is assumed to be Hermitian (symmetric if real-valued), enabling a more efficient method for finding singular values. Its default value is False.
以下是有关如何使用该函数的一些示例:
示例 1:
Python3
# Import numpy library
import numpy as np
# Create a numpy array
arr = np.array([[0, 0, 0, 0, 1], [2, 0, 0, 1, 3],
[4, 0, 2, 0, 0], [3, 2, 0, 0, 1]],
dtype=np.float32)
print("Original array:")
print(arr)
# Compute the factor by Singular Value
# Decomposition
U, s, V = np.linalg.svd(arr, full_matrices=False)
# Print the result
print("\nFactor of the given array by Singular Value Decomposition:")
print("\nU=", U, "\n\ns=", s, "\n\nV=", V)
Python3
# Import numpy library
import numpy as np
# Create a numpy array
arr = np.array([[8, 4, 0], [2, 5, 1],
[4, 0, 9]], dtype=np.float32)
print("Original array:")
print(arr)
# Compute the factor
U, s, V = np.linalg.svd(arr, full_matrices=False)
# Print the result
print("\nFactor of the given array by Singular Value Decomposition:")
print("\nU=", U, "\n\ns=", s, "\n\nV=", V)
Python3
# Import numpy library
import numpy as np
# Create a numpy array
arr = np.array([[8, 1], [0, 5]], dtype=np.float32)
print("Original array:")
print(arr)
# Compute the factor
U, s, V = np.linalg.svd(arr, full_matrices=False)
# Print the result
print("\nFactor of the given array by Singular Value Decomposition:")
print("\nU=", U, "\n\ns=", s, "\n\nV=", V)
输出 :
示例 2:
Python3
# Import numpy library
import numpy as np
# Create a numpy array
arr = np.array([[8, 4, 0], [2, 5, 1],
[4, 0, 9]], dtype=np.float32)
print("Original array:")
print(arr)
# Compute the factor
U, s, V = np.linalg.svd(arr, full_matrices=False)
# Print the result
print("\nFactor of the given array by Singular Value Decomposition:")
print("\nU=", U, "\n\ns=", s, "\n\nV=", V)
输出 :
示例 3:
Python3
# Import numpy library
import numpy as np
# Create a numpy array
arr = np.array([[8, 1], [0, 5]], dtype=np.float32)
print("Original array:")
print(arr)
# Compute the factor
U, s, V = np.linalg.svd(arr, full_matrices=False)
# Print the result
print("\nFactor of the given array by Singular Value Decomposition:")
print("\nU=", U, "\n\ns=", s, "\n\nV=", V)
输出 :