【问题标题】:Python - The integer linear programming (ILP) function in CVXOPT is not generating correct resultsPython - CVXOPT 中的整数线性规划 (ILP) 函数未生成正确的结果
【发布时间】:2015-11-18 16:33:01
【问题描述】:

我正在尝试使用 Python 2.7 上的 CVXOPT 库解决https://en.wikipedia.org/wiki/Integer_programming#Example 中的简单示例;最佳答案是 (1,2) 或 (2,2)。我得到(0.0,0.0)。我在下面的代码中做错了什么?谢谢!

import numpy as np
import cvxopt
from cvxopt import glpk

c=cvxopt.matrix([0,-1]) #-1 since we're maximising the 2nd variable
G=cvxopt.matrix([[-1,1],[3,2],[2,3],[-1,0],[0,-1]],tc='d')
h=cvxopt.matrix([1,12,12,0,0],tc='d')
(status, x)=glpk.ilp(c,G.T,h,B=set([0,1]))
print status
print x[0],x[1]    #should be (1,2) or (2,2)
print sum(c.T*x)

【问题讨论】:

    标签: python-2.7 optimization binary integer-programming


    【解决方案1】:

    您的代码基本正确,但需要做两处小修改:

    1. c 向量也必须是双精度的。
    2. 变量 x[0] 和 x[1] 应该是整数,而不是二进制。

    然后,一个可行的解决方案是:

    import numpy as np
    import cvxopt
    
    c=cvxopt.matrix([0,-1],tc='d')
    G=cvxopt.matrix([[-1,1],[3,2],[2,3],[-1,0],[0,-1]],tc='d')
    h=cvxopt.matrix([1,12,12,0,0],tc='d')
    (status, x)=cvxopt.glpk.ilp(c,G.T,h,I=set([0,1]))
    print status
    print x[0],x[1] 
    print sum(c.T*x)
    

    【讨论】:

    • 好的,谢谢,变量 x[0](以前的 x)和 x[1](以前的 y)的命名更合适了。
    【解决方案2】:

    Python 3.8.8 更新

    from cvxopt.glpk import ilp
    import numpy as np
    from cvxopt import matrix
    c=matrix([0,-1],tc='d')
    G=matrix([[-1,1],[3,2],[2,3],[-1,0],[0,-1]],tc='d')
    h=matrix([1,12,12,0,0],tc='d')
    (status, x)=ilp(c,G.T,h,I=set([0,1]))
    print (status)
    print (x[0],x[1])
    print (sum(c.T*x))
    

    调用:

    cvxopt.glpk.ilp(c,G.T,h,I=set([0,1]))
    

    返回: 模块“cvxopt”没有属性“glpk”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-25
      相关资源
      最近更新 更多