'''
最小二乘法拟合函数曲线
f(x)
1
、拟合多项式为:
y
=
a0
+
a1*x
+
a2*x^2
+
...
+
ak*x^k
2
、求每个点到曲线的距离之和:
Loss
=
∑
(yi
-
(a0
+
a1*x
+
a2*x^2
+
...
+
ak*x^k))^2
3
、最优化
Loss
函数,即求
Loss
对
a0,a1,...ak
的偏导数为
0
3.1
、数学解法——求解线性方程组:
整理最优化的偏导数矩阵为:
X
:含有
xi
的系数矩阵,
A
:含有
ai
的系数矩阵,
Y
:
含有
yi
的系数矩阵
求解:
XA=Y
中的
A
矩阵
3.2
、迭代解法——梯度下降法:
计算每个系数矩阵
A[k]
的梯度,并迭代更新
A[k]
的梯度
A[k]
=
A[k]
-
(learn_rate
*
gradient)
'''
import
numpy
as
np
import
matplotlib.pyplot
as
plt
plt.rcParams['font.sans-serif']
=
['SimHei']
plt.rcParams['axes.unicode_minus']
=
False
'''
高斯列主消元算法
'''
#
得到增广矩阵
def
get_augmented_matrix(matrix,
b):
row,
col
=
np.shape(matrix)
matrix
=
np.insert(matrix,
col,
values=b,
axis=1)
return
matrix
#
取出增广矩阵的系数矩阵(第一列到倒数第二列)
def
get_matrix(a_matrix):
return
a_matrix[:,
:a_matrix.shape[1]
-
1]
#
选列主元,在第
k
行后的矩阵里,找出最大值和其对应的行号和列号
def
get_pos_j_max(matrix,
k):
max_v
=
np.max(matrix[k:,
:])
pos
=
np.argwhere(matrix
==
max_v)
i,
_
=
pos[0]
return
i,
max_v
#
矩阵的第
k
行后,行交换
def
exchange_row(matrix,
r1,
r2,
k):
matrix[[r1,
r2],
k:]
=
matrix[[r2,
r1],
k:]
return
matrix
#
消元计算
(
初等变化
)
def
elimination(matrix,
k):
row,
col
=
np.shape(matrix)
for
i
in
range(k
+
1,
row):
m_ik
=
matrix[i][k]
/
matrix[k][k]
matrix[i]
=
-m_ik
*
matrix[k]
+
matrix[i]
return
matrix
#
回代求解
def
backToSolve(a_matrix):
matrix
=
a_matrix[:,
:a_matrix.shape[1]
-
1]
#
得到系数矩阵
b_matrix
=
a_matrix[:,
-1]
#
得到值矩阵
row,
col
=
np.shape(matrix)
x
=
[None]
*
col
#
待求解空间
X