I have a well behaved data-set, and I try to fit this data-set with two Gaussian fitting. My code for fitting this data-set is:
from scipy import stats
from pylab import *
from scipy.optimize import curve_fit
from scipy.integrate import*
from lmfit import Model
data=concatenate((normal(1,.2,5000),normal(2,.2,2500)))
y,x,_=hist(data,100,alpha=.3,label='data')
x=(x[1:]+x[:-1])/2
def gaussian1(x, amp1, cen1, wid1):
"1-d gaussian: gaussian(x, amp, cen, wid)"
return (amp1/(sqrt(2*pi)*wid1)) * exp(-(x-cen1)**2 /(2*wid1**2))
def gaussian2(x, amp2, cen2, wid2):
"1-d gaussian: gaussian(x, amp, cen, wid)"
return (amp2/(sqrt(2*pi)*wid2)) * exp(-(x-cen2)**2 /(2*wid2**2))
gmodel = Model(gaussian1) + Model(gaussian2)
#pars = gmodel.make_params( amp1=20,cen1=1.0,wid1=0.2,amp2=10,cen2=2.0,wid2=0.19)
pars = gmodel.make_params(amp1=260,cen1=1.0,wid1=0.2,amp2=140,cen2=2.0,wid2=0.19)
result = gmodel.fit(y, pars, x=x)
print(result.fit_report())
#plt.plot(x, y, 'bo')
plt.plot(x, result.init_fit, 'k--',label='Initial Fit')
plt.plot(x, result.best_fit, 'r-',label='Best Fit')
plt.show()
This returns the below output and plot:
[[Model]]
(Model(gaussian1) + Model(gaussian2))
[[Fit Statistics]]
# fitting method = leastsq
# function evals = 29
# data points = 100
# variables = 6
chi-square = 8297.41156
reduced chi-square = 88.2703358
Akaike info crit = 453.852870
Bayesian info crit = 469.483891
[[Variables]]
amp1: 122.899857 +/- 1.52937166 (1.24%) (init = 260)
cen1: 1.00027783 +/- 0.00288716 (0.29%) (init = 1)
wid1: 0.20129987 +/- 0.00290241 (1.44%) (init = 0.2)
amp2: 61.0231508 +/- 1.51470406 (2.48%) (init = 140)
cen2: 1.99916357 +/- 0.00564876 (0.28%) (init = 2)
wid2: 0.19744994 +/- 0.00567828 (2.88%) (init = 0.19)
[[Correlations]] (unreported correlations are < 0.100)
C(amp2, wid2) = 0.581
C(amp1, wid1) = 0.581
C(wid1, wid2) = -0.103
The plot for this fit looks fine. But the problem is that the value of the two amplitude values amp1, amp2
do not match those shown in the plot:
According to the plot amp1=255
and amp2 = 125
According to the printed values amp1 = 122.89
and amp2 = 61.02
Another thing is that it returns a very high chi-square value (e.g., 8297.41).
Please help me fix the value of amp1, amp2
and chi-square value and solve these issues.