0

我有这个优化问题,我试图根据列 X 的唯一值最大化列 z,但也在一个约束范围内,即 X 选择的每个唯一值加起来的 Y 列最多小于或等于(在这个例子)23。

例如,我有这个示例数据:

X  Y  Z
1  9  25    
1  7  20     
1  5  5
2  9  20 
2  7  10 
2  5  5    
3  9  10 
3  7  5
3  5  5

结果应如下所示:

   XYZ

  1 9 25  
  2 9 20     
  3 5 5

这是使用 LpSolve 在 R 中设置线性规划优化的副本?有解决方案,但我在 python 中需要相同的解决方案。

4

1 回答 1

0

对于那些想要在 python 中开始使用纸浆的人可以参考http://ojs.pythonpapers.org/index.php/tppm/article/view/111

Github repo- https://github.com/coin-or/pulp/tree/master/doc/KPyCon2009也很方便。

下面是 Python 中针对虚拟问题提出的代码

            import pandas as pd
            import pulp

            X=[1,1,1,2,2,2,3,3,3]
            Y=[9,7,5,9,7,5,9,7,5]
            Z=[25,20,5,20,10,5,10,5,5]

            df = pd.DataFrame({'X':X,'Y':Y,'Z':Z})
            allx = df['X'].unique()
            possible_values = [(w,b) for w in allx for b in range(1,4)]

            x = pulp.LpVariable.dicts('arr', (allx, range(1,4)),
                                        lowBound = 0,
                                        upBound = 1,
                                        cat = pulp.LpInteger)

            model = pulp.LpProblem("Optim", pulp.LpMaximize)
            model += sum([x[w][b]*df[df['X']==w].reset_index()['Z'][b-1] for (w,b) in possible_values])

            model += sum([x[w][b]*df[df['X']==w].reset_index()['Y'][b-1] for (w,b) in possible_values]) <= 23, \
                                        "Maximum_number_of_Y"

            for value in allx:
                model += sum([x[w][b] for (w,b) in possible_values if w==value])>=1

            for value in allx:
                model += sum([x[w][b] for (w,b) in possible_values if w==value])<=1

            ##View definition
            model

            model.solve()

            print("The choosen rows are out of a total of %s:"%len(possible_values))
            for v in model.variables():
                print v.name, "=", v.varValue

对于 R 中的解决方案

    d=data.frame(x=c(1,1,1,2,2,2,3,3,3),y=c(9,7,5,9,7,5,9,7,5),z=c(25,20,5,20,10,5,10,5,3))
            library(lpSolve)
            all.x <- unique(d$x)
            d[lp(direction = "max",
                 objective.in = d$z,
                 const.mat = rbind(outer(all.x, d$x, "=="), d$y),
                 const.dir = rep(c("==", "<="), c(length(all.x), 1)),
                 const.rhs = rep(c(1, 23), c(length(all.x), 1)),
                 all.bin = TRUE)$solution == 1,]
于 2018-03-02T15:40:42.240 回答