Fitting Function in SciPy

Fitting Function in SciPy#

import numpy as np
import matplotlib.pyplot as plt
from scipy import optimize
# make up some experimental data
a0 = 2.5
a1 = 2./3.
sigma = 4.0

N = 25

x = np.linspace(0.0, 4.0, N)
r = sigma * np.random.randn(N)
y = a0 * np.exp(a1 * x) + r
yerr = np.abs(r)

fig, ax = plt.subplots()
ax.errorbar(x, y, yerr=yerr, fmt="o")
<ErrorbarContainer object of 3 artists>
../_images/34155b0201f7e11d376084047602bfde06344f2121fd2d3e331cc35dbb0b2f50.png
def resid(avec, x, y, yerr):
    """ the residual function -- this is what will be minimized by the
        scipy.optimize.leastsq() routine.  avec is the parameters we
        are optimizing -- they are packed in here, so we unpack to
        begin.  (x, y) are the data points 

        scipy.optimize.leastsq() minimizes:

           x = arg min(sum(func(y)**2,axis=0))
                    y

        so this should just be the distance from a point to the curve,
        and it will square it and sum over the points
        """

    a0, a1 = avec

    # note: if we wanted to deal with error bars, we would weight each
    # residual accordingly
    return (y - a0 * np.exp(a1 * x)) / yerr
# initial guesses
a0 = 0.5
a1 = 0.5

# fit -- here the args is a tuple of objects that will be added to the
# argument lists for the function to be minimized (resid in our case)
afit, flag = optimize.leastsq(resid, [a0, a1], args=(x, y, yerr))

print(flag)
print(afit)
1
[2.41342982 0.68109146]
ax.plot(x, afit[0] * np.exp(afit[1] * x))
fig
../_images/7ba6c064d2251065fa6ce9a02cd6c9ceeb2776ef8bda98892c3592010b54222d.png