I'm trying to compute the best fit of two forms of an exponential to some x, y
data (the data file can be downloaded from here)
Here's the code:
from scipy.optimize import curve_fit
import numpy as np
# Get x,y data
data = np.loadtxt('data.txt', unpack=True)
xdata, ydata = data[0], data[1]
# Define first exponential function
def func(x, a, b, c):
return a * np.exp(b * x) + c
# Get parameters estimate
popt, pcov = curve_fit(func, xdata, ydata)
print popt
# Define second exponential function (one more parameter)
def func2(x, a, b, c, d):
return a * np.exp(b * x + c) + d
# Get parameters estimate
popt2, pcov2 = curve_fit(func2, xdata, ydata)
print popt2
The first exponential gives the exact same values as zunzun.com (PDF here) for popt
:
[ 7.67760545e-15 1.52175476e+00 2.15705939e-02]
but the second gives values that are clearly wrong for popt2
:
[ -1.26136676e+02 -8.13233297e-01 -6.66772692e+01 3.63133641e-02]
This are zunzun.com values (PDF here) for that same second function:
a = 6.2426224704624871E-15
b = 1.5217697532005228E+00
c = 2.0660424037614489E-01
d = 2.1570805929514186E-02
I tried making the lists arrays as reccomended here Strange result with python's (scipy) curve fitting, but that didn't help. What am I doing wrong here?
Add 1
I'm guessing the problem has to do with the lack of initial values I'm feeding my function (as explained here: gaussian fit with scipy.optimize.curve_fit in python with wrong results)
If I feed the estimates from the first exponential to the second one like so (making the new parameter d
be initially zero):
popt2, pcov2 = curve_fit(func2, xdata, ydata, p0 = [popt[0], popt[1], popt[2], 0])
I get results that are much reasonable but still wrong compared to zunzun.com:
[ 1.22560853e-14 1.52176160e+00 -4.67859961e-01 2.15706930e-02]
So now the question changes to: how can I feed my second function more reasonable parameters automatically?