python - Scipy optimize.minimize 在不满足约束时成功退出

标签 python scipy

我一直在使用 scipy.optimize.minimize (docs)

当我定义一个不可能满足约束的问题时,我注意到了一些奇怪的行为。这是一个例子:

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)

结果输出:

fun: -3.0
     jac: array([ 2.])
 message: 'Optimization terminated successfully.'
    nfev: 3
     nit: 5
    njev: 1
  status: 0
 success: True
       x: array([ 3.])

此问题没有满足约束的解,但是,minimize() 成功返回,使用初始条件作为最优解。

这种行为是故意的吗?如果是这样,如果最优解不满足约束,是否有办法强制失败?

最佳答案

这似乎是一个错误。我在 issue on github 中添加了一 strip 有您示例变体的评论.

如果您使用不同的方法,例如 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)

关于python - Scipy optimize.minimize 在不满足约束时成功退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51110277/

相关文章:

Python:折线周围的坐标框

python - 在Python中求解具有时间相关系数的常微分方程(odeint)

python - Django csrf token 的作用是什么?

python - 如何使用 if 语句使 for 循环遍历字符串中的每个项目?

python - Tkinter 按钮使用网格扩展

python - 具有时变截止频率的低通滤波器,使用 Python

python - 使用 scipy.stats.multivariate_normal.pdf 时出现错误 :operands could not be broadcast together with shapes (1, 8) (21,)

python - 如何使用 scipy.ndimage.interpolation.affine_transform 围绕其中心旋转图像?

java - 从 jar 文件运行 python 脚本

python - 按字典值过滤数据框,但有时包括值,有时排除它们