繁体   English   中英

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

暂无
暂无

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

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