简体   繁体   中英

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. 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 . scipy.optimize.curve_fit() will make the indefensible choice of silently assuming that you wanted initial values of a=b=c=1 . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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