scipy 将边界转换为不等式约束不会得到正确答案

9gm1akwq  于 2022-11-10  发布在  其他
关注(0)|答案(1)|浏览(159)

我有一个一般形式的线性规划:
https://i.stack.imgur.com/Nqnei.png
我在玩scipy的linprog,在文档中他们提供了一个例子:
https://i.stack.imgur.com/4Y7Q8.png
它们提供代码:

c = [-1, 4]
G = [[-3, 1], [1, 2]]
h = [6, 4]
x0_bounds = (None, None)
x1_bounds = (-3, None)
from scipy.optimize import linprog
res = linprog(c, A_ub=A, b_ub=b, bounds=[x0_bounds, x1_bounds])

Linprog不能处理“大于”不等式约束,所以我们需要转换为“小于”不等式约束。注意,他们显式地输入了边界(不等式x1≥-3部分)。
我在想我可以把边界合并到一般的不等式矩阵G中。
我有这个功能:

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import linprog

def LP(c,d,G,h,A,b, method = 'revised simplex'):
  res = linprog(c, A_ub = G, b_ub = h, A_eq = A, b_eq = b, method = method)
  if res.success == True:
    print('The optimization was successful in', res.nit, 'iterations')
    print('The optimal solution is:', res.x)
    print('The objective function is equal to:', res.fun+d)
    return res.x
  if res.success == False:
    print('The optimization was not successful')
    if res.status == 1:
      print('Iteration limit reached')
    if res.status == 2:
      print('Problem appears to be infeasible')
    if res.status == 3:
      print('Problem appears to be unbounded')
    if res.status == 4:
      print('Numerical difficulties encountered')

参数为:

c = [-1,4]
d = 0
G = [[-3,1],[1,2],[0,-1]]
h = [6,4,3]
A = None
b = None

运行该程序,我得到了目标obj = -4的最优解x = [4.,0.]。然而,在文档中,他们说目标obj = -22的最优解是[10.,-3.]。两个解都在可行集中,因此他们的解显然更好。
有人知道为什么我得到的答案与文档中的答案不同吗?
文档链接:https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.linprog.html

64jmpszr

64jmpszr1#

引用文件:
请注意,默认情况下lb = 0且ub = None,除非指定了界限。
因此,您需要明确指定优化变量没有界限:

bounds = [(None, None), (None, None)]
res = linprog(c, A_ub = G, b_ub = h, A_eq = A, b_eq = b, bounds=bounds, method = method)

相关问题