CVXPY#
This Python notebook shows a basic example using CVXPY.
import cvxpy as cp
import numpy as np
# Problem data.
m = 10
n = 7
np.random.seed(1)
A = np.random.randn(m, n)
b = np.random.randn(m)
# Construct the problem.
x = cp.Variable(n)
# *, +, -, / are overloaded to construct CVXPY objects.
cost = cp.sum_squares(A @ x - b)
objective = cp.Minimize(cost)
# <=, >=, == are overloaded to construct CVXPY constraints.
constraints = [0 <= x, x <= 1]
prob = cp.Problem(objective, constraints)
# The optimal objective is returned by prob.solve().
result = prob.solve()
# The optimal value for x is stored in x.value.
print(x.value)
# The optimal Lagrange multiplier for a constraint
# is stored in constraint.dual_value.
print(constraints[0].dual_value)
[ 1.84938877e-01 4.25089350e-01 -4.02558020e-22 -2.86851394e-21
1.58256609e-22 1.68042475e-01 6.01518175e-22]
[0. 0. 0.4282705 4.44105024 2.45354868 0.
3.24159717]