scipy 的最小化功能是否使用方法“COBYLA"?接受界限? [英] Does scipy's minimize function with method "COBYLA" accept bounds?
问题描述
我在 scipy 的 optimize.minimize
函数(针对 cygwin 的 v.0.11 版本)中使用算法 'COBYLA'
.我观察到在这种情况下似乎没有使用参数 bounds
.举个简单的例子:
I'm using the algorithm 'COBYLA'
in scipy's optimize.minimize
function (v.0.11 build for cygwin). I observed that the parameter bounds
seems not to be used in this case. For instance, the simple example:
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.'
而不是 x
的预期 2
.
有没有人发现同样的问题?是否存在已知错误或文档错误?在 scipy 0.11 文档中,COBYLA 算法不排除此选项.事实上,函数 fmin_cobyla
没有 bounds
参数.感谢您的任何提示.
Did anyone perceived the same problem? Is there a known bug or documentation error? In the scipy 0.11 documentation, this option is not excluded for the COBYLA algorithm. In fact the function fmin_cobyla
doesn't have the bounds
parameter.
Thanks for any hint.
推荐答案
你可以用约束的形式来制定边界
You can formulate the bounds in the form of constraints
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 个上限和下限.结果产生:
Note that the minimize function will give the design variables to the function. In this case 3 input variables are given with 3 upper and lower bounds. the result yields:
fun: -6.0
maxcv: -0.0
message: 'Optimization terminated successfully.'
nfev: 21
status: 1
success: True
x: array([ 2., 1., 3.])
这篇关于scipy 的最小化功能是否使用方法“COBYLA"?接受界限?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!