[SciPy-User] optimize.leastsq - Value Error: The truth value of an array with more than one element is ambiguous

josef.pktd at gmail.com josef.pktd at gmail.com
Sat May 15 07:02:40 EDT 2010


On Sat, May 15, 2010 at 5:25 AM, Zhe Wang <3njoywind at gmail.com> wrote:
> Traceback (most recent call last):
>   File "D:\Yt.py", line 31, in <module>
>     r = leastsq(residuals, [1,0], args=(Y,T), maxfev=10000000)
>   File "D:\Python26\lib\site-packages\scipy\optimize\minpack.py", line 266,
> in leastsq
>     m = check_func(func,x0,args,n)[0]
>   File "D:\Python26\lib\site-packages\scipy\optimize\minpack.py", line 12,
> in check_func
>     res = atleast_1d(thefunc(*((x0[:numinputs],)+args)))
>   File "D:\Yt.py", line 26, in residuals
>     return y - Yt(x, p)
>   File "D:\Yt.py", line 20, in Yt
>     for i in range(0, Et(x)):
>   File "D:\Yt.py", line 11, in Et
>     if t == 1995:
> ValueError: The truth value of an array with more than one element is
> ambiguous. Use a.any() or a.all()
> ---------------------------------------------------------------------------------------------------------
>
> When running the following code:
>
> --------------------------------------------------------------------------------------------
>
> from scipy.optimize import leastsq
> import numpy as np
>
> def Iv(t):
>     if t == 1995:
>         return t + 2
>     else:
>         return t
>
> def Et(t):
>     if t == 1995:
>         return t + 2
>     else:
>         return t
>
> def Yt(x, p):
>     a, pa = p
>     sum = 0
>
>     for i in range(0, Et(x)):
>         v = x - et + i
>         sum += a*(1+p)**(v)*Iv(v)
>     return sum
>
> def residuals(p, y, x):
>     return y - Yt(x, p)
>
> T = np.array([1995,1996,1997,1998,1999])
> Y =
> np.array([639300.36866,664872.383407,691467.278743,719125.969893,747891.008688])
>
> r = leastsq(residuals, [1,0], args=(Y,T), maxfev=10000000)
> A, Pa = r[0]
> print "A=",A,"Pa=",Pa
>
> ----------------------------------------------------------------------------------------------
>
> I know the error occurs when I compare t like: "if t == 1995",but I have no
> idea how to handle it correctly.

try the vectorized version of a conditional assignment, e.g.
np.where(t == 1995, t, t+2)

I didn't read enough of your example, to tell whether your Yt loop can
be vectorized with a single sum, but I guess so.

optimize leastsq expects an array, so residuals (and Yt) need to
return an array not a single value, maybe np.cusum and conditional or
data dependent slicing/indexing works

Josef


>
> Any help would be greatly appreciated.
>
> Zhe Wang
>
> _______________________________________________
> SciPy-User mailing list
> SciPy-User at scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user
>
>



More information about the SciPy-User mailing list