欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【python 3.7.5 求解二次规划】MATLAB函数quadprog的python 实现

程序员文章站 2022-05-21 20:33:21
...

【python 3.7.5 求解二次规划】MATLAB函数quadprog的python 实现
【python 3.7.5 求解二次规划】MATLAB函数quadprog的python 实现

【python 3.7.5 求解二次规划】MATLAB函数quadprog的python 实现

【python 3.7.5 求解二次规划】MATLAB函数quadprog的python 实现

matlab 使用quadprog 函数,求解线性规划,二次规划等问题。那么如何保持跟matlab 相同的参数,python使用习惯呢,下面定义一个函数,符合matlab用户的使用习惯。简单例子如下:

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)

运行结果:

[[ 1 -1]
 [-1  2]]
[[-2]
 [-6]]
[[ 1  1]
 [-1  2]
 [ 2  1]]
[[2]
 [2]
 [3]]
     pcost       dcost       gap    pres   dres
 0: -1.1510e+01 -8.7580e+00  3e+00  9e-01  7e-16
 1: -9.1195e+00 -8.5750e+00  3e-01  1e-01  2e-16
 2: -8.3243e+00 -8.2258e+00  2e-01  3e-02  6e-16
 3: -8.2233e+00 -8.2223e+00  2e-03  3e-04  2e-16
 4: -8.2222e+00 -8.2222e+00  2e-05  3e-06  2e-16
 5: -8.2222e+00 -8.2222e+00  2e-07  3e-08  7e-17
Optimal solution found.
[[0.6666667 ]
 [1.33333334]]

参考百度文库:二次规划教程

相关标签: 数据科学--python