简体   繁体   English

拟合高斯曲线

[英]Fitting the curve on the gaussian

What is the problem on my code for fitting the curve? 我的曲线拟合代码有什么问题?

I've written some code for fitting my data based on Gaussian distribution. 我已经写了一些代码来根据高斯分布拟合我的数据。 However, I got some wrong value of a, b, c defined at the beginning of the code. 但是,在代码开头定义的a,b,c值有误。 Could you give me some advice to fix that problem? 您能给我一些建议来解决这个问题吗?

from numpy import *
from scipy.optimize import curve_fit

def func(x, a, b, c):
    return a*exp(-(x-b)**2/(2*c**2))
file = loadtxt("angdist1.xvg", skiprows = 18, dtype = float)
x = []
y = []
for i in range(shape(file)[0]):
    x.append(file[i,0])
    y.append(file[i,1])

popt, pcov = curve_fit(func, x, y)

plt.plot(x, func(x, *popt), color = 'red', linewidth=2)
plt.legend(['Original','fitting'], loc=0)
plt.show()

You did not provide initial guesses for your variables a , b , and c . 您没有提供变量abc初始猜测。 scipy.optimize.curve_fit() will make the indefensible choice of silently assuming that you wanted initial values of a=b=c=1 . scipy.optimize.curve_fit()会假设您想要a=b=c=1初始值,从而做出scipy.optimize.curve_fit()的无声选择。 Depending on your data, that could be so far off as to prevent the method from finding any solution at all. 根据您的数据,可能相距太远,以至于根本无法阻止该方法找到任何解决方案。

The solution is to give initial values for the variables that are close. 解决方案是为接近的变量提供初始值。 They don't have to be perfect. 他们不一定是完美的。 For example, 例如,

ainit = y.sum()  # amplitude is within 10x of integral
binit = x.mean() # centroid is near mean x value
cinit = x.std()  # standard deviation is near range of data
popt, pcov = curve_fit(func, x, y, [ainit, binit, cinit])

might give you a better result. 可能会给您带来更好的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM