python 求解二次规划(quadprog)
二次规划在MATLAB中,quadprog是具有线性约束的二次目标函数的求解器。quadprog 求由下式指定的问题的最小值H、A 和 Aeq 是矩阵,f、b、beq、lb、ub 和 x 是向量。其具体用法为:x = quadprog(H,f)x = quadprog(H,f,A,b)x = quadprog(H,f,A,b,Aeq,beq)x = quadprog(H,f,A,b,Aeq,beq
二次规划
在MATLAB中,quadprog是具有线性约束的二次目标函数的求解器。
quadprog 求由下式指定的问题的最小值
H、A 和 Aeq 是矩阵,f、b、beq、lb、ub 和 x 是向量。
其具体用法为:
x = quadprog(H,f)
x = quadprog(H,f,A,b)
x = quadprog(H,f,A,b,Aeq,beq)
x = quadprog(H,f,A,b,Aeq,beq,lb,ub)
x =quadprog(H,f,A,b,Aeq,beq,lb,ub,x0)
x =quadprog(H,f,A,b,Aeq,beq,lb,ub,x0,options)
x = quadprog(problem)
[x,fval] = quadprog()
[x,fval,exitflag,output] = quadprog()
[x,fval,exitflag,output,lambda] = quadprog(___)
当解决一个具有线性约束的二次规划问题时:
要求解此问题,首先输入系数矩阵。
使用MATLAB语句为:
H = [1 -1; -1 2];
f = [-2; -6];
A = [1 1; -1 2; 2 1];
b = [2; 2; 3];
[x,fval,exitflag,output,lambda] = ...
quadprog(H,f,A,b);
x,fval %打印结果
当使用python进行二次型求解时,采用qpsolvers库中的solve_qp函数进行求解:
进行库文件的安装
pip install cvxopt==1.2.6 cvxpy==1.1.11 Cython==0.29.22 ecos==2.0.7.post1 numpy osqp==0.6.2.post0 qdldl==0.1.5.post0 qpsolvers==1.7.0 quadprog==0.1.8 scipy scs==2.1.4 -i https://pypi.tuna.tsinghua.edu.cn/simple
from numpy import array
from qpsolvers import solve_qp
H=array([[1.,-1.],[-1.,2.]])
f=array([[-2.],[-6.]]).reshape((2,))
L=array([[1.,1.],[-1.,2.],[2.,1.]])
k=array([[2.],[2.],[3.]]).reshape((3,))
x = solve_qp(H, f, L,k)
print("QP solution: x = {}".format(x))
输出
QP solution: x = [0.66666667 1.33333333]
也可参考这位大佬的博客
(https://blog.csdn.net/u013421629/article/details/108358409)
import numpy as np
import cvxopt
def quadprog(H, f, L=None, k=None, Aeq=None, beq=None, lb=None, ub=None):
"""
Input: Numpy arrays, the format follows MATLAB quadprog function: https://www.mathworks.com/help/optim/ug/quadprog.html
Output: Numpy array of the solution
"""
n_var = H.shape[1]
P = cvxopt.matrix(H, tc='d')
q = cvxopt.matrix(f, tc='d')
if L is not None or k is not None:
assert(k is not None and L is not None)
if lb is not None:
L = np.vstack([L, -np.eye(n_var)])
k = np.vstack([k, -lb])
if ub is not None:
L = np.vstack([L, np.eye(n_var)])
k = np.vstack([k, ub])
L = cvxopt.matrix(L, tc='d')
k = cvxopt.matrix(k, tc='d')
if Aeq is not None or beq is not None:
assert(Aeq is not None and beq is not None)
Aeq = cvxopt.matrix(Aeq, tc='d')
beq = cvxopt.matrix(beq, tc='d')
sol = cvxopt.solvers.qp(P, q, L, k, Aeq, beq)
return np.array(sol['x'])
if __name__ == '__main__':
H=np.array([[1,-1],[-1,2]])
print(H)
f=np.array([[-2],[-6]])
print(f)
L=np.array([[1,1],[-1,2],[2,1]])
print(L)
k=np.array([[2],[2],[3]])
print(k)
res=quadprog(H, f, L,k)
print(res)
更多推荐
所有评论(0)