Python Scipy optimize.minimize exits在约束不存在时成功地最小化退出';我不满意
我一直在使用scipy.optimize.minimize 当我定义一个不可能满足约束的问题时,注意到一些奇怪的行为。下面是一个例子:Python Scipy optimize.minimize exits在约束不存在时成功地最小化退出';我不满意,python,scipy,Python,Scipy,我一直在使用scipy.optimize.minimize 当我定义一个不可能满足约束的问题时,注意到一些奇怪的行为。下面是一个例子: from scipy import optimize # minimize f(x) = x^2 - 4x def f(x): return x**2 - 4*x def x_constraint(x, sign, value): return sign*(x - value) # subject to x >= 5 and x<
from scipy import optimize
# minimize f(x) = x^2 - 4x
def f(x):
return x**2 - 4*x
def x_constraint(x, sign, value):
return sign*(x - value)
# subject to x >= 5 and x<=0 (not possible)
constraints = []
constraints.append({'type': 'ineq', 'fun': x_constraint, 'args': [1, 5]})
constraints.append({'type': 'ineq', 'fun': x_constraint, 'args': [-1, 0]})
optimize.minimize(f, x0=3, constraints=constraints)
这个问题没有满足约束的解决方案,但是,minimize()使用初始条件作为最佳解决方案成功返回
这种行为是故意的吗?如果是这样,如果最优解决方案不满足约束条件,是否有办法强制失败?这似乎是一个错误。我在文章中添加了一条注释,其中包含您示例的变体 如果使用不同的方法,如COBYLA,函数将无法正确找到解决方案:
In [10]: optimize.minimize(f, x0=3, constraints=constraints, method='COBYLA')
Out[10]:
fun: -3.75
maxcv: 2.5
message: 'Did not converge to a solution satisfying the constraints. See `maxcv` for magnitude of violation.'
nfev: 7
status: 4
success: False
x: array(2.5)
In [10]: optimize.minimize(f, x0=3, constraints=constraints, method='COBYLA')
Out[10]:
fun: -3.75
maxcv: 2.5
message: 'Did not converge to a solution satisfying the constraints. See `maxcv` for magnitude of violation.'
nfev: 7
status: 4
success: False
x: array(2.5)