如何使用每个类别最多一次来最大化一个函数

huangapple go评论106阅读模式
英文:

How to maximize a function using each category 1 time max

问题

Sure, here is the translation of the code you provided without the code parts:

  1. 我尝试优化Totpod之和约束条件是每个Cat只能被选择一次但如果我改变我的代码要么什么都得不到要么得到所有的组件
  2. 这是我的代码
  3. 导入库
  4. ```python
  5. import numpy as np
  6. import pandas as pd
  7. import scipy.optimize as sc
  8. from pulp import LpProblem, LpVariable, LpMaximize, lpSum, LpMinimize, value
  9. prob = LpProblem("Maximize_TotPod", LpMaximize)

数据部分:

  1. data={'a':['Amu',508], 'b':['Coif',508], 'c':['Amu', 253]}
  2. df= pd.DataFrame.from_dict(data, orient='index', columns=['Cat', 'Totpod'])

创建二进制决策变量:

  1. cat_vars = LpVariable.dicts("Cat", df['Cat'], cat="Binary")

计算'Totpod'值的总和:

  1. totpod_sum = df['Totpod'].sum()

目标函数:最大化'Totpod'的总和:

  1. prob += lpSum(cat_vars[cat] * df.loc[df['Cat'] == cat, 'Totpod'].sum() for cat in df['Cat'])

约束条件:每个'Cat'只能选择一次:

  1. for cat in df['Cat']:
  2. prob += cat_vars[cat] <= 1

解决问题:

  1. prob.solve()

选择的'Cat'和最大的Totpod值:

  1. selected_cats = [cat for cat in df['Cat'] if cat_vars[cat].value() == 1]
  2. total_sum = totpod_sum + value(prob.objective)
  3. print("Selected index:", selected_cats)
  4. print("Max Totpod:", total_sum)

它返回[‘Amu’, ‘Coif’, ‘Amu’]和3299.0,但我想要[‘a’, ‘b’]和(508+508) 1016。

你知道如何修改以使其正常工作吗?我不介意使用另一个优化器。

  1. <details>
  2. <summary>英文:</summary>
  3. I tried to optimize the sum of &#39;Totpod&#39; under the constraint that each &#39;Cat&#39; could only be taken once but if I change my code I either got nothing or all the components.
  4. Here is my code:
  1. Cat Fo Pod Pa2 Pa3 Pa4 Pa5 Pa6 Coif Amu An1 An2 Bot Ceint Arm Totpod

a Amu 101 3 4 5 6 7 8 9 10 11 12 13 14 15 508
b Coif 101 3 4 5 6 7 8 9 10 11 12 13 14 15 508
c Amu 50 3 4 5 6 7 8 9 10 11 12 13 14 15 253

  1. import numpy as np
  2. import pandas as pd
  3. import scipy.optimize as sc
  4. from pulp import LpProblem, LpVariable, LpMaximize, lpSum, LpMinimize, value
  5. prob = LpProblem(&quot;Maximize_TotPod&quot;, LpMaximize)
  6. data={&#39;a&#39;:[&#39;Amu&#39;,508], &#39;b&#39;:[&#39;Coif&#39;,508], &#39;c&#39;:[&#39;Amu&#39;, 253]}
  7. df= pd.DataFrame.from_dict(data, orient=&#39;index&#39;, columns=[&#39;Cat&#39;, &#39;Totpod&#39;])
  8. # Creating binary decision variables for each &#39;Cat&#39; value
  9. cat_vars = LpVariable.dicts(&quot;Cat&quot;, df[&#39;Cat&#39;], cat=&quot;Binary&quot;)
  10. # Calculating the total sum of &#39;Totpod&#39; values
  11. totpod_sum = df[&#39;Totpod&#39;].sum()
  12. # Objective function: maximize the sum of &#39;Totpod&#39;
  13. prob += lpSum(cat_vars[cat] * df.loc[df[&#39;Cat&#39;] == cat, &#39;Totpod&#39;].sum() for cat in df[&#39;Cat&#39;])
  14. # Constraint: select each &#39;Cat&#39; only once
  15. for cat in df[&#39;Cat&#39;]:
  16. prob += cat_vars[cat] &lt;= 1
  17. # Solving the problem
  18. prob.solve()
  19. selected_cats = [cat for cat in df[&#39;Cat&#39;] if cat_vars[cat].value() == 1]
  20. total_sum = totpod_sum + value(prob.objective)
  21. # Printing the selected index and the max of Totpod
  22. print(&quot;Selected index:&quot;, selected_cats)
  23. print(&quot;Max Totpod&#39;:&quot;, total_sum)
  24. It returns me [&#39;Amu&#39;, &#39;Coif&#39;, &#39;Amu&#39;] and 3299.0 while I want [&#39;a&#39;, &#39;b&#39;] and (508+508) 1016
  25. Do you know how I can modify to make it works, I don&#39;t mind using another optimizer
  26. </details>
  27. # 答案1
  28. **得分**: 1
  29. 以下是您要翻译的部分:
  30. IIUC,您可以将`selected_cats`简单生成为唯一`Cat`值的列表,以及通过按`Cat`分组,取最大`Totpod`值并对它们求和来获得最优(我假设您指的是最大)`Totpod`总和:
  31. ```python
  32. selected_cats = df['Cat'].unique().tolist()
  33. total_sum = df.groupby('Cat')['Totpod'].max().sum()
  34. print("Selected index:", selected_cats)
  35. print("Max Totpod:", total_sum)

输出(对于您的示例数据):

  1. Selected index: ['Amu', 'Coif']
  2. Max Totpod: 1016
英文:

IIUC, you can generate your selected_cats simply as a list of the unique Cat values, and the optimal (I'm presuming you mean maximum) Totpod sum by grouping by Cat, taking the maximum Totpod values and summing them:

  1. selected_cats = df[&#39;Cat&#39;].unique().tolist()
  2. total_sum = df.groupby(&#39;Cat&#39;)[&#39;Totpod&#39;].max().sum()
  3. print(&quot;Selected index:&quot;, selected_cats)
  4. print(&quot;Max Totpod&#39;:&quot;, total_sum)

Output (for your sample data)

  1. Selected index: [&#39;Amu&#39;, &#39;Coif&#39;]
  2. Max Totpod&#39;: 1016

huangapple
  • 本文由 发表于 2023年5月17日 15:39:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76269607.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定