Python中的优化(线性规划)

2024-06-25 05:22:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我对优化还不熟悉,正在试用我用Python编写的一个示例。我的目标是找出我需要添加多少组件才能尽可能地模拟产品

我举的例子是这样的:我得到一个包含3个组件(x,y,z)的产品,这些组件都有与之相关的值,但我不知道每个组件中有多少用于制作最终产品。另外一个条件是,3个组件的总值可能与最终产品的值不匹配。我给自己的一个限制是,我知道产品的重量,在这个例子中,我举了10个例子

由于组件和产品的值可能不匹配,我认为最好使用组件和产品总值的每个值之间的差异,然后最小化原始3个组件的wrt

我厌倦了用纸浆来解决这个问题,但我不确定如何去写一个好的目标函数,甚至我的目标函数的想法是否可行

一些python代码示例:

components = pd.DataFrame({
        "x": [3, 4, 1, 4],
        "y": [0, 2, 1, 4],
        "z": [0, 0, 1, 4],
        "total": [4, 6, 3, 12]
        })

product = pd.DataFrame({
        "product": [4, 2, 6, 12]
        })

difference = product["product"] - components["total"]

# define model
model = LpProblem("test", sense = LpMinimize)

# variables to add to the model to add to the model
component1 = LpVariable("component1", lowBound = 0, upBound = None, cat = "Integer")
component2 = LpVariable("component2", lowBound = 0, upBound = None, cat = "Integer")
component3 = LpVariable("component3", lowBound = 0, upBound = None, cat = "Integer")

# constraints

model += component1 + component2 + component3 == 10

# objective function
# minimise the difference wrt to the 3 components

model.solve()

示例输出(如果这是最佳输出):

component1 = 3
component2 = 6
component3 = 1

先谢谢你


Tags: theto示例目标model产品components组件