【发布时间】:2015-03-06 17:27:12
【问题描述】:
我想用高斯函数拟合一个数据数组(在名为“data”的程序中,大小为“n”),我想得到曲线参数的估计值,即均值和 sigma .我在网上找到的以下代码是一种快速的方法吗?如果是这样,我怎样才能真正得到参数的估计值?
import pylab as plb
from scipy.optimize import curve_fit
from scipy import asarray as ar,exp
x = ar(range(n))
y = data
n = len(x) #the number of data
mean = sum(x*y)/n #note this correction
sigma = sum(y*(x-mean)**2)/n #note this correction
def gaus(x,a,x0,sigma,c):
return a*exp(-(x-x0)**2/(sigma**2))+c
popt,pcov = curve_fit(gaus,x,y,p0=[1,mean,sigma,0.0])
print popt
print pcov
plt.plot(x,y,'b+:',label='data')
plt.plot(x,gaus(x,*popt),'ro:',label='fit')
plt.legend()
plt.title('Fig. 3 - Fit')
plt.xlabel('q')
plt.ylabel('data')
plt.show()
【问题讨论】:
-
在这个 IPython 笔记本的底部,我展示了一个使用
astropy的示例,而后者又使用了scipy。 nbviewer.ipython.org/github/j-faria/python-for-astronomers/blob/… -
@johnhenry:我的解决方案有效吗?
标签: python parameters curve-fitting gaussian data-fitting