pthon最小二乘法实现以及”坑位避让“
初次最小二乘法实现:
import numpy as np import scipy as sp import pylab as pl from scipy.optimize import leastsq n = 9 def real_func(x): return np.sin(2*np.pi*x) def fit_func(p,x): f=np.polyld(p) return f(x) def resideals_func(p,y,x): ret = fit_func(p,x) - y return ret ...
在这里出现了第一个问题!
模块numpy中没有poyld,我思量很久终于发现是字母的问题,poly1d中的1是数字1并不是L !!!不得不说这个浪费时间的东西,坑啊!
你知道之后就继续写,终于写完了!
x = np.linspace(0,1,9) x_points = np.linspace(0,1,1000) y0 = real_func(x) y1 = [np.random.normal(0,0.1)+ y for y in y0] p_init = np.random.rand(n) plsq = leastsq(func=resideals_func,x0=p_init,args=(y1,x)) print('Fitting Parameters:',plsq[0]) pl.plot(x_points,real_func(x_points),label='real') pl.plot(x_points,fit_func(plsq[0],x_points),label='fitting curve') pl.plot(x,y1,'bo',label = 'with noise') pl.legend() pl.show()
看图发现拟合的很好,不错,这时你就去修改参数让模型更好,将plsq[0]修改为plsq[5]时,你就会发现......
第二个问题
x = np.linspace(0,1,9) x_points = np.linspace(0,1,1000) y0 = real_func(x) y1 = [np.random.normal(0,0.1)+ y for y in y0] p_init = np.random.rand(n+0) plsq = leastsq(func=resideals_func,x0=p_init,args=(y1,x)) print('Fitting Parameters:',plsq[5]) pl.plot(x_points,real_func(x_points),label='real') pl.plot(x_points,fit_func(plsq[5],x_points),label='fitting curve') pl.plot(x,y1,'bo',label = 'with noise') pl.legend() pl.show()
元组索引超出范围...你又不能放弃那就继续去找解决办法吧,终于找到了改进的办法,但是这个问题还时存在的,由于还是个小白,还请大家帮忙解决一下呀。
下面时修改的代码,供参考
import numpy as np import scipy as sp import pylab as pl from scipy.optimize import leastsq #目标函数 def real_func(x): return np.sin(2*np.pi*x) #多项式,,注意poly1d y后面是数字1不是L def fit_func(p,x): f=np.poly1d(p) return f(x) #残差 def resideals_func(p,y,x): ret = fit_func(p,x) - y return ret #随机选择9个点 x = np.linspace(0,1,9) x_points = np.linspace(0,1,1000) #目标函数 y0 = real_func(x) #在目标函数上添加符合正太分布的噪声函数 y1 = [np.random.normal(0,0.1)+ y for y in y0] def Fitting(n = 0): #随机初始化多项式参数 p_init = np.random.rand(n+0) #通过leastsq函数,寻找最佳匹配函数 #** #func :残差函数,x0 :初始参数值,打包到args中 #* plsq = leastsq(func=resideals_func,x0=p_init,args=(y1,x)) print('Fitting Parameters:',plsq[0]) #可视化 pl.plot(x_points,real_func(x_points),label='real') pl.plot(x_points,fit_func(plsq[0],x_points),label='fitting curve') pl.plot(x,y1,'bo',label = 'with noise') pl.legend() pl.show() plsq_1 = Fitting(1) plsq_5 = Fitting(5) plsq_9 = Fitting(9)
参考:https://blog.csdn.net/dz4543/article/details/85224391