cvxpy,线性优化,以编程方式建立问题,目标是一些变量的总和

时间:2018-10-26 15:22:39

标签: mathematical-optimization linear-programming cvxpy

我遇到了需要优化某些产品分配的问题。每个产品都有权重(基本上是客户喜欢的程度)和类别(某些客户不接受每种产品)

我的数据看起来像这样

prod_name, category, weight
name1,     c1,    10
name2,     c1,    5
name3,     c1,    1
name4,     c2,    8
name5,     c2,    7
name6,     c2,    6

我还有一张桌子说我们的债务属于不同类别(与上表相同)

category, debt
c1,    100
c2,    500

x1 + x2 + x3 = 100的约束下,我想最大化X *权重(在这种情况下,它是两个六维向量的点积)(或者,将其表示为对应于第1类必须加总到第1类中的债务)和x4 + x5 + x6 = 500

实际上,我喜欢800个类别,所以我想以编程方式进行操作,但是我不知道如何开始构建此问题。

目标很简单

Xxx = cvx.Variable(len(R))
objective = cvx.Maximize(cvx.sum_entries(Xxx.T*R))

其中R只是一个numpy数组的“ weight”列

但是我不知道如何建立约束。另外,我想跟踪名称(也就是说,一旦获得解决方案,就需要将解决方案数组的所有元素映射回prod_name列中的名称)

cvxpy是否允许上述任何一种,还是我需要查看其他软件包?

1 个答案:

答案 0 :(得分:1)

据我所知,以下应该可以实现您的目标。请注意,该解决方案似乎很简单:无论选择哪种方案,只要最大化重磅项目的数量即可偿还债务。

#!/usr/bin/env python3

import cvxpy

#The data from your original post
weights = [
  {"name":'name1', "cat":'c1', "weight":10},
  {"name":'name2', "cat":'c1', "weight": 5},
  {"name":'name3', "cat":'c1', "weight": 1},
  {"name":'name4', "cat":'c2', "weight": 8},
  {"name":'name5', "cat":'c2', "weight": 7},
  {"name":'name6', "cat":'c2', "weight": 6}
]

#The data from your original post
debts = [
  {"cat": 'c1', "debt": 100},
  {"cat": 'c2', "debt": 500}
]

#Add a variable to each item in weights
for w in weights:
  w['var'] = cvxpy.Variable()

#Add up all the weight variables from each category
weights_summed_by_cat = dict()
for w in weights:
  if w['cat'] in weights_summed_by_cat:
    weights_summed_by_cat[w['cat']] += w['var']
  else:
    weights_summed_by_cat[w['cat']] = w['var']

#Create a list of debt constraints from the summed weight variables
constraints = []
for d in debts:
  if d['cat'] in weights_summed_by_cat:
    constraints.append(weights_summed_by_cat[d['cat']]<=d['debt'])

#Don't allocate negative amounts
for w in weights:
  constraints.append(w['var']>=0)

#Create the objective function
obj = cvxpy.Maximize(cvxpy.sum([w['weight']*w['var'] for w in weights]))

#Create a problem instance
prob = cvxpy.Problem(obj, constraints)

#Solve the problem and catch the optimal value of the objective
val = prob.solve()

#Print optimal value
print("Final value: {0}".format(val))

#Print the amount assigned to each weight
for w in weights:
  print("Allocate {0} of {1}".format(w['var'].value, w['name']))