[SciPy-user] Estimation of parameters while fitting data
Pauli Virtanen
pav@iki...
Wed Apr 2 16:31:28 CDT 2008
Wed, 02 Apr 2008 11:22:34 +0200, Doreen Mbabazi wrote:
> What you proposed has worked and I have been able to get the values that
> I want to use to obtain the residuals however when it comes to using the
> leastsq, I get an error which I have tried to google but its giving me
> no useful results. Below is the code and the error.
I think you should try to construct your program piece-by-piece, testing
each part one-by-one (eg. printing/displaying some intermediate results
to see whether they are correct), ie.
1. Does the function f(y,t,p) function as expected?
2. Does the function S(t, p) function as expected?
3. Does the function residuals(p, y, t) function as expected?
4. Does the whole shebang work?
I think in this case you would have noticed problems in phases 2 and 3
even before 4.
[clip]
> def S(t, p):
> y_list = []
> ys = odeint(f, initial_y, t, args =(p,))
> for i in range(len(t)):
> y_V = ys[i][2]
> y_list.append(y_V)
> return y_list
I'm not sure whether the indentation was messed up in the mail, but if
the code reads like this, it probably won't work (y_list will always
contain only a single value).
Anyway, you'll likely be better off using indexing instead of
constructing a list:
def S(t, p):
ys = odeint(f, initial_y, t, args =(p,))
return ys[:,2]
> y = odeint(f,initial_y,t,args=(p,))
> #print S(t,p)
>
> def residuals(p,y,t):
> return [V - S(t,p) for i in xrange(len(t))]
Also this looks a bit funny: you create a list of len(t) elements that
are all the same. Also, each element is an 1-d array containing the
values V[:] - S(t[0],p).
Anyway, you probably meant (no need to use the loop, subtraction is
defined also for arrays):
def residuals(p, y, t):
return V - S(t,p)
In general, if you find yourself writing xrange(len(z)) in numpy code,
this often indicates that you should think a second time what you are
trying to do: there may be an easier and more efficient way.
> pbest = leastsq(residuals, p, args=(V,t))
>
> The error
> ValueError: setting an array element with a sequence.
> Traceback (most recent call last):
> File "essay6.py", line 44, in <module>
> pbest = leastsq(residuals, p, args=(V,t))
> File "/usr/lib/python2.5/site-packages/scipy/optimize/minpack.py",
> line 266, in leastsq
> retval =
> _minpack._lmdif
(func,x0,args,full_output,ftol,xtol,gtol,maxfev,epsfcn,factor,diag)
> minpack.error: Result from function call is not a proper array of
> floats.
I think this says that the 'residuals' function didn't return an array (1-
d?) of floats, which it indeed doesn't appear to do.
--
Pauli Virtanen
More information about the SciPy-user
mailing list