💬 例1
import numpy as np
# 打印A
def pprint(msg, A):
print("---", msg, "---")
(n,m) = A.shape
for i in range(0, n):
line = ""
for j in range(0, m):
line += "{0:.2f}".format(A[i,j]) + "\t"
print(line)
print("")
print("奇异值分解\n")
A = np.array([
[1,2,3,4,5,6,7,8,9,10],
[11,12,13,14,15,16,17,18,19,20],
[21,22,23,24,25,26,27,28,29,30]])
pprint("数据", A)
U, s, VT = np.linalg.svd(A) # 奇异值分解
pprint("U", U)
m, n = A.shape
Sigma = np.zeros((m, n)) # mxn 矩阵 sigma
k = np.size(s)
Sigma[:k, :k] = np.diag(s) # 奇异值
pprint("Sigma", Sigma)
pprint("V^T", VT) # nxn 矩阵 V^T
# 奇异值选择
n_elements = 2
Sigma = Sigma[:, :n_elements]
VT = VT[:n_elements, :]
# 低系数近似重构数据
B = np.matmul(U, np.matmul(Sigma, VT))
pprint("重构的数据: ", B)
🚩 运行结果:
奇异值分解
--- 数据 ---
1.00 2.00 3.00 4.00 5.00 6.00 7.00 8.00 9.00 10.00
11.00 12.00 13.00 14.00 15.00 16.00 17.00 18.00 19.00 20.00
21.00 22.00 23.00 24.00 25.00 26.00 27.00 28.00 29.00 30.00
--- U ---
-0.19 0.89 0.41
-0.51 0.26 -0.82
-0.84 -0.37 0.41
--- Sigma ---
96.97 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00
0.00 7.26 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00
0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00
--- V^T ---
-0.24 -0.26 -0.27 -0.29 -0.30 -0.32 -0.34 -0.35 -0.37 -0.38
-0.54 -0.43 -0.32 -0.21 -0.10 0.01 0.12 0.23 0.34 0.44
-0.72 0.22 0.36 0.23 0.12 0.28 -0.35 0.06 -0.00 -0.20
-0.03 -0.18 -0.38 0.89 -0.08 -0.12 0.03 -0.07 -0.05 -0.01
-0.08 -0.06 -0.31 -0.09 0.92 -0.12 -0.01 -0.10 -0.10 -0.07
0.07 0.08 -0.47 -0.10 -0.08 0.84 0.04 -0.14 -0.14 -0.09
-0.34 0.17 0.06 -0.02 -0.06 -0.08 0.86 -0.16 -0.19 -0.23
-0.02 0.33 -0.33 -0.06 -0.07 -0.17 -0.03 0.80 -0.23 -0.22
-0.03 0.45 -0.31 -0.04 -0.07 -0.17 -0.05 -0.23 0.73 -0.27
-0.13 0.57 -0.16 -0.02 -0.06 -0.16 -0.11 -0.26 -0.32 0.65
--- 重构的数据: ---
1.00 2.00 3.00 4.00 5.00 6.00 7.00 8.00 9.00 10.00
11.00 12.00 13.00 14.00 15.00 16.00 17.00 18.00 19.00 20.00
21.00 22.00 23.00 24.00 25.00 26.00 27.00 28.00 29.00 30.00
参考文献
Introduction to Linear Algebra, International 4 th Edition by Gilbert Strang, Wellesley Cambridge Press.
百度百科[EB/OL]. []. https://baike.baidu.com/
本篇完。