Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scipy.optimize.fmin with 2 variables. How to make it work

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.

like image 918
user3218615 Avatar asked Nov 01 '22 06:11

user3218615


1 Answers

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])
like image 154
Fred Foo Avatar answered Nov 09 '22 15:11

Fred Foo