Scipy优化约束

时间:2019-03-15 17:21:51

标签: scipy

有人可以分享如何正确设置Scipy Optimize的约束吗?

这是用于将总和设置为>=100

 def constraint1(x):
        return (x[0]+x[1]-100)

您如何将其设置为=100<=100 我只是在文档或其他示例中没有看到这些情况。

当我尝试执行以下操作时,出现语法错误,但在其他示例中看到了该错误。

def constraint2(x):
    return (x[0]%=0)

这是完整的示例:

import numpy as np
from scipy.optimize import minimize
profit_0=50
profit_1=25

# initial guesses
n = 2
x0 = np.zeros(n)
x[0]=0
x[1]=0

def objective(x):
    return -1*(x[0]*profit_0 + x[1]*profit_1)

def constraint1(x):
    return (x[0]+x[1]-100)

def constraint2(x):
    return (x[0]%=0)

def constraint3(x):
    return (x[1]%=0)

b = (0,100)
bnds = (b, b)

con1 = {'type': 'ineq', 'fun': constraint1} 
con2 = {'type': 'eq', 'fun': constraint2} 
con3 = {'type': 'eq', 'fun': constraint3} 
cons = ([con1,con2,con3])

solution = minimize(objective,x0,method='SLSQP',bounds=bnds,constraints=cons)#constraints=cons
x=solution.x
print (solution)

1 个答案:

答案 0 :(得分:1)

我将更详细地解释@sascha的评论。 首先,让我们看一下不平等和平等约束之间的区别。 documentation说:

  

等式约束表示约束函数结果为零,而不等式表示约束函数结果为非负。

因此对于x [0] + x [1] <= 100的约束,您可以使用不等式约束并按如下所示定义约束函数:

def constraint(x):
    return 100 - x[0] - x[1]

如果满足条件,则为非负数。

对于x [0] + x [1] == 100的条件,您有两种可能性:

  1. 您可以使用两个不等式约束:
def constraint1(x):
  return 100 - x[0] - x[1]
def constraint2(x):
  return x[0] + x[1] - 100
con1 = {'type': 'ineq', 'fun': constraint1}
con2 = {'type': 'ineq', 'fun': constraint2}
  1. 您可以使用等式约束:
def constraint(x):
    return x[0] + x[1] - 100
con = {'type': 'eq', 'fun': constraint}

如果您觉得更直观,也可以考虑在约束函数中使用if语句:

def constraint(x):
    return 1 if x[0] + x[1] <= 100 else 0
con = {'type': 'ineq', 'fun':constraint}

关于约束2和3,请注意x[0]%=0x[0] = x[0]%0的缩写。这意味着,这是一项任务。尝试返回分配会给您带来语法错误。 此外,还应注意:未定义以零为模。例如5%0会给您一个错误。 (尽管对于numpy数组x x[0]%0似乎只给出警告并返回0。)

您能解释一下在这种约束下要实现的目标吗?

相关问题