简体   繁体   English

用SciPy解决约束最大化

[英]Solving constrained maximization with SciPy

Function to maximize: 功能最大化:

x[0] + x[1] + x[2]

Constraints: 约束:

0.2 * x[0] + 0.4 * x[1] - 0.33 * x[2] <= 25
5 * x[0] + 8.33 * x[2] <= 130
...
x[0] >= 0
x[1] >= 0
x[2] >= 0

My code looks like: 我的代码如下:

from numpy import *
from scipy.optimize import minimize


cons = ({'type': 'ineq', 'fun': lambda x:  array([25 - 0.2 * x[0] - 0.4 * x[1] - 0.33 * x[2]])},
        {'type': 'ineq', 'fun': lambda x:  array([130 - 5 * x[0] - 8.33 * x[2]])},
        {'type': 'ineq', 'fun': lambda x:  array([16 - 0.6 * x[1] - 0.33 * x[2]])},
        {'type': 'ineq', 'fun': lambda x:  array([7 - 0.2 * x[0] - 0.1 * x[1] - 0.33 * x[2]])},
        {'type': 'ineq', 'fun': lambda x:  array([14 - 0.5 * x[1]])},
        {'type': 'ineq', 'fun': lambda x:  array([x[0]])},
        {'type': 'ineq', 'fun': lambda x:  array([x[1]])},
        {'type': 'ineq', 'fun': lambda x:  array([x[2]])})


f = lambda x: -1 * (x[0] + x[1] + x[2])

res = minimize(f, [0, 0, 0], method='SLSQP', constraints=cons, options={'disp': True})

print(res)

Unfortunately, result I got is: 不幸的是,我得到的结果是:

Positive directional derivative for linesearch    (Exit mode 8)
            Current function value: -18240083542.4
            Iterations: 20
            Function evaluations: 180
            Gradient evaluations: 16
       x: array([  6.05846118e+09,   6.05846118e+09,   6.12316118e+09])
     jac: array([ 0.,  0.,  0.,  0.])
 message: 'Positive directional derivative for linesearch'
     fun: -18240083542.377449
  status: 8
    njev: 16
    nfev: 180
     nit: 20
 success: False

I can successfully solve this problem in Excel Solver, so I guess I do something wrong in Python. 我可以在Excel Solver中成功解决此问题,所以我想我在Python中做错了。

Bug in SciPy, code works under Python2, but refuses to work under Python3 SciPy中的错误,代码在Python2下工作,但是拒绝在Python3下工作

Issue on GitHub: https://github.com/scipy/scipy/issues/4240 在GitHub上发布: https : //github.com/scipy/scipy/issues/4240

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

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