Reputation: 215
I am using this code to curve fit some data:
def extract_parameters(Ts, ts):
def model(t, Ti, Ta, c):
return (Ti - Ta)*math.e**(-t / c) + Ta
popt, pcov = cf(model, Ts, ts, p0 = (10, 6, 7))
Ti, Ta, c = popt
maxx = max(Ts)
xfine = np.linspace(0, maxx, 101)
print "xfine: ", xfine
yfitted = model(xfine, *popt)
print "yfittted", yfitted
pl.plot(Ts, ts, 'o', label = 'data point')
pl.plot(xfine, yfitted, label = 'fit')
pylab.legend()
pylab.show()
return Ti, Ta, c
When I enter:
extract_parameters([1,2,3,4,5,6],[100,60,50,40,45,34])
I get a perfect fit
but when I enter:
extract_parameters([1,2,3,4,5,6,7],[100,80,70,65,60,58,56])
I get this instead
Can anyone see why? The curve fit changes drastically?
Upvotes: 0
Views: 337
Reputation: 881027
Optimizers like curve_fit
try to find the optimal fit, but don't always succeed.
Notice that extract_parameters([1,2,3,4,5,6],[100,60,50,40,45,34])
returns
(196.85292746741234, 38.185643828689777, 1.0537367332516778)
That means it started with an initial parameter guess of p0 = (10, 6, 7)
and found its way to quite a different location.
You can help the optimizer out by picking an initial guess which is closer to the optimal value. Simply by changing it to
p0 = (100, 6, 7)
allows
extract_parameters([1,2,3,4,5,6,7],[100,80,70,65,60,58,56])
to find a better fit: (131.71232607048836, 54.894539483338022, 1.8503931318517444)
.
Upvotes: 2