赞
踩
最小二乘法(又称最小平方法)是一种数学优化技术。它通过最小化误差的平方和寻找数据的最佳函数匹配。利用最小二乘法可以简便地求得未知的数据,并使得这些求得的数据与实际数据之间误差的平方和为最小。最小二乘法还可用于曲线拟合。
对于线性拟合,最小二乘法存在解析解,其矩阵形式的公式如下所示:
X
B
=
Y
⇒
B
=
(
X
T
X
)
−
1
X
T
Y
\mathbf{X B}=\mathbf{Y} \Rightarrow \mathbf{B}=\left(\mathbf{X}^{T} \mathbf{X}\right)^{-1} \mathbf{X}^{T} \mathbf{Y}
XB=Y⇒B=(XTX)−1XTY
import numpy as np from matplotlib import pyplot as plt X = np.array([[0,1],[1,1],[2,1],[3,1],[4,1]]) y = np.array([0,2,1,2,4]) Xt = X.transpose() Xs = np.matmul(Xt,X) Xsi = np.linalg.inv(Xs) Wstar = np.matmul(np.matmul(Xsi,Xt),y) print(Wstar) Xhat = Wstar[0]*y + Wstar[1] print(Xhat) Xp = X[:,0] plt.scatter(Xp,y) plt.plot(Xhat,y) plt.show()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。