使用方法“COBYLA”接受边界时,scipy的函数是否最小化?

时间:2012-10-08 12:20:13

标签: python scipy

我在scipy的'COBYLA'函数(v.0.11 build for cygwin)中使用了算法optimize.minimize。我观察到在这种情况下似乎不使用参数bounds。例如,简单的例子:

from scipy.optimize import minimize

def f(x):
    return -sum(x)

minimize(f, x0=1, method='COBYLA', bounds=(-2,2))

返回:

status: 2.0
nfev: 1000
maxcv: 0.0
success: False
fun: -1000.0
x: array(1000.0)
message: 'Maximum number of function evaluations has been exceeded.'

而不是2的预期x

有没有人察觉到同样的问题?是否存在已知错误或文档错误?在scipy 0.11文档中, COBYLA 算法不排除此选项。实际上,函数fmin_cobyla没有bounds参数。 谢谢你的任何提示。

2 个答案:

答案 0 :(得分:6)

您可以以约束的形式制定界限

import scipy
#function to minimize
def f(x):
    return -sum(x)
#initial values
initial_point=[1.,1.,1.]    
#lower and upper bound for variables
bounds=[ [-2,2],[-1,1],[-3,3]   ]

#construct the bounds in the form of constraints
cons = []
for factor in range(len(bounds)):
    lower, upper = bounds[factor]
    l = {'type': 'ineq',
         'fun': lambda x, lb=lower, i=factor: x[i] - lb}
    u = {'type': 'ineq',
         'fun': lambda x, ub=upper, i=factor: ub - x[i]}
    cons.append(l)
    cons.append(u)

#similarly aditional constrains can be added

#run optimization
res = scipy.optimize.minimize(f,initial_point,constraints=cons,method='COBYLA')
#print result
print res

请注意,最小化函数会将设计变量赋予函数。在这种情况下,给出3个输入变量,其中3个上限和下限。结果产生:

   fun: -6.0
   maxcv: -0.0
 message: 'Optimization terminated successfully.'
    nfev: 21
  status: 1
 success: True
       x: array([ 2.,  1.,  3.])

答案 1 :(得分:4)

原始 COBYLA(2) FORTRAN算法不显式支持变量边界,您必须在一般约束的上下文中制定边界。

查看 SciPy minimize界面here的当前源代码,很明显 SciPy 中尚未采取任何措施处理这个限制。

因此,为了在 SciPy minimize函数中为 cobyla 算法应用 bounds ,您需要制定变量绑定为不等式约束,并将它们包含在关联的约束参数中。

(源代码摘录)

// bounds set to anything else than None yields warning
if meth is 'cobyla' and bounds is not None:
    warn('Method %s cannot handle bounds.' % method,
         RuntimeWarning)
...
// No bounds argument in the internal call to the COBYLA function
elif meth == 'cobyla':
    return _minimize_cobyla(fun, x0, args, constraints, **options)
相关问题