ValueError: Invalid input for linprog: b_ub must be a 1-D array; b_ub must not have more than one non-singleton dimension and the number of rows in A_ub must equal the number of values in b_ub 仍然报错
时间: 2024-01-04 15:02:07 浏览: 178
非常抱歉,我之前给出的答案有误。在调用linprog函数时,确实需要将b_ub参数传递一个一维数组,且长度与约束矩阵A_ub的行数相等。
这里是修正后的代码:
```python
import numpy as np
from scipy.optimize import linprog
def integer_cutting_plane(c, A, b, bounds):
relaxed_A = A
relaxed_b = b
while True:
res = linprog(c=c, A_ub=relaxed_A, b_ub=relaxed_b.flatten(), bounds=bounds)
x = res.x
if all(int(val) == val for val in x):
return x.astype(int)
new_constraint = (relaxed_A @ x <= relaxed_b)
relaxed_A = np.vstack((relaxed_A, new_constraint))
def get_bounds():
return [(0, None), (0, None)]
def get_c():
return np.array([40, 90])
def get_A():
return np.array([[-9, -7], [-7, -20]])
def get_b():
return np.array([-56, -70])
if __name__ == '__main__':
bounds = get_bounds()
relaxed_A = get_A()
relaxed_b = get_b()
integer_cutting_plane(get_c(), relaxed_A, relaxed_b, bounds)
```
这次我在主函数中添加了两个变量`relaxed_A`和`relaxed_b`,分别用于保存初始的约束矩阵A和约束向量b。然后在调用`integer_cutting_plane`函数时,传递这两个变量而不是直接调用`get_A()`和`get_b()`函数。
这样,通过使用`relaxed_b.flatten()`将`relaxed_b`转换为一维数组,可以解决报错问题。
再次对之前的错误表示歉意,并感谢你的耐心指正。希望这次修改能够解决问题。
阅读全文