Hello Group,
I just wanted to use sage for least-square fitting, and
couldn't find a useful function to do so. So I just
wrote one, using the least square fitting algorithm of
scipy.
Is there a better method to do so? If not, someone could
add the following code to some appropriate place so
everyone can use it:
================ snip ==================
import numpy
import scipy.optimize
def fit(function, parameters, y, x=None):
""" fit function to x varying parameters
Perform a least-squares fit of the function by varying
the parameters (given as a dictionary of start values)
to the value pairs x, y. x is range(len(y)) by default.
Return a tuple of the optimized parameter dictionary
and a function with these parameters applied.
EXAMPLES::
sage: a, b, c, x = var("a b c x")
sage: fit(a * x ** 2 + b * x + c, {a: 1, b: 1, c: 1}, [3, 2,
1, 2, 3])
"""
def f(params):
args = dict((str(keys[i]), params[i]) for i in range(len
(params)))
f = function(**args)
var = str(f.default_variable())
rr = array([f(**{var: float(xx)}) for xx in x], dtype=float)
return y - rr
if x is None:
x = numpy.arange(len(y))
y = array(y, dtype=float)
keys = parameters.keys()
p = [float(parameters[k]) for k in keys]
rr = f(p)
p, s = scipy.optimize.leastsq(f, p)
args = dict((str(keys[i]), p[i]) for i in range(len(p)))
r = dict((keys[i], p[i]) for i in range(len(p)))
return r, function(**args)
================ snip ==================
greetings
Martin Teichmann
--~--~---------~--~----~------------~-------~--~----~
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at http://groups.google.com/group/sage-devel
URLs: http://www.sagemath.org
-~----------~----~----~----~------~----~------~--~---