我正在用 Python 设置一个新的线性优化代码。不幸的是,我对 Pulp、Scipy 和 Gekko 包没有相同的结果。
我试图用不同的包在 Python 中实现线性优化的代码。
使用 GEKKO 进行优化
from gekko import GEKKO
import numpy as np
import matplotlib.pyplot as plt
m = GEKKO() # create GEKKO model
x = m.Var(value=0, lb=0, ub=400000) # define new variable, initial value=0
y = m.Var(value=0, lb=0, ub=200) # define new variable, initial value=1
z = m.Var(value=0, lb=0)
m.Equation(x+y+z==100)
m.Obj(1.2*x + y + z) # equations
m.solve(disp=False) # solve
print("Solution with The GEKKO package")
print(x.value, y.value , z.value)# # print solution
使用 Scipy 进行优化
import numpy as np
from scipy.optimize import minimize
def objective(m):
x = m[0]
y = m[1]
z = m[2]
return 1.2*x + y + z
def constraint1(m):
return m[0] + m[1] + m[2] - 100
def constraint2(x):
return x[2]
x0 = [0,0,0]
b1 = (0,400000)
b2 = (0,200)
b3= (0,None)
bnds = (b1,b2,b3)
con1 = {'type' : 'eq', 'fun' : constraint1}
con2 = {'type' : 'ineq', 'fun' : constraint2}
cons = [con1,con2]
sol = minimize(objective,x0,method='SLSQP', bounds=bnds , constraints=cons)
print("Solution with The SCIPY package")
print(sol)
纸浆优化
from pulp import *
prob = LpProblem("Problem",LpMinimize)
x = LpVariable("X",0,400000,LpContinuous)
y = LpVariable("Y",0,200,LpContinuous)
z = LpVariable("Z",0,None,LpContinuous)
prob += 1.2*x + y + z
prob += (x + y + z == 100)
prob.solve()
print("Solution with The PULP package")
print("Status:", LpStatus[prob.status])
for v in prob.variables():
print(v.name, "=", v.varValue)
我希望得到相同的结果,但不幸的是实际输出不同:
GEKKO 软件包的解决方案
[0.0] [36.210291349] [63.789708661]
SCIPY 软件包的解决方案
fun: 100.0000000000001
jac: array([1.19999981, 1. , 1. ])
message: 'Optimization terminated successfully.'
nfev: 35
nit: 7
njev: 7
status: 0
success: True
x: array([4.88498131e-13, 5.00000000e+01, 5.00000000e+01])
纸浆包的解决方案
X = 0.0
Y = 100.0
Z = 0.0