Scipy 的线性规划

Linear programming with Scipy

我正在尝试用 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

只需更换

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