<>根据坐标点用最小二乘法进行曲线拟合
已知观测数据表如下,试用最小二乘法求一个二次多项式 y = c1+c2x+ c3x^2
x0012345
y0521123 import numpy as np import matplotlib.pyplot as plt A = np.array([[1,0,
0],[1,0,0],[1,1,1],[1,2,4],[1,3,9],[1,4,16],[1,5,25]]) B = np.array([0,5,2,1,1,2
,3]) ATA = np.matmul(A.T,A)#求A的转置与A相乘 ATB = np.matmul(A.T,B)#求A的转置与B相乘 np.
set_printoptions(formatter={'float':'{:0.6f}'.format})#格式化输出数组 print(np.matmul(
np.linalg.inv(ATA),ATB))#求解 x = np.matmul(np.linalg.inv(ATA),ATB) xlist = np.
arange(0,5,0.01) ylist = [] for i in xlist: ylist.append(x[0]+i*x[1]+x[2]*(i**2)
)#用拟合曲线求纵坐标 plt.xlabel('x') plt.ylabel('y') plt.scatter([0,0,1,2,3,4,5],[0,5,2,1
,1,2,3],c='g',label='scatter')#画出原来观测点的位置 plt.plot(xlist,ylist,label='plot')
#画出拟合曲线 plt.legend() plt.show()
最小二乘法原理以及推导过程后续补充
感谢观看!