Python⼆次规划和线性规划使⽤实例
这篇⽂章主要介绍了Python⼆次规划和线性规划使⽤实例,⽂中通过⽰例代码介绍的⾮常详细,对⼤家的学习或者⼯作具有⼀定的参考学习价值,需要的朋友可以参考下
对于⼆次规划(quadratic programming)和线性规划(Linear Programming)问题
MATLAB⾥是有可以直接⽤来解决⼆次规划问题的,来解决线性规划问题。Python中也有很多库⽤来解决,对于⼆次规划有CVXOPT, CVXPY, Gurobi, MOSEK, qpOASES 和 quadprog;对于线性规划有,,。
⽬前发现quadprog进⾏pip install quadprog不成功,⽽cvxopt成功了,就先说cvxopt的使⽤。
安装
正则化的最小二乘法曲线拟合pythonconda install -c conda-forge cvxopt
安装⾮常顺利
使⽤
cvxopt有⾃⼰的matrix格式,因此使⽤前得包装⼀下
对于⼆次规划:
def cvxopt_solve_qp(P, q, G=None, h=None, A=None, b=None):
P = .5 * (P + P.T) # make sure P is symmetric
args = [cvxopt.matrix(P), cvxopt.matrix(q)]
if G is not None:
if A is not None:
sol = cvxopt.solvers.qp(*args)
if 'optimal' not in sol['status']:
return None
return np.array(sol['x']).reshape((P.shape[1],))
对于线性规划:
def cvxopt_solve_lp(f, A, b):
#args = [cvxopt.matrix(f), cvxopt.matrix(A), cvxopt.matrix(b)]
#cvxopt.solvers.lp(*args)
sol = cvxopt.solvers.lp(cvxopt.matrix(f), cvxopt.matrix(A), cvxopt.matrix(b))
return np.array(sol['x']).reshape((f.shape[0],))
参考:
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。