Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Solving a bounded non-linear minimization with scipy in python

Trying to solve a simple non linear minimization problem with one variable.

from scipy.optimize import minimize
import math

alpha = 0.05
waiting = 50
mean_period = 50
neighborhood_size = 5

def my_func(w):
    return -(2/(w+1) + alpha*math.floor(waiting/mean_period))*(1-(2/(w+1) + alpha*math.floor(waiting/mean_period)))**(neighborhood_size-1)

print minimize(my_func, mean_period, bounds=(2,200))

which gives me

ValueError: length of x0 != length of bounds

Do I input it wrong? How should I format it?

And if I remove the bounds, I get:

status: 2
  success: False
     njev: 19
     nfev: 69
 hess_inv: array([[1]])
      fun: array([-0.04072531])
        x: array([50])
  message: 'Desired error not necessarily achieved due to precision loss.'
      jac: array([-1386838.30676792])

The function looks like that and therefore I need the bounds to limit the solution in the local maximum that I am interested in.

like image 559
George Avatar asked Aug 12 '14 16:08

George


1 Answers

It should be:

print minimize(my_func, mean_period, bounds=((2,200),))

  status: 0
 success: True
    nfev: 57
     fun: array([-0.08191999])
       x: array([ 12.34003932])
 message: 'CONVERGENCE: NORM_OF_PROJECTED_GRADIENT_<=_PGTOL'
     jac: array([  2.17187379e-06])
     nit: 4

For each parameter you have to provide a bound, therefore here we need to pass a tuple, which contains only one tuple (2,200), to minimize().

like image 121
CT Zhu Avatar answered Sep 22 '22 10:09

CT Zhu