您的位置:首页 > 其它

一元非线性回归-多项式函数拟合

2016-05-11 20:50 246 查看
参考博客:http://blog.csdn.net/jairuschan/article/details/7517773/
                  http://blog.csdn.net/xiaolewennofollow/article/details/46757657
推导过程:

     1. 设拟合多项式为:

          


     2. 各点到这条曲线的距离之和,即偏差平方和如下:

          


     3. 为了求得符合条件的a值,对等式右边求ai偏导数,因而我们得到了: 

                


          


          

                         .......

          


     4. 将等式左边进行一下化简,然后应该可以得到下面的等式:

          


          


                     .......

          


     5. 把这些等式表示成矩阵的形式,就可以得到下面的矩阵:

          


     

          

     6. 也就是说X*A=Y,那么A
= (X'*X)-1*X'*Y,便得到了系数矩阵A,同时,我们也就得到了拟合曲线。
所以计算出∑ i=1 N x j i (j=0,1,2,⋯,2M) 和∑ i=1 N x j i y i (j=0,1,2,⋯,M) 然后将这些值带入上述线性方程组求解即可。

所以计算出∑ i=1 N x j i (j=0,1,2,⋯,2M) 和∑ i=1 N x j i y i (j=0,1,2,⋯,M) 然后将这些值带入上述线性方程组求解即可。

# coding=utf-8

'''
作者:Xiaole Wen
程序:多项式曲线拟合算法
'''
import matplotlib.pyplot as plt
import math
import numpy
import random

fig = plt.figure()
ax = fig.add_subplot(111)

#在这里给出拟
c962
合多项式的阶数
order=9

#生成曲线上的各个点
x = numpy.arange(-1,1,0.02)
y = [((a*a-1)*(a*a-1)*(a*a-1)+0.5)*numpy.sin(a*2) for a in x]
#ax.plot(x,y,color='r',linestyle='-',marker='')
#,label="(a*a-1)*(a*a-1)*(a*a-1)+0.5"
plt.plot(x,y)                                                                                                                                     #生成的曲线上的各个点偏移一下,并放入到xa,ya中去
i=0
xa=[]
ya=[]
for xx in x:
yy=y[i]
d=float(random.randint(60,140))/100
#ax.plot([xx*d],[yy*d],color='m',linestyle='',marker='.')
i+=1
xa.append(xx*d)
ya.append(yy*d)

ax.plot(xa,ya,color='m',linestyle='',marker='.')
#存储从0次到m次的所有冥方和
bigMat=[]
for j in range(0,2*order+1):
sum=0
for i in range(0,len(xa)):
sum+=(xa[i]**j)
bigMat.append(sum)

#计算线性方程组系数矩阵
matA=[]
for rowNum in range(0,order+1):
row=bigMat[rowNum:rowNum+order+1]
matA.append(row)

matA=numpy.array(matA)

matB=[]
for i in range(0,order+1):
ty=0.0
for k in range(0,len(xa)):
ty+=ya[k]*(xa[k]**i)
matB.append(ty)

matB=numpy.array(matB)

matAA=numpy.linalg.solve(matA,matB)

#画出拟合后的曲线
#print(matAA)
xxa= numpy.arange(-1,1.06,0.01)
yya=[]
for i in range(0,len(xxa)):
yy=0.0
for j in range(0,order+1):
dy=(xxa[i]**j)
dy*=matAA[j]
yy+=dy
yya.append(yy)
ax.plot(xxa,yya,color='g',linestyle='-',marker='')

ax.legend()
plt.show()


下面给出阶叔分别取3和取9的时候的拟合结果

图中蓝色的线代表原始数据生成函数,绿色代表拟合函数


 





内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: