import cvxpy as cp import numpy as np from scipy.optimize import minimize A=np.array([[14,16,21],[19,17,10],[10,15,12],[9,12,13]]) X=cp.Variable((4,7),integer=False) y=X[:,3:7] x=X[:,0:3] T=cp.Variable(1,integer=True) obj=lambda T:T cons={'type':'ineq','fun': lambda T,x:T*np.ones(4).reshape(4,1)-A[:,2]-x[:,2],'type':'ineq','fun': lambda x:x[:,1:3]-A[:,0:2]-x[:,0:2],'type':'ineq','fun': lambda T,x:T*y[0:3,1:4]+x[1:4,]-x[0:3,]-A[0:3,],'type':'ineq','fun': lambda T,x:T*y[0:2,2:4]+x[2:4,]-x[0:2,]-A[0:2,],'type':'ineq','fun': lambda T,x:T*y[0,3]+x[3,]-x[0,]-A[0,]} prob=minimize(obj,np.ones(4,4),constraints=cons)
时间: 2023-06-15 11:05:09 浏览: 145
这段代码有一些问题,首先是在定义约束条件时,用了多个`type`参数,应该将它们放在同一个字典中,例如:
```
cons = [
{'type': 'ineq', 'fun': lambda T,x: T*np.ones(4).reshape(4,1)-A[:,2]-x[:,2]},
{'type': 'ineq', 'fun': lambda x: x[:,1:3]-A[:,0:2]-x[:,0:2]},
{'type': 'ineq', 'fun': lambda T,x: T*y[0:3,1:4]+x[1:4,]-x[0:3,]-A[0:3,]},
{'type': 'ineq', 'fun': lambda T,x: T*y[0:2,2:4]+x[2:4,]-x[0:2,]-A[0:2,]},
{'type': 'ineq', 'fun': lambda T,x: T*y[0,3]+x[3,]-x[0,]-A[0,]}
]
```
另外,在调用`minimize`函数时,应该将初始值传给`x0`参数,而不是直接传给`args`参数,应该修改为:
```
prob = minimize(obj, np.ones((4, 7)), constraints=cons, options={'disp': True})
```
最后,由于`minimize`函数需要提供一个可行解作为初始值,因此需要先手动计算一个可行解,例如将所有变量都设置为0:
```
X_init = np.zeros((4, 7))
y_init = X_init[:, 3:7]
x_init = X_init[:, 0:3]
T_init = 1
```
完整代码如下:
```
import cvxpy as cp
import numpy as np
from scipy.optimize import minimize
A = np.array([[14, 16, 21], [19, 17, 10], [10, 15, 12], [9, 12, 13]])
X = cp.Variable((4, 7), integer=False)
y = X[:, 3:7]
x = X[:, 0:3]
T = cp.Variable(1, integer=True)
obj = lambda T: T
cons = [
{'type': 'ineq', 'fun': lambda T,x: T*np.ones(4).reshape(4,1)-A[:,2]-x[:,2]},
{'type': 'ineq', 'fun': lambda x: x[:,1:3]-A[:,0:2]-x[:,0:2]},
{'type': 'ineq', 'fun': lambda T,x: T*y[0:3,1:4]+x[1:4,]-x[0:3,]-A[0:3,]},
{'type': 'ineq', 'fun': lambda T,x: T*y[0:2,2:4]+x[2:4,]-x[0:2,]-A[0:2,]},
{'type': 'ineq', 'fun': lambda T,x: T*y[0,3]+x[3,]-x[0,]-A[0,]}
]
X_init = np.zeros((4, 7))
y_init = X_init[:, 3:7]
x_init = X_init[:, 0:3]
T_init = 1
prob = minimize(obj, X_init, constraints=cons, options={'disp': True})
print(prob.x)
```
阅读全文