Reputation: 3202
I am trying to to fit my data to a Gaussian using Scipy curve_fit. Unfortunately curve_fit returns 1,1,1.
Kp4=fnamer4[615:645]
xk=np.arange(0,1024,1)[615:645]
def func(x, a, x0, sigma):
return a*np.exp(-(x-x0)**2/(2*sigma**2))
popt, pcov = curve_fit(func, xk, Kp4)
print (popt)
Kp4_fit= func(xk, popt[0], popt[1], popt[2])
plt.plot(xk, Kp4_fit, 'r',xk, Kp4, 'bs')
Kp4 is equal to
>>> Kp4
array([23, 27, 20, 26, 22, 22, 26, 29, 32, 19, 34, 26, 29, 24, 32, 41, 27,
39, 33, 30, 30, 30, 26, 39, 30, 21, 17, 16, 17, 14])
The output of the print popt is [ 1. 1. 1.]
I have tried curve_fit on much different data before, and it worked fine. Perhaps the problem is that curve_fit cannot fit the data the Gaussian function?!
Thanks for any help.
The concept I am using for the curve_fit is based on an example from a link bellow: http://python4esac.github.io/fitting/examples1d.html
Upvotes: 1
Views: 176
Reputation: 1588
You have to pass an initial guess for popt, otherwise the fit starts with [1,1,1] as initial guess which is pretty poor for your dataset!
The following gives reasonable results for me:
popt, pcov = curve_fit(func, xk, Kp4, p0=[20,630,5])
The initial guess could be [np.mean(Kp4), np.mean(xk),5*(max(xk)-min(xk))/len(xk)]
, to have a general starting point.
Don't forget to put plt.show()
or something similar at the end.
Upvotes: 1