使用 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

最新更新