如何解决使用 Scipy 通过两个限制最大化优化
我正在尝试解决具有两个约束的线性规划函数。 基本上,我需要在限制产能和预算的情况下实现利润最大化。
import numpy as np
from scipy.optimize import minimize
"""
maximize g1*g1_profit + g2*g2_profit (or minimize -...)
st (g1*g1_price + g2*g2_price) <= budget
(g1*g1_size + g2*g2_size) <= total_size
"""
budget = 10000
total_size = 50
g1_price = 300
g2_price = 600
g1_size = 2
g2_size = 1
g1_profit = 1200
g2_profit = 1000
def objective(x):
global g1,g2
g1 = x[0]
g2 = x[1]
return g1*g1_profit + g2*g2_profit
def constraint1(x):
return -(g1*g1_price + g2*g2_price) + budget
def constraint2(x):
return -(g1*g1_size + g2*g2_size) + total_size
x0 = [1,1]
print(-objective(x0))
cons1 = {'type': 'ineq','fun': constraint1}
cons2 = {'type': 'ineq','fun': constraint2}
cons = (cons1,cons2)
sol = minimize(objective,x0,method='SLSQP',constraints=cons)
print(sol)
我得到了这个结果:
print(sol)
fun: -1.334563245874159e+38
jac: array([1200.00002082,1000.0000038 ])
message: 'Singular matrix E in LSQ subproblem'
nfev: 144
nit: 48
njev: 48
status: 5
success: False
x: array([-6.56335026e+34,-5.46961214e+34])
所以成功是False,结果是错误的。 我确实阅读了优化帮助页面,并在网上查看了一些示例,但找不到任何解决方案。 提前致谢。
解决方法
首先,请尽可能避免使用全局变量。您可以轻松地将函数重写为:
def objective(x):
g1,g2 = x
return g1*g1_profit + g2*g2_profit
def constraint1(x):
g1,g2 = x
return -(g1*g1_price + g2*g2_price) + budget
def constraint2(x):
g1,g2 = x
return -(g1*g1_size + g2*g2_size) + total_size
然后,您需要将目标乘以 -1.0,以便将最大化问题转化为最小化问题:
minimize(lambda x: -1.0*objective(x),x0,method='SLSQP',constraints=cons)
这给了我
fun: -32222.222047310468
jac: array([-1200.,-1000.])
message: 'Optimization terminated successfully'
nfev: 6
nit: 6
njev: 2
status: 0
success: True
x: array([22.22222214,5.55555548])
因此,最优目标函数值为 32222。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。