[SciPy-user] number of function evaluation for leastsq
Pauli Virtanen
pav at iki.fi
Tue Apr 15 16:26:23 EDT 2008
Tue, 15 Apr 2008 20:15:33 +0200, Achim Gaedke wrote:
> Hello!
>
> I use scipy.optimize.leastsq to adopt paramters of a model to measured
> data. Each evaluation of that model costs 1.5 h of computation time.
> Unfortunately I can not specify a gradient function.
[clip]
> Unfortunately that behaviour is not described and I would eagerly demand
> to avoid the superficial calls to the function.
As a workaround, you can memoize the function calls, something like this:
---- clip ----
import scipy as sp
def memoize_single(func):
"""Optimize out repeated function calls with the same arguments"""
last_z = []
last_f = None
def wrapper(z, *a, **kw):
if sp.all(z == last_z):
return last_f.copy()
last_z = sp.array(z, copy=True)
last_f = sp.array(func(z, *a, **kw), copy=True)
return last_f.copy()
return wrapper
@memoize_single
def target_function(z):
print "Evaluating..."
z = sp.asarray(z)
return sum(z**2)
for k in xrange(10):
target_function([1,2,3])
---- clip ----
Is should output
---- clip ----
Evaluating...
14
14
14
14
14
14
14
14
14
14
---- clip ----
--
Pauli Virtanen
More information about the SciPy-User
mailing list