通过两个参数最大化功能

时间:2019-01-18 15:18:22

标签: python python-2.7 scipy minimize

我正在尝试找到两个参数的值,这些参数称为 a e b ,它们使函数f(x,a,b)最大化,且b> 0。 我是这样写的:

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))

其中x是包含我的数据的数组。

我收到以下错误:

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

有人可以帮我吗?

2 个答案:

答案 0 :(得分:0)

尝试使用minimize()<iframe src="https://www.facebook.com/plugins/video.php?href=https%3A%2F%2Fwww.facebook.com%2FPretty52Official%2Fvideos%2Fvb.217293018312810%2F468824230316244%2F&width=500&show_text=false&appId=115391488481724&height=500" width="500" height="500" style="border:none;overflow:hidden" scrolling="no" frameborder="0" allowTransparency="true" allow="encrypted-media" allowFullScreen="true"></iframe> 属性设置边界。可能您的b在某一点变负。

答案 1 :(得分:0)

对于这个问题,由于要搜索a的最佳值,b的目标应重新定义如下,

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))

接下来,您必须执行检查以确保np.log得到value > 0.0,否则会得到域错误。您可以计算a w.r.t b的范围,或者反之,然后指定bounds