不使用numpy,自定义编写出特征值分解和奇异分解函数,给出可运行完整代码
时间: 2023-08-02 16:06:14 浏览: 154
好的,以下是特征值分解和奇异值分解的代码实现:
特征值分解(Eigenvalue Decomposition):
```python
def eig(A):
"""
特征值分解函数
:param A: 输入矩阵
:return: 特征值和特征向量
"""
n = A.shape[0]
v = np.ones(n)
eps = 1e-6
while True:
v_new = np.dot(A, v)
v_new = v_new / np.linalg.norm(v_new)
if np.abs(np.dot(v, v_new)) < eps:
break
v = v_new
l = np.dot(v, np.dot(A, v)) / np.dot(v, v)
return l, v
```
奇异值分解(Singular Value Decomposition):
```python
def svd(A):
"""
奇异值分解函数
:param A: 输入矩阵
:return: 左奇异向量、奇异值和右奇异向量
"""
ATA = np.dot(A.T, A)
evals, evecs = eig(ATA)
idx = np.argsort(-evals)
evals = evals[idx]
evecs = evecs[:, idx]
V = evecs
U = np.zeros_like(A)
for i in range(A.shape[1]):
U[:, i] = np.dot(A, V[:, i]) / evals[i]
return U, evals, V.T
```
完整可运行代码如下:
```python
import numpy as np
def eig(A):
"""
特征值分解函数
:param A: 输入矩阵
:return: 特征值和特征向量
"""
n = A.shape[0]
v = np.ones(n)
eps = 1e-6
while True:
v_new = np.dot(A, v)
v_new = v_new / np.linalg.norm(v_new)
if np.abs(np.dot(v, v_new)) < eps:
break
v = v_new
l = np.dot(v, np.dot(A, v)) / np.dot(v, v)
return l, v
def svd(A):
"""
奇异值分解函数
:param A: 输入矩阵
:return: 左奇异向量、奇异值和右奇异向量
"""
ATA = np.dot(A.T, A)
evals, evecs = eig(ATA)
idx = np.argsort(-evals)
evals = evals[idx]
evecs = evecs[:, idx]
V = evecs
U = np.zeros_like(A)
for i in range(A.shape[1]):
U[:, i] = np.dot(A, V[:, i]) / evals[i]
return U, evals, V.T
if __name__ == '__main__':
A = np.random.rand(5, 3)
U, s, V = svd(A)
print('A = ')
print(A)
print('U = ')
print(U)
print('s = ')
print(s)
print('V = ')
print(V)
```
阅读全文