CVXPY

1.8.2 · active · verified Fri Apr 10

CVXPY is a Python-embedded modeling language for convex optimization problems. It allows users to express optimization problems in a natural way that follows mathematical notation, automatically transforming them into standard form, calling a solver, and unpacking the results. It is actively maintained with frequent patch releases, and major versions (e.g., 1.8.x) are supported with bugfixes while the next major release (e.g., 1.9) is under development, with older major versions no longer officially supported.

Warnings

Install

Imports

Quickstart

This example demonstrates how to solve a least-squares problem with box constraints using CVXPY. It defines variables, an objective function, and constraints, then solves the problem and prints the optimal variable values and duals.

import cvxpy as cp
import numpy as np

# Problem data.
m = 30
n = 20
np.random.seed(1)
A = np.random.randn(m, n)
b = np.random.randn(m)

# Construct the problem.
x = cp.Variable(n)
objective = cp.Minimize(cp.sum_squares(A @ x - b))
constraints = [0 <= x, x <= 1]
prob = cp.Problem(objective, constraints)

# The optimal objective value is returned by `prob.solve()`.
result = prob.solve()

# The optimal value for x is stored in `x.value`.
print("Optimal x:\n", x.value)
# The optimal Lagrange multiplier for a constraint is stored in
# `constraint.dual_value`.
print("Dual value for 0 <= x constraint:\n", constraints[0].dual_value)

view raw JSON →