【问题标题】:Simple Symbolic LP problem to Matrix form矩阵形式的简单符号 LP 问题
【发布时间】:2020-06-18 10:08:34
【问题描述】:

我解决了一个线性规划问题,这是我的符号形式代码。

import cvxpy as cp
import numpy as np

x11 = cp.Variable(nonneg=True)
x12 = cp.Variable(nonneg=True)
x21 = cp.Variable(nonneg=True)
x22 = cp.Variable(nonneg=True)
x31 = cp.Variable(nonneg=True)
x32 = cp.Variable(nonneg=True)

constraints = [x11 + x12 == 1000,
              x21 + x22 == 1500,
              x31 + x32 == 1200,
              x11 + x21 + x31 == 2300,
              x12 + x22 + x32 == 1400]

obj = cp.Minimize((80*x11 + 215*x12 + 100*x21 + 108*x22 + 102*x31 + 68*x32))

prob = cp.Problem(obj, constraints)
prob.solve()
print('status: ', prob.status)
print('optimal value: ', prob.value)
print('optimal variables: ', x11.value, x12.value, x21.value, x22.value, x31.value, x32.value)

状态:最佳

最佳值:313200.00003146095

最佳变量:999.9999999627637 3.7235625579412695e-08 1299.99999940076 200.00000059923934 6.364774533690845e-07 1199.999999363524

但我想将此代码更改为矩阵形式。这是我的矩阵形式的另一个代码

x = cp.Variable((3, 2), nonneg=True)

constraints = [cp.sum(x[0,:]) == 1000,
              cp.sum(x[1,:]) == 1500,
              cp.sum(x[2,:]) == 1200,
              cp.sum(x[:, 0]) == 2300,
              cp.sum(x[:, 1]) == 1400]

coe = [[80, 215], [100, 108], [102, 68]]

t
obj = cp.Minimize(cp.sum(coe @ x))

prob = cp.Problem(obj, constraints)
prob.solve()
print('status: ', prob.status)
print('optimal value: ', prob.value)
for i in range(3):
    for j in range(2):
        print('optimal variables:x('+str(i)+','+str(j)+')', x[i,j].value)

状态:最佳

最佳值:810999.9999986519

最优变量:x(0,0) 649.9892627159586

最优变量:x(0,1) 350.01073728291954

最优变量:x(1,0) 900.0113075911175

最优变量:x(1,1) 599.9886924056102

最优变量:x(2,0) 749.9994296884455

最优变量:x(2,1) 450.00057030957413

我认为结果应该是一样的,矩阵形式的代码是错误的。你能找出我的错误吗?

【问题讨论】:

    标签: python linear-programming cvxpy cvxopt


    【解决方案1】:

    在处理矩阵乘法时必须小心,尤其是在不同的库中。我发现@ 用于矩阵-矩阵乘法。而不是element-wise 乘法。见cvxpy's official documents

    @ 乘法过程中不知何故,cvxpy 误解了你的目标。

    解决方案: 将 obj = cp.Minimize(cp.sum(coe @ x)) 更改为

    obj = cp.Minimize(cp.sum(cp.multiply(coe, x.T))) (我也很困惑为什么coe被认为是(2x3))

    【讨论】:

      猜你喜欢
      • 2014-05-11
      • 1970-01-01
      • 2021-08-23
      • 1970-01-01
      • 2021-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多