[SciPy-User] Trouble using curve_fit

Robert Kern robert.kern at gmail.com
Mon Jan 9 14:07:24 EST 2012


On Mon, Jan 9, 2012 at 18:56, klo uo <klonuo at gmail.com> wrote:
> Example provided at the bottom of this page: scipy.optimize.curve_fit seemed
> perfect for what I hoped I need, but result was bad. I don't know if I
> misuse it or I don't have enough data, but as can be seen from attached
> screen-shot, I did not expect problem for finding obvious exponential
> function fit.
>
> Here is snippet:
> ========================================
> import numpy as np
> from scipy.optimize import curve_fit
>
> def func(x, a, b, c):
>     return a*np.exp(-b*x)+c
>
> x = np.array([ 0.8, 11., 12., 16., 32., 37.8, 44., 48., 56., 64., 88., 96.,
> 112., 128., 144., 176., 192. ])
> y = np.array([0.94597685600279, 0.95856916599601, 0.96009142950541,
> 0.96454515552826, 0.97938932735214, 0.98252400815195, 0.98500175787242,
> 0.98621192462708, 0.98816995007392, 0.98964101933472, 0.99247255046129,
> 0.99308203517541, 0.99406737810867, 0.99480702681278, 0.99538268958706,
> 0.99622916581118, 0.99653501465135])
>
> popt, pcov = curve_fit(func, x, y)
> popt
>
> Out[]: array([ 164.57396829  206.83406927    0.98251156])
> ========================================

The initial parameters often matter a lot, particularly when
exponentials are involved. The default is just (1, 1, 1). If you start
with a negative initial value for `a`, then you will converge to the
right answer better. Try this:

  popt, pcov = curve_fit(func, x, y, [-1, 1, 1])

> I then found this page: wolfram and quickly
>
> ========================================
> def lsq_exp(x, y):
> #   return A and B in y=A*exp(B*x)

That's missing the constant term, so it's not even the same model.
That's why it isn't giving you an answer that makes sense for your
data.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
  -- Umberto Eco



More information about the SciPy-User mailing list