pythoncurve-fittinglmfit

Extracting variables from fit statistics parameters after curve fitting using lmfit


I am using lmfit to plot a Gaussian fit against my data. I want to extract just one of the variable parameters (eg: I0 ) and store it in an array. Any suggestions to would really help. I have attached my sample code below:

def Gauss(x,I0,x0,sigma,Background):
            return I0*exp((-(x-x0)**2)/(2*sigma**2))+Background   
mod=Model(Gauss)
result=mod.fit(yData,x=xData,I0=1,x0=mean,sigma=sigma,Background=1)
result.plot()
plt.grid()
plt.xlabel('x,y,z distribution')
plt.ylabel('PL intensity')
basename=os.path.basename(file)
plt.title(basename)
print('The fit statistics for',basename)
print(result.fit_report()) 


[[Fit Statistics]]
    # fitting method   = leastsq
    # function evals   = 264
    # data points      = 30
    # variables        = 4
    chi-square         = 8379722.68
    reduced chi-square = 322297.026
    Akaike info crit   = 384.203840
    Bayesian info crit = 389.808629
[[Variables]]
    I0:          6128.15928 +/- 343.334644 (5.60%) (init = 1)
    x0:         -5.1147e-07 +/- 3.1252e-08 (6.11%) (init = -4.039265e-07)
    sigma:      -7.4953e-07 +/- 6.0842e-08 (8.12%) (init = 9.136697e-07)
    Background:  1730.50204 +/- 338.181818 (19.54%) (init = 1)

Solution

  • reading the lmfit documentation and going through some of the examples might help. On SO, the expectation is that you would show what you tried and what may not have worked as you expected.

    You say:

    I want to extract all the variable parameters (eg: I0 ) and plot it against my data and visualise the error bars for my fits.

    The resulting parameters are in result.params, a dictionary with keys of parameter names and values of lmfit.Parameter, which will have multiple attributes.

    If you want just the best-fit parameter values, you might try

    print(result.params.valuesdict())

    For more, consult the docs.

    I'm not sure what you mean by "plot it against my data and visualise the error bars for my fits."

    You also say:

    I also want to compute the variable parameters for each of my data points and store in an array.

    Perhaps you mean that you would like the array values for the model? If so, that's in result.best_fit.