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, 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() integer_cutting_plane(get_c(), get_A(), get_b(), bounds)以上代码运行报错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-04-17 11:24:42 浏览: 223
在你的代码中,报错是因为在调用linprog函数时,传递给参数b_ub的参数relaxed_b是一个二维数组。linprog函数要求b_ub是一个一维数组。
要解决这个问题,你可以使用numpy库的flatten()方法将relaxed_b转换为一维数组。flatten()方法会将多维数组展平为一维数组。
以下是修改后的代码:
```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()
integer_cutting_plane(get_c(), get_A(), get_b(), bounds)
```
通过使用flatten()方法将relaxed_b转换为一维数组,你可以解决报错问题。请注意,这里使用的是numpy库的flatten()方法,而不是reshape()方法。
阅读全文