基于python numpy库实现的二次型标准化的算法

寒假在家,闲来无事,摆烂之余,写了一个基于python numpy的矩阵标准化算法,适用于任意对称阵的标准化(由于规范化很简单就做)。

没用用到任何高级的东西,就是遍历循环按照矩阵的初等变换来标准化,可能效率不是很高,但是除非大型矩阵(几万几百万那种的),一般能见到的矩阵就是秒出结果,当数据较少或较小时算法间的差别并不大(基本没有什么区别)

代码如下:

 1 import numpy as np
 2 
 3 a = np.array(eval(input('请输入矩阵:')), dtype=np.float16)
 4 x = len(a)
 5 print('原矩阵:\n',a)
 6 for n in range(x):
 7     if a[n, n] == 0 and n != x - 1:
 8         v = 0
 9         for i in range(x):
10             v = v + a[n, i]
11         if v == 0:
12             continue
13         else:
14             for i in range(x):
15                 if a[n, i] == 0:
16                     continue
17                 else:
18                     for p in range(x):
19                         a[int(f'{p}'), int(f'{n}')] -= a[int(f'{p}'), int(f'{i}')]
20                     for p in range(x):
21                         a[int(f'{n}'), int(f'{p}')] -= a[int(f'{i}'), int(f'{p}')]
22                     break
23         for i in range(n + 1, x):
24             xi_shu = a[n, i] / a[n, n]
25             for p in range(x):
26                 a[int(f'{p}'), int(f'{i}')] -= a[int(f'{p}'), int(f'{n}')] * xi_shu
27             for p in range(x):
28                 a[int(f'{i}'), int(f'{p}')] -= a[int(f'{n}'), int(f'{p}')] * xi_shu
29     else:
30         for i in range(n + 1, x):
31             xi_shu = a[n, i] / a[n, n]
32             for p in range(x):
33                 a[int(f'{p}'), int(f'{i}')] -= a[int(f'{p}'), int(f'{n}')] * xi_shu
34             for p in range(x):
35                 a[int(f'{i}'), int(f'{p}')] -= a[int(f'{n}'), int(f'{p}')] * xi_shu
36 print('标准化矩阵:\n',a)

 

posted @ 2022-01-23 19:09  清明。  阅读(450)  评论(0编辑  收藏  举报