How can I make scipy's fmin_cg
use one function that returns cost
and gradient
as a tuple? The problem with having f
for cost and fprime
for gradient, is that I might have to perform an operation twice (very costly) by which the grad
and cost
is calculated. Also, sharing the variables between them could be troublesome.
In Matlab however, fmin_cg
works with one function that returns cost and gradient as tuple. I don't see why scipy's fmin_cg
cannot provide such convenience.
Thanks in advance...
You can use
scipy.optimize.minimize
withjac=True
. If that's not an option for some reason, then you can look at how it handles this situation:This class wraps a function that returns function value and gradient, keeping a one-element cache and checks that to see if it already knows its result. Usage:
The strange thing about this code is that it assumes
f
is always called beforefprime
(but not everyf
call is followed by anfprime
call). I'm not sure ifscipy.optimize
actually guarantees that, but the code can be easily adapted to not make that assumption, though. Robust version of the above (untested):