用Scipy进行线性编程

时间:2018-09-02 12:04:50

标签: python scipy arguments linear-programming

我正在尝试使用Scipy解决线性编程问题,但出现错误,指出参数的尺寸不匹配。但似乎确实如此,下面的代码和错误消息

代码

import numpy as np
from scipy import optimize as opt


k = 6
n = 3
indexes = [1, 2, 5, 6, 7, 9]
V = np.zeros((1, k))
count = 0
for ID in xrange(1, 4):
    ind = count * n + ID
    p = indexes.index(ind)
    V[0, p] = 1
    count += 1

bounds = []
for i in xrange(6):
    bounds.append((0, 1))
bounds = tuple(bounds)
W1 = np.zeros((3, 6))
W1[1, 2] = 0.4
W1[2, 3] = 0.5
b1 = np.transpose(np.zeros(3))
b1[1] = 0.8
b1[2] = 0.25

W3 = np.zeros((3, 6))
W3[1, 2] = 0.7
W3[2, 3] = 0.8
b3 = np.transpose(np.zeros(3))
b3[1] = 0.6
b3[2] = 0.2

EQ = np.vstack([W1, W3]).T
Eb = np.vstack([b1, b3]).T

print EQ.shape, "shape of A_eq"
print V.shape, "shape of c"

res = opt.linprog(c=V, A_eq=EQ, b_eq=Eb, bounds=bounds, options={"disp": True})

错误消息

ValueError: Invalid input for linprog with method = 'simplex'.  Number of columns in A_eq must be equal to the size of c

1 个答案:

答案 0 :(得分:2)

只需替换

res = opt.linprog(c=V, A_eq=EQ, b_eq=Eb, bounds=bounds, options={"disp": True})

通过

res = opt.linprog(c=V[0], A_eq=EQ, b_eq=Eb, bounds=bounds, options={"disp": True})

如果打印V,您将看到它是列表的列表。因此,所需的数据位于V[0]下。尽管优化失败。

其他方法是将V重新定义为

V = np.zeros(k)

然后在for循环中使用

V[p] = 1.

这样,您可以在优化部分坚持使用c=V