[SciPy-User] Problems with optimize.leastsq and curve_fit

Paul Hobson pmhobson@gmail....
Tue Mar 19 14:47:02 CDT 2013


I guess I don't quite understand how to use the functions properly since
they're not returning meaningful results on what should be a pretty trivial
linear fit. My initial thought is that they're being tripped up by my `x`
variable not being uniformly spaced.

Consider the following (overly) simplified example:

## start
import numpy as np
import scipy.optimize as opt
x = np.array([  0. ,   0.5,   1. ,   2. ,   3. ,   3.5,   5. ,   5.5,   6. ,
                6.5,   7. ,   7.5,   8. ,   8.5,   9. ,   9.5,  10. ,  11. ,
               11.5,  12.5], dtype=np.float32)

y = np.array([  2.7,   8.6,   9.  ,  13.8,  16.8,  17.8,  23.24,  25.2,
               26.3,  27.1,  27.68,  30.7,    32.9,  32.9,  37.07,  39.5,
               40.5,  45.7,  46.76,  50.2], dtype=np.float32)

def lsq_line(params, x, y):
    return y - (params[0]*x + params[1])

def cf_line(x, m, b):
    return m*x + b

np.polyfit(x, y, 1)  # works great
# Out[6]: array([ 3.54965901,  5.09342384], dtype=float32)

opt.leastsq(lsq_line, [3,5], args=(x,y))  # bad
# Out[9]: (array([ 3.,  5.]), 4)

opt.curve_fit(cf_line, x, y, p0=[3,5]) # bad
# Out[10]: (array([ 3.,  5.]), inf)
## stop

Any thoughts or advice on how to better use these functions would be much
appreciated.

Thanks,
-p
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/scipy-user/attachments/20130319/906c2b16/attachment.html 


More information about the SciPy-User mailing list