svd代码实现python
时间: 2023-09-30 20:08:03 浏览: 100
SVD实现代码
5星 · 资源好评率100%
Sure! Here is the Python code to implement Singular Value Decomposition (SVD) using NumPy:
```python
import numpy as np
def svd(matrix):
U, s, Vt = np.linalg.svd(matrix)
return U, s, Vt
# Example usage
A = np.array([[4, 0], [3, -5]])
U, s, Vt = svd(A)
print("Matrix A:")
print(A)
print("\nU:")
print(U)
print("\nSingular values:")
print(s)
print("\nVt:")
print(Vt)
```
In this code, we first import the NumPy library. Then, we define the `svd()` function that takes a matrix as input and computes its singular value decomposition using the `np.linalg.svd()` function from NumPy. The function returns the left singular vectors (U), singular values (s), and right singular vectors (Vt).
We then provide an example usage where we define a matrix `A`, compute its SVD using the `svd()` function, and print the original matrix, U, s, and Vt to the console.
Note: SVD can also be computed using other libraries like SciPy and scikit-learn. The above code demonstrates the usage with NumPy.
阅读全文