[SciPy-user] number of function evaluation for leastsq

Michael McNeil Forbes mforbes at physics.ubc.ca
Tue Apr 15 16:12:15 EDT 2008


On 15 Apr 2008, at 11:47 AM, dmitrey wrote:
> You could try using leastsq from scikits.openopt, it has mechanism for
> preventing double-call objective function with same x value as before.
>
> Regards, D.
>
> 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 that behaviour is not described and I would eagerly  
>> demand
>> to avoid the superficial calls to the function.
>>
>> Yours, Achim

In principle, you could also just roll your own memoization to cache  
the results (assuming that you can afford to store them, but since it  
takes 1.5 hours per call, you can't have to many calls!):

def memoize(f):
   def memoized_f(x,_cache={}):
     key = tuple(numpy.ravel(x)) # Numpy arrays are not valid keys...
     if not _cache.has_key(key):
       _cache[key] = f(x)
     return _cache[key]
   return memoized_f

Now you can decorate your expensive function, and it will not compute  
values for the same input.

@memoize
def expensive_function(x):
    print "Computing %s**2..."%str(x)
    return x*x

 >>> expensive_function(1.01)
Computing 1.010000**2...
1.0201
 >>> expensive_function(1.01)
1.0201
 >>> expensive_function(array([1,2,3]))
 >>> expensive_function(array([1,2,3]))
Computing [1 2 3]**2...
array([1, 4, 9])
 >>> expensive_function(array([1,2,3]))
array([1, 4, 9])

Michael.




More information about the SciPy-User mailing list