简体   繁体   English

scipy.optimize.minimize返回不满足问题约束的解决方案。 为什么?

[英]scipy.optimize.minimize returns a solution that does not satisfied constraints of the problem. Why?

scipy.optimize.minimize produces solution that does not satisfy the constraints, but the report says that optimization terminated successfully. scipy.optimize.minimize产生的解决方案不满足约束条件,但是报告说优化成功终止。

The objective is (x[0] - 3)**2 + (x[1] - 2)**2 目标是(x [0]-3)** 2 +(x [1]-2)** 2

The constraint is x[0]+x[1]<=4 约束为x [0] + x [1] <= 4

The correct solution should be [2.5, 1.5] 正确的解决方案应该是[2.5,1.5]

The answer from the function is [3,2] 该函数的答案是[3,2]

I tried different optimization methods. 我尝试了不同的优化方法。 Tried no methods. 尝试没有方法。 Tried variations on the syntax. 尝试了语法的变体。

Here is the code (super simple, it seems): 这是代码(看起来很简单):

import numpy as np
from scipy import optimize

def f(x):
    return (x[0] - 3)**2 + (x[1] - 2)**2

def con(x):
    return sum(x)-4 

x0 = np.array([0, 0])
res=optimize.minimize(f, x0, method="SLSQP",constraints={"fun": con, "type": "ineq"}, options={'disp':True}) 
print(res)
print(sum(res.x)-4)

ineq is a >= 0 inequality. ineq是> = 0的不等式。 I assumed (based on the examples I have seen) that it is <=0 inequality. 我假设(基于我所看到的示例)它是<= 0不等式。 Indeed, the code below, after correcting for this misinterpretation, produces the correct answer. 的确,下面的代码在纠正了这种误解之后会产生正确的答案。

import numpy as np from scipy import optimize 从scipy导入优化中将numpy导入为np

def f(x): return (x[0] - 3)**2 + (x[1] - 2)**2 def f(x):返回(x [0]-3)** 2 +(x [1]-2)** 2

def con(x): return 4-sum(x) def con(x):返回4-sum(x)

x0 = np.array([0, 0]) res=optimize.minimize(f, x0, method="SLSQP",constraints={"fun": con, "type": "ineq"}, options={'disp':True}) print(res) print(sum(res.x)-4) x0 = np.array([0,0])res = optimize.minimize(f,x0,method =“ SLSQP”,constraints = {“ fun”:con,“ type”:“ ineq”},options = {' disp':True})print(res)print(sum(res.x)-4)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM