Strange Result With Python's (scipy) Curve Fitting
Solution 1:
It works if you change the values in xlist
to a numpy array:
In [38]: popt, pcov = curve_fit(func, array(xlist, dtype=float), ylist)
In [39]: popt
Out[39]: array([ 7.83722896e-03, -3.94023294e-05])
At first this looks like a bug, but what's happening is that the underlying code takes the argument xdata
and passes it unchanged to your function. In your example, this means in the expression a + b*x
, x
is a Python list. That means that b*x
is not doing the calculation that you want.
So to make your definition of func
work, the argument xdata
must be a numpy array. Or, you could define func
this way:
def func(x, a, b):
return a + b*np.asarray(x)
Solution 2:
The default initial parameters for scipy's curve fitting routine are all 1.0, if I recall correctly. While this works well for simple cases such as straight lines - since error space is simpler for straight line curve fitting -if you try to fit where error space is "bumpy and uneven" you will likely again see differences between your results and those of zunzun.com.
If you have some idea of the correct values (or range of values) where the optimum solution should exist, starting the scipy routine with such values will in almost all cases give better results than starting with all ones.
While zunzun.com allows entry of initial parameter "estimates" - or guesses - these are not required by the web site as a genetic algorithm is used to determine initial parameter estimates. The BSD-licensed Python fitting source code for the zunzun.com web site is at
http://code.google.com/p/pyeq2/
and it comes with a very wide range of examples. Look at the bottom of the zunzun.com web pages for links to the code as well. Let me know if you have any questions and I will be glad to help.
James Phillips zunzun@zunzun.com
Post a Comment for "Strange Result With Python's (scipy) Curve Fitting"