使用pulp优化Python

尝试使用pulp编写优化代码。

从给定的数据集中,我希望选出5个项目,这些项目在总和上最大化价值,同时受到以下约束:2个项目是蓝色,2个项目是黄色,以及一个随机项目。但是,使用附件中的代码,我只得到了3个项目,请参考输出部分。

请建议对现有代码需要做出的更改。

import pandas as pd
import pulp
import re
import sys
sys.setrecursionlimit(10000)
data = [['A', 'blue', 'circle', 0.454],
        ['B', 'yellow', 'square', 0.570],
        ['C', 'red', 'triangle', 0.789],
        ['D', 'red', 'circle', 0.718],
        ['E', 'red', 'square', 0.828],
        ['F', 'orange', 'square', 0.709],
        ['G', 'blue', 'circle', 0.696],
        ['H', 'orange', 'square', 0.285],
        ['I', 'orange', 'square', 0.698],
        ['J', 'orange', 'triangle', 0.861],
        ['K', 'blue', 'triangle', 0.658],
        ['L', 'yellow', 'circle', 0.819],
        ['M', 'blue', 'square', 0.352],
        ['N', 'orange', 'circle', 0.883],
        ['O', 'yellow', 'triangle', 0.755]]
df = pd.DataFrame(data, columns = ['item', 'color', 'shape', 'value'])
BlueMatch = lambda x: 1 if x=='blue' else 0
YellowMatch = lambda x: 1 if x=='yellow' else 0
RedMatch = lambda x: 1 if x=='red' else 0
OrangeMatch = lambda x: 1 if x=='orange' else 0
df['color'] = df['color'].astype(str)
df['isBlue'] = df.color.apply(BlueMatch)
df['isYellow'] = df.color.apply(YellowMatch)
df['isRed'] = df.color.apply(RedMatch)
df['isOrange'] = df.color.apply(OrangeMatch)
prob  = pulp.LpProblem("complex_napsack", pulp.LpMaximize)
x = pulp.LpVariable.dicts( "x", indexs = df.index, lowBound=0, cat='Integer')
prob += pulp.lpSum([x[i]*df.value[i] for i in df.index ])
prob += pulp.lpSum([x[i]*df.isBlue[i] for i in df.index])==2
prob += pulp.lpSum([x[i]*df.isYellow[i] for i in df.index])==2
prob += pulp.lpSum([x[i] for i in df.index ])==10
prob.solve()
for v in prob.variables():
    if v.varValue != 0.0:
        mystring = re.search('([0-9]*$)', v.name)
        print(v.name, "=", v.varValue)
        ind = int(mystring.group(1))
        print(df.item[ind])
output:
x_11 = 2.0
L
x_13 = 6.0
N
x_6 = 2.0
G

回答:

您只需要将变量声明为二进制而不是整数,像这样:

x = pulp.LpVariable.dicts("x", indexs=df.index, cat=pulp.LpBinary)

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注