[英]Constraint with scipy
I have a problem of multi-objective optimization under constraint (maximization), in fact I transformed it into a mono-objective problem via the weighting technique and I added 2 variable x1, x2 (to optimize) with a constraint 0 <x1 + x2 <1
so their sum must be strictly less than 1 to give rise to the 3rd objective function as described in the code below.我有一个约束下的多目标优化问题(最大化),实际上我通过加权技术将其转换为单目标问题,并添加了 2 个变量 x1, x2(优化),约束0 <x1 + x2 <1
,因此它们的总和必须严格小于 1,才能产生第三个目标 function,如下面的代码中所述。
When I execute the sum is always greater than 1.当我执行时,总和总是大于 1。
for i in range(len(f1)):
def f(x):
x1= x[0]
x2= x[1]
return -(x1*f1[i]+ x2*f2[i]+ (1-x1-x2)*f3[i])
def constraint(x):
return x[0]+x[1]-1
b= (0.2, 0.8)
bnds= (b, b)
x0=[0.5,0.4]
cons= ({'type': 'ineq','fun':constraint})
res = minimize(f,x0, method= 'SLSQP', bounds=bnds, constraints=cons)
print('Vect_ponderation : ', res.x)
Output: Output:
Vect_ponderation : [0.8 0.8]
Vect_ponderation : [0.8 0.8]
Vect_ponderation : [0.8 0.8]
Vect_ponderation : [0.8 0.8]
The documentation says: 文档说:
Equality constraint means that the constraint function result is to be zero whereas inequality means that it is to be non-negative .等式约束意味着约束 function 结果为零,而不等式意味着它是非负的。 Note that COBYLA only supports inequality constraints.请注意,COBYLA 仅支持不等式约束。
def constraint(x):
return x[0] + x[1] -1
means:方法:
x0 + x1 - 1 >= 0 # non-negative
<->
x0 + x1 >= 1
which is respected in your solution.这在您的解决方案中受到尊重。
You probably want:你可能想要:
def constraint(x):
return - x[0] - x[1] + 1
Also keep in mind, that there is no concept of strict inequality .还要记住,没有严格不平等的概念。 You will need to introduce some epsilon constant a-priori like: eps = 1e-6
:您将需要先验引入一些epsilon常数,例如: eps = 1e-6
:
def constraint(x):
return - x[0] - x[1] + 1 - EPS
As I understand, your problem is that the output has x1+x2>1
.据我了解,您的问题是 output 具有x1+x2>1
。 I've checked optimize documentation and it says: 'inequality means that it is to be non-negative'.我检查了优化文档,它说:'不等式意味着它是非负的'。 Thus, you have requested something opposite to what you think you have requested.因此,您请求的内容与您认为自己请求的内容相反。
Suggestions:建议:
You have very simple function, so try providing jacobian as an additional parameter.您有非常简单的 function,因此请尝试提供 jacobian 作为附加参数。 The fit is much more efficient then.那时的合身效率要高得多。
Try to present minimal reproducible example .尝试呈现最小的可重现示例。 This makes answering much easier.这使得回答更容易。 Your question lacks f1
, f2
, and f3
definitions.您的问题缺少f1
、 f2
和f3
定义。
Try to ask a question.试着问一个问题。 I've found something that might be the problem you're trying to solve, but I'm not sure because there is no question (ie, sentence with question mark) in your question.我发现了一些可能是您要解决的问题,但我不确定,因为您的问题中没有问题(即带问号的句子)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.