Python_多项式拟合

来源:互联网 发布:斗牛怎么快速算点数js 编辑:程序博客网 时间:2024/04/28 00:14

所用模块:numpy

实现功能:一元多项式拟合

<span style="font-size:18px;"># -*- coding: utf-8 -*-"""Created on Fri Oct 07 08:07:42 2016@author: zhangweiguo"""'''这里使用numpy来对函数进行最小二乘的多项式拟合'''import numpyfrom matplotlib import pyplot as plclass fitting:def __init__(self,X,Y):self.x=numpy.array(X)self.y=numpy.array(Y)def fitting(self,n):self.z=numpy.polyfit(self.x,self.y,n)self.p=numpy.poly1d(self.z)self.error=numpy.abs(self.y-numpy.polyval(self.p,self.x))self.ER2=numpy.sum(numpy.power(self.error,2))/len(self.x)return self.z,self.pdef geterror(self):return self.error,self.ER2def show(self):figure1=pl.figure()pl.plot(self.x,self.y,'ro-',markersize=7,figure=figure1,label='origin data')pl.plot(self.x,numpy.polyval(self.p,self.x),markersize=7,figure=figure1,label='fitting data')pl.legend()pl.show()def predict(self,x):return numpy.polyval(self.p,x)X=[ 1 ,2  ,3 ,4 ,5 ,6]Y=[ 2.5 ,3.51 ,4.45 ,5.52 ,6.47 ,7.51]F=fitting(X,Y)z,p=F.fitting(3)e,E=F.geterror()print '系数:',zprint '拟合函数:',pprint '最小平方误差:',Eprint 'F(9)的预测值',F.predict(9)F.show()</span>

结果:

系数: [  4.62962963e-04  -1.46825397e-03   9.90925926e-01   1.51333333e+00]
拟合函数:

0.000463 x^3 - 0.001468 x^2 + 0.9909 x + 1.513
最小平方误差:0.00054828042328
F(9)的预测值:10.6502380952


图形显示:



0 0