Steven T.
Steven T.

Reputation: 1

Maximize function with two parameters

I'm trying to find the values of two parameters called a e b that maximize a function f(x,a,b), with b>0. I wrote this:

a=0.1 #start value for a
b=150 #start value for b
n=len(x)
def f(y,a,b):
    c=sum([np.log(1-a/b*i) for i in y])
    return -n*np.log(b)+(1-a/a)*c
minimize(f,x,args=(a,b))

where x is an array with my data.

I get the following error:

RuntimeWarning: invalid value encountered in log
  c=sum([np.log(1-a/b*i) for i in x])
C:\Python27\lib\site-packages\numpy\core\_methods.py:26: RuntimeWarning: invalid value encountered in reduce
  return umr_maximum(a, axis, None, out, keepdims)
      fun: nan
 hess_inv: array([[1, 0, 0, ..., 0, 0, 0],
       [0, 1, 0, ..., 0, 0, 0],
       [0, 0, 1, ..., 0, 0, 0],
       ...,
       [0, 0, 0, ..., 1, 0, 0],
       [0, 0, 0, ..., 0, 1, 0],
       [0, 0, 0, ..., 0, 0, 1]])
      jac: array([nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan,
       nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan,
       nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan,
       nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan,
       nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan,
       nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan,
       nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan,
       nan, nan, nan, nan])
  message: 'Desired error not necessarily achieved due to precision loss.'
     nfev: 97
      nit: 0
     njev: 1
   status: 2
  success: False

Could someone help me?

Upvotes: 0

Views: 174

Answers (2)

newkid
newkid

Reputation: 1468

For this problem, since you are searching for optimal values of a, b your objective should be redefined as follows,

def f(x,y):
    a = x[0] # Parameter 1
    b = x[1] # Parameter 2
    c=sum([np.log(1-a/b*i) for i in y])
    return -n*np.log(b)+(1-a/a)*c
minimize(f,x,args=(y))

Next, you have to implement a check to ensure that np.log gets a value > 0.0 else you would get a domain error. You can compute the bounds of the value of a w.r.t b or the other way around and then specify bounds.

Upvotes: 1

Sharku
Sharku

Reputation: 1092

Try setting boundarys with the bounds property of minimize(). Probably your b gets negative at one point.

Upvotes: 0

Related Questions