這篇文章主要介紹了Python二次規劃和線性規劃使用實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
對于二次規劃(quadratic programming)和線性規劃(Linear Programming)問題
MATLAB里是有quadprog函數可以直接用來解決二次規劃問題的,linprog函數來解決線性規劃問題。Python中也有很多庫用來解決,對于二次規劃有CVXOPT, CVXPY, Gurobi, MOSEK, qpOASES 和 quadprog; 對于線性規劃有Gurobi,PuLP, cvxopt。
目前發現quadprog進行pip install quadprog不成功,而cvxopt成功了,就先說cvxopt的使用。
安裝
conda 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: args.extend([cvxopt.matrix(G), cvxopt.matrix(h)]) if A is not None: args.extend([cvxopt.matrix(A), cvxopt.matrix(b)]) 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],))
參考:
Quadratic Programming in Python
Linear Programming in Python with CVXOPT
cvxopt.org
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網之家。
新聞熱點
疑難解答