使用Scipy最大化优化

时间:2017-04-30 02:31:56

标签: python scipy

我正在尝试使用下面显示的约束解决此线性编程函数,x1x2的答案应分别为26,并且目标函数的值应等于36。我写的代码为我提供了答案43。我可能做错了什么?最大化z=3*x1 + 5*x2的功能。约束是x1 <= 4; 2*x2 <=12; 3*x1 + 2*x2 <= 18; x1>=0; x2>=0

import numpy as np
from scipy.optimize import minimize
def objective(x, sign=1.0):
    x1 = x[0]
    x2 = x[1]
    return sign*((3*x1) + (5*x2))
def constraint1(x, sign=1.0):
    return sign*(3*x[0] +2*x[1]- 18.0)
x0=[0,0]

b1 = (0,4)
b2 = (0,12)
bnds= (b1,b2)
con1 = {'type': 'ineq', 'fun': constraint1}

cons = [con1]
sol = minimize (objective,x0,method='SLSQP',bounds=bnds,constraints=cons)

print(sol)

2 个答案:

答案 0 :(得分:8)

您的代码存在以下问题:

  • 您将objective传递给minimize的方式会导致最小化而不是目标的最大化。如果您想最大化 objective minimize,则应将sign参数设置为-1。请参阅scipy documentation中的最大化示例。
  • minimize假设约束函数返回的值大于而不是零。因此,编写约束的方式意味着3*x1 + 2*x2 - 18.0 >=0,而实际约束使用<=
  • b2的上限与约束2*x2 <= 12隐含的界限不对应。

答案 1 :(得分:1)

如果有人想要工作代码,请在下面。我还添加了cvx。解决方案是x:array([2。,6。])

def objective(x, sign=-1.0):
    x1 = x[0]
    x2 = x[1]
    return sign*(3*x1 + 5*x2)

def constraint1(x):
    return 18.0 - 3*x[0] -2*x[1]

x0 = [0,0]

b1 = (0,4)
b2 = (0,6)
bnds= (b1,b2)
con1 = {'type': 'ineq', 'fun': constraint1}
cons = [con1]
sol = minimize(objective, x0, method='SLSQP', bounds = bnds, constraints = cons)

print(sol)

CVXPY

 # Create two scalar optimization variables (CVXPY Variable)
 x1 = cp.Variable()
 x2 = cp.Variable()
 # Create two constraints (Python list)
 constraints = [3*x1 + 2*x2 <= 18, x1 >= 0, x2 >= 0, x1 <=4, x2 <= 6]
 # Form objective
 obj = cp.Maximize(3*x1 + 5*x2)
 # Form and solve problem
 prob = cp.Problem(obj, constraints)
 prob.solve() # Returns the optimal value.
 print("status:", prob.status)
 print("optimal value", np.round(prob.value, 5))
 print("optimal var", np.round(x1.value, 5), np.round(x2.value, 5))