I have no problems making scipy.optimize.fmin work for functions with one variable, but somehow I'm not able to figure out how to make it work for 2 variables. Below is a simple example of a function I have tried (and failed) to maximize. What am I doing wrong?
from scipy.optimize import fmin
test2 = lambda x,y: x-x**2 + y - y**2
guess = [ 0.5,0.5 ] #just some guess
print fmin( -test2, guess, args=(x,y) )
Error message:
print fmin( -test2, guess, args=(x,y) )
TypeError: bad operand type for unary -: 'function'
UPDATE: Thank you for answering! Ended up with the following that also worked:
Thank you, that worked. Ended up with the following code which also worked:
from scipy.optimize import fmin
test2 = lambda x: -(x[0]-x[0]**2 + x[1] - x[1]**2 )
guess = [ 0.5,0.5 ] #just some guess
print fmin( test2, guess )
Optimization terminated successfully.
Current function value: -0.500000
Iterations: 18
Function evaluations: 37
[ 0.5 0.5]
As you might have guessed, I'm still learning the basics, and don't always find the error messages that obvious.
The error message is pretty explicit: you can't negate a function. Move the negation inside the function definition. At the same time, you should change the function so that it works on a single argument, a NumPy array:
>>> def test2(x):
... return -np.sum(x - x**2)
...
>>> test2(np.array([.5, .5]))
-0.5
Then minimize it without the args
:
>>> fmin(test2, np.array([.5, .5]))
Optimization terminated successfully.
Current function value: -0.500000
Iterations: 18
Function evaluations: 37
array([ 0.5, 0.5])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With