[SciPy-User] leastsq error

Kevin Gullikson kevin.gullikson.signup at gmail.com
Mon Oct 29 09:48:29 EDT 2012


Lucas,

Your x and y arrays are normal python lists, but you are basically assuming
they are numpy arrays in your functions. They do not work like that (see
below)

In [3]: a = [1,2]

In [4]: 2*a
Out[4]: [1, 2, 1, 2]

In [5]: import numpy

In [6]: 2*numpy.array(a)
Out[6]: array([2, 4])

So if you just make your x and y into numpy arrays, I think it will work.


On Sun, Oct 28, 2012 at 8:02 PM, stephen lukacs <sjlukacs at gmail.com> wrote:

> hello one and all,
>
> i am having a terrible time with optimize.leastsq, even fitting a line, so
> please help.  here is my python code and error
>
> >>> import numpy
> >>> from scipy import optimize
> >>> def expr_conductance(x, a, b, c):
> ...     return a*0 + b*x + c
> ...
> >>> def residual_conductance(p,x,y):
> ...     a, b, c = p
> ...     return y - expr_conductance(x, a, b, c)
> ...
> >>> x = [0.99771057137610752, 0.49976145827781415, 0.24821831884394957,
> 0.12480215949109599, 0.06315070141095365, 0.03065779901355976,
> 0.015669312142317458, 0.0078799613766362755, 0.0039027338918740067]
> >>> len(x)
> 9
> >>> y = [2.9954211427522148, 1.9995229165556283, 1.496436637687899,
> 1.2496043189821919, 1.1263014028219074, 1.0613155980271196,
> 1.031338624284635, 1.0157599227532725, 1.007805467783748]
> >>> len(y)
> 9
> >>> [a, b, c], conv = optimize.leastsq(residual_conductance,
> [0,10000.,5.], args = (x,y))
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>   File "/usr/lib/python2.6/site-packages/scipy/optimize/minpack.py", line
> 276, in leastsq
>     m = _check_func('leastsq', 'func', func, x0, args, n)[0]
>   File "/usr/lib/python2.6/site-packages/scipy/optimize/minpack.py", line
> 13, in _check_func
>     res = atleast_1d(thefunc(*((x0[:numinputs],) + args)))
>   File "<stdin>", line 3, in residual_conductance
> ValueError: operands could not be broadcast together with shapes (9)
> (90000)
> >>>
>
>  i have tried many permutations and looked all over for syntax, but i can
> not find why this error is there or how to deal with it.  i have scipy
> 0.10.1 and numpy 1.6.1 under python 2.6.6 on a centos 6.3 system.
>  ultimately i want to put make the fit function
> a*numpy.power(x,(3/2))+b*x+c, which is a bit nonlinear but at this point i
> can't even get a line to fit.
>
> thank you in advance and have a great day.  lucas
>
> _______________________________________________
> SciPy-User mailing list
> SciPy-User at scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.scipy.org/pipermail/scipy-user/attachments/20121029/d194a420/attachment.html>


More information about the SciPy-User mailing list