1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
import os import matplotlib.pyplot as plt import numpy as np import scipy os.chdir('/home/vg/Downloads/projects/ex19') os.getcwd() beta=(0.25,0.75,0.5) def f(x,b0,b1,b2): return b0+b1*np.exp(-b2*x**2) xdata=np.linspace(0,5,50) y=f(xdata,*beta) ydata=y+0.05*np.random.randn(len(xdata)) def g(beta): return ydata-f(xdata,*beta) beta_start=(1,1,1) beta_opt,beta_cov=scipy.optimize.leastsq(g,beta_start) print(beta_opt) fig,ax=plt.subplots() ax.scatter(xdata,ydata,label='samples') ax.plot(xdata,y,'r',lw=2,label='true model') ax.plot(xdata,f(xdata,*beta_opt),'b',lw=2,label='fitted model') ax.set_xlim(0,5) ax.set_xlabel(r"$x$",fontsize=18) ax.set_ylabel(r"$f(x,\beta)$",fontsize=18) ax.legend() ax.set_title("Nonlinear least square fitting") plt.savefig("example19.png", dpi=100) plt.show() plt.close() beta_opt,beta_cov=scipy.optimize.curve_fit(f,xdata,ydata) print(beta_opt) <img class=" wp-image-108 aligncenter" src="https://gantovnik.com/bio-tips/wp-content/uploads/2018/12/example19.png" alt="example19" width="548" height="365" /> |
Recent Comments