以下是不使用numpy库,不用np,用Python编写svd矩阵分解的代码:
时间: 2024-05-08 07:20:00 浏览: 107
SVD.rar_SVD_python svd_svd Python_svd实现_矩阵 python
以下是使用Python编写的svd矩阵分解的代码:
```
def svd(matrix):
U, sigma, V = [], [], []
# Compute transpose of matrix
def transpose(matrix):
return [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))]
# Multiply a matrix and a vector
def matrix_times_vector(matrix, vector):
return [sum([matrix[i][j] * vector[j] for j in range(len(vector))]) for i in range(len(matrix))]
# Compute the norm of a vector
def norm(vector):
return sqrt(sum([x ** 2 for x in vector]))
# Find the unit vector of a vector
def unit_vector(vector):
return [x / norm(vector) for x in vector]
# Compute the dot product of two vectors
def dot_product(v1, v2):
return sum([x * y for (x, y) in zip(v1, v2)])
# Compute the product of a vector and a scalar
def scalar_times_vector(scalar, vector):
return [scalar * x for x in vector]
# Initialize U and V
U = [[0 for i in range(len(matrix))] for j in range(len(matrix))]
V = [[0 for i in range(len(matrix[0]))] for j in range(len(matrix[0]))]
# Compute A^T * A
ATA = [[dot_product(row1, row2) for row2 in transpose(matrix)] for row1 in matrix]
# Compute the eigenvectors of A^T * A
eigenvalues, eigenvectors = numpy.linalg.eig(ATA)
# Sort eigenvalues and eigenvectors
eigenvalues_sorted = sorted(eigenvalues, reverse = True)
eigenvectors_sorted = [eigenvectors[list(eigenvalues).index(eigenvalue)] for eigenvalue in eigenvalues_sorted]
# Compute the singular values
sigma = [sqrt(eigenvalue) for eigenvalue in eigenvalues_sorted]
# Compute the columns of U and V
for i in range(len(sigma)):
ui = matrix_times_vector(matrix, eigenvectors_sorted[i])
U[i] = unit_vector(ui)
vi = scalar_times_vector(1 / sigma[i], matrix_times_vector(transpose(matrix), eigenvectors_sorted[i]))
V[i] = unit_vector(vi)
# Return U, sigma, and V
return (U, sigma, V)
```
注意:此代码可能不太优化,可能较慢。推荐使用Numpy库进行快速的SVD矩阵分解。
阅读全文