Levenberg-Marquardt non-linear least-squares fitting in Python [follow-on]

edmondo.giovannozzi at gmail.com edmondo.giovannozzi at gmail.com
Fri Mar 29 05:35:04 EDT 2019



>     ltemp = [ydata[i] - ydata[0] for i in range(ll)]
>     ytemp = [ltemp[i] * .001 for i in range(ll)]
>     ltemp = [xdata[i] - xdata[0] for i in range(ll)]
>     xtemp = [ltemp[i] * .001 for i in range(ll)]

Use the vectorization given by numpy:

      ytemp = (ydata - ydata[0]) * 0.001
      xtemp =  (xdata - xdata[0]) * 0.001

....
      fitted =  popt[0] - popt[1] * np.exp(-popt[2] * xtemp)

 or better

      fitted = func2fit(xtemp, *popt)
  

> #
> #  popt is a list of the three optimized fittine parameters [a, b, c]
> #  we are interested in the value of a.
> #  cov is the 3 x 3 covariance matrix, the standard deviation (error) of the fit is
> #  the square root of the diagonal.
> #
>     popt,cov = curve_fit(func2fit, xtemp, ytemp)
> #
> #  Here is what the fitted line looks like for plotting
> #
>     fitted = [popt[0] - popt[1] * np.exp(-popt[2] * xtemp[i]) for i in range(ll)]
> #
> #  And now plot the results to check the fit
> #    
>     fig1, ax1 = plt.subplots()
>     plt.title('Normalized Data ' + str(run_num))
>     color_dic = {0: "red", 1: "green", 2: "blue", 3: "red", 4: "green", 5: "blue"}
>     ax1.plot(xtemp, ytemp, marker = '.', linestyle  = 'none', color = color_dic[run_num])
>     ax1.plot(xtemp, fitted, linestyle = '-', color = color_dic[run_num])
>     plt.savefig('Normalized ' + str(run_num))
>     perr = np.sqrt(np.diag(cov))
>     return popt, cov, xdata[0], ydata[0], fitted, perr[0]




More information about the Python-list mailing list