写了一下, 效率很低, 数据样本是从GSLA扒下来的, 有空继续改进
import numpy as np
import math
# Given a matrix and its transposed
matrix = np.array([[2, 2], [1, 1]])
matrix_transposed = np.matrix.transpose(matrix)
# Generate (A^T)A and A(A^T)
left_symmetric_matrix = np.matmul(matrix, matrix_transposed)
right_symmetric_matrix = np.matmul(matrix_transposed, matrix)
left_singular_values, left_singular_vectors = np.linalg.eig(
left_symmetric_matrix)
right_singular_values, right_singular_vectors \
= np.linalg.eig(right_symmetric_matrix)
# Sort the eigenvalues
U = np.array([ele for _, ele in sorted(
zip(left_singular_values, left_singular_vectors), reverse=True)])
# Construct a diagonal
Sigma = np.zeros(matrix.shape)
np.fill_diagonal(Sigma, [math.sqrt(abs(val)) for val in left_singular_values])
# V^T
VT = np.array([ele for _, ele in
sorted(zip(right_singular_values, right_singular_vectors), reverse=True)])
VT = np.matrix.transpose(VT)
print("U=", '\n', U, end='\n\n')
print("Sigma=", '\n', Sigma, end='\n\n')
print("V^T=", '\n', VT, end='\n\n')