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

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

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:

我尝试优化Totpod之和约束条件是每个Cat只能被选择一次但如果我改变我的代码要么什么都得不到要么得到所有的组件

这是我的代码

导入库
```python
import numpy as np
import pandas as pd
import scipy.optimize as sc
from pulp import LpProblem, LpVariable, LpMaximize, lpSum, LpMinimize, value
prob = LpProblem("Maximize_TotPod", LpMaximize)

数据部分:

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

创建二进制决策变量:

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

计算'Totpod'值的总和:

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

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

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

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

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

解决问题:

prob.solve()

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

selected_cats = [cat for cat in df['Cat'] if cat_vars[cat].value() == 1]
total_sum = totpod_sum + value(prob.objective)

print("Selected index:", selected_cats)
print("Max Totpod:", total_sum)

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

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


<details>
<summary>英文:</summary>

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.

Here is my code:

    
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

    import numpy as np
    import pandas as pd
    import scipy.optimize as sc
    from pulp import LpProblem, LpVariable, LpMaximize, lpSum, LpMinimize, value
    prob = LpProblem(&quot;Maximize_TotPod&quot;, LpMaximize)
    
    data={&#39;a&#39;:[&#39;Amu&#39;,508], &#39;b&#39;:[&#39;Coif&#39;,508], &#39;c&#39;:[&#39;Amu&#39;, 253]}
    df= pd.DataFrame.from_dict(data, orient=&#39;index&#39;, columns=[&#39;Cat&#39;, &#39;Totpod&#39;])

    # Creating binary decision variables for each &#39;Cat&#39; value
    cat_vars = LpVariable.dicts(&quot;Cat&quot;, df[&#39;Cat&#39;], cat=&quot;Binary&quot;)

    # Calculating the total sum of &#39;Totpod&#39; values
    totpod_sum = df[&#39;Totpod&#39;].sum()

    # Objective function: maximize the sum of &#39;Totpod&#39;
    prob += lpSum(cat_vars[cat] * df.loc[df[&#39;Cat&#39;] == cat, &#39;Totpod&#39;].sum() for cat in df[&#39;Cat&#39;])

    # Constraint: select each &#39;Cat&#39; only once
    for cat in df[&#39;Cat&#39;]:
        prob += cat_vars[cat] &lt;= 1

    # Solving the problem
    prob.solve()

    selected_cats = [cat for cat in df[&#39;Cat&#39;] if cat_vars[cat].value() == 1]
    total_sum = totpod_sum + value(prob.objective)

    # Printing the selected index and the max of Totpod
    print(&quot;Selected index:&quot;, selected_cats)
    print(&quot;Max Totpod&#39;:&quot;, total_sum)

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

Do you know how I can modify to make it works, I don&#39;t mind using another optimizer 

</details>


# 答案1
**得分**: 1

以下是您要翻译的部分:

IIUC,您可以将`selected_cats`简单生成为唯一`Cat`值的列表,以及通过按`Cat`分组,取最大`Totpod`值并对它们求和来获得最优(我假设您指的是最大)`Totpod`总和:

```python
selected_cats = df['Cat'].unique().tolist()
total_sum = df.groupby('Cat')['Totpod'].max().sum()

print("Selected index:", selected_cats)
print("Max Totpod:", total_sum)

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

Selected index: ['Amu', 'Coif']
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:

selected_cats = df[&#39;Cat&#39;].unique().tolist()
total_sum = df.groupby(&#39;Cat&#39;)[&#39;Totpod&#39;].max().sum()

print(&quot;Selected index:&quot;, selected_cats)
print(&quot;Max Totpod&#39;:&quot;, total_sum)

Output (for your sample data)

Selected index: [&#39;Amu&#39;, &#39;Coif&#39;]
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:

确定