数学建模 of python(用最小二乘法对多项式进行拟合)

吉吉:

刚参加完数学建模竞赛,本篇文章所讲代码是对A题附件的数据进行拟合,如下:

import xlrd
import numpy
from matplotlib import pyplot as pl
data=xlrd.open_workbook(r'C:\Users\admin\Desktop\1.xlsx')
table=data.sheet_by_name('sheet1')
a=table.col_values(0)[2:]
b=table.col_values(1)[2:]
x=numpy.array(a)
y=numpy.array(b)
class 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.p
	def geterror(self):
		return self.error,self.ER2
	def show(self):
		figure1=pl.figure()
		pl.plot(self.x,self.y,'ro-',markersize=0.5,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)
F=fitting(x,y)
z,p=F.fitting(5)
e,E=F.geterror()
print ('系数:',z)
print ('拟合函数:',p)
print ('最小平方误差:',E)
a=6000#通过改变a的值来进行预测
print ('F({})的预测值'.format(a),F.predict(a))
F.show()

ending啦啦啦。。。。

猜你喜欢

转载自blog.csdn.net/weixin_41503009/article/details/82746513
今日推荐