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

sax*_*ian 5 python scipy

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

from scipy.optimize import minimize

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

minimize(f, x0=1, method='COBYLA', bounds=(-2,2))
Run Code Online (Sandbox Code Playgroud)

收益:

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.'
Run Code Online (Sandbox Code Playgroud)

而不是预期2x.

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

小智 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
Run Code Online (Sandbox Code Playgroud)

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

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


And*_*son 5

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

在此处查看SciPy minimize接口的当前源代码,显然SciPy尚未采取任何措施来处理此限制。

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

(源代码摘录)

// 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)
Run Code Online (Sandbox Code Playgroud)