编程语言
首页 > 编程语言> > Python求解凸优化问题之CVXPY

Python求解凸优化问题之CVXPY

作者:互联网

CVXPY

CVX是由Michael Grant和Stephen Boyd开发的用于构造和解决严格的凸规划(DCP)的建模系统,建立在Löfberg (YALMIP), Dahl和Vandenberghe (CVXOPT)的工作上。

CVX支持的问题类型

还可以解决更复杂的凸优化问题,包括

CVX使用的注意事项

安装

Python
https://www.cvxpy.org/install/index.html

代码案例(least square)

# Import packages.
import cvxpy as cp
import numpy as np

# Generate data.
m = 20
n = 15
np.random.seed(1)
A = np.random.randn(m, n)
b = np.random.randn(m)
print('\n Closed form solution of least square',np.dot(np.linalg.pinv(A), b))


# Define and solve the CVXPY problem.
x = cp.Variable(n)
cost = cp.sum_squares(A @ x - b)
prob = cp.Problem(cp.Minimize(cost))
prob.solve()

# Print result.
print("\nThe optimal value is", prob.value)
print("The optimal x is")
print(x.value)
print("The norm of the residual is ", cp.norm(A @ x - b, p=2).value)

#add constraint
x_cons = cp.Variable(n)
cost_cons = cp.sum_squares(A @ x_cons - b)
prob_cons = cp.Problem(cp.Minimize(cost_cons),[x_cons >= -10, x_cons <= 10])
prob_cons.solve()

# Print result.
print("\nThe optimal value is", prob_cons.value)
print("The optimal x is")
print(x_cons.value)
print("The norm of the residual is ", cp.norm(A @ x_cons - b, p=2).value)

标签:CVXPY,cons,CVX,求解,Python,programs,print,np,cp
来源: https://blog.csdn.net/weixin_43464554/article/details/121280322