简体   繁体   English

将绝对偏差编程为线性程序

[英]Programming absolute deviation as linear program

I am attempting to convert a sum of absolute deviations to a linear programming problem so that I can utilize CPLEX (or other solver).我正在尝试将绝对偏差的总和转换为线性规划问题,以便我可以利用 CPLEX(或其他求解器)。 I am stuck on how the matrices are to be set up.我被困在如何设置矩阵上。 The problem is as follows:问题如下:

minimize abs(x1 - 5) + abs(x2 - 3)
s.t. x1 + x2 = 10

I have the following constraints set up to transform the problem into a linear form:我设置了以下约束以将问题转换为线性形式:

  x1 - 5  <= t1
-(x1 - 5) <= t1 and 

  x2 - 3  <= t2
-(x2 - 3) <= t2

I've set up the objective function as我已将目标 function 设置为

c = [0,0,1,1]

but I am lost on how to set up但我不知道如何设置

Ax <= b

in matrix form.以矩阵形式。 What I have so far is:到目前为止,我所拥有的是:

A = [[ 1, -1, 0, 0],
     [-1, -1, 0, 0],
     [ 0,  0, 1,-1],
     [ 0,  0,-1,-1]]
b =  [ 5, -5, 3,-3] 

I have set up the other constraint in matrix for as:我在矩阵中设置了另一个约束为:

B =  [1, 1, 0, 0]
b2 = [10] 

When I run the following:当我运行以下命令时:

linprog(c,A_ub=A,b_ub=b,A_eq=B,b_eq=b2,bounds=[(0,None),(0,None)])

I get the following error message back:我收到以下错误消息:

ValueError: Invalid input for linprog: A_eq must have exactly two dimensions, and the number of columns in A_eq must be equal to the size of c

I know there is a solution because when I use scipy.optimize.minimize it solves to [6,4].我知道有一个解决方案,因为当我使用 scipy.optimize.minimize 时,它会解决到 [6,4]。 I'm sure the issue is I am not formulating the input matrices correctly but I am not sure how to set them up so that it runs.我确定问题是我没有正确地制定输入矩阵,但我不确定如何设置它们以使其运行。

Edit - here is the code that does not run:编辑 - 这是不运行的代码:

import numpy as np
from scipy.optimize import linprog, minimize

c = np.block([np.zeros(2),np.ones(2)])
print("c =>",c)

A = [[ 1, -1, 0, 0],
     [-1, -1, 0, 0],
     [ 0,  0, 1,-1],
     [ 0,  0,-1,-1]]

b =  [[ 5, -5, 3,-3]]
print(A)
print(np.multiply(A,b))

B = [ 1, 1, 0, 0]
b2 = [10]
print(np.multiply(B,b2))

linprog(c,A_ub=A,b_ub=b,A_eq=B,b_eq=b2,bounds=[(0,None),(0,None)],
        options={'disp':True})

I think the message is quite good.我认为这个消息非常好。 B should be 2-dimensional matrix instead of a 1-dimensional vector. B应该是二维矩阵而不是一维向量。 So:所以:

B =  [[1, 1, 0, 0]]

Secondly, the bounds array is too short.其次,bounds 数组太短。 Thirdly, your ordering of variables is inconsistent.第三,您的变量顺序不一致。 The columns in A are x1,t1,x2,t2 while the columns in B (and c) seem to be x1,x2,t1,t2 . A中的列是x1,t1,x2,t2而 B (和 c)中的列似乎是x1,x2,t1,t2 They need to follow the same scheme.他们需要遵循相同的方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM