编程语言
首页 > 编程语言> > python – 从PuLP迁移到Scipy

python – 从PuLP迁移到Scipy

作者:互联网

我使用PuLP来解决一些最小化问题
有约束,超级和低限.
它非常简单干净.

但我只需要使用Scipy和Numpy
模块.

我在读:
http://docs.scipy.org/doc/scipy/reference/tutorial/optimize.html

Constrained minimization of multivariate scalar functions

但是我有点失落……一些好的灵魂可以发布一个小例子
这个PuLP在Scipy中有一个?

提前致谢.
MM

from pulp import *

'''
Minimize        1.800A + 0.433B + 0.180C
Constraint      1A + 1B + 1C = 100
Constraint      0.480A + 0.080B + 0.020C >= 24
Constraint      0.744A + 0.800B + 0.142C >= 76
Constraint                            1C <= 2
'''

...

解决方法:

考虑以下:

import numpy as np
import scipy.optimize as opt

#Some variables
cost = np.array([1.800, 0.433, 0.180])
p = np.array([0.480, 0.080, 0.020])
e = np.array([0.744, 0.800, 0.142])

#Our function
fun = lambda x: np.sum(x*cost)

#Our conditions
cond = ({'type': 'eq', 'fun': lambda x: np.sum(x) - 100},
        {'type': 'ineq', 'fun': lambda x: np.sum(p*x) - 24},
        {'type': 'ineq', 'fun': lambda x: np.sum(e*x) - 76},
        {'type': 'ineq', 'fun': lambda x: -1*x[2] + 2})


bnds = ((0,100),(0,100),(0,100))
guess = [20,30,50]
opt.minimize(fun, guess, method='SLSQP', bounds=bnds, constraints = cond)

应该注意的是,eq条件应该等于零,而ineq函数将对任何大于零的值返回true.

我们获得:

  status: 0
 success: True
    njev: 4
    nfev: 21
     fun: 97.884100000000345
       x: array([ 40.3,  57.7,   2. ])
 message: 'Optimization terminated successfully.'
     jac: array([ 1.80000019,  0.43300056,  0.18000031,  0.        ])
     nit: 4

仔细检查平等:

output = np.array([ 40.3,  57.7,   2. ])

np.sum(output) == 100
True
round(np.sum(p*output),8) >= 24
True
round(np.sum(e*output),8) >= 76
True

舍入来自双点精度误差:

np.sum(p*output)
23.999999999999996

标签:python,numpy,scipy,pulp
来源: https://codeday.me/bug/20190624/1281649.html