이영규
이영규

Reputation: 1

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()

Upvotes: 0

Views: 46

Answers (1)

M Newville
M Newville

Reputation: 7862

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.

Upvotes: 1

Related Questions