Skip to content

scipy optimization with multiple constraints

An answer to this question on Stack Overflow.

Question

How to find solution to a linear regression with multiple constraints on the coefficients in python?

enter image description here

Answer

cvxpy is a good choice:

import cvxpy as cp 
import numpy as np
np.random.seed(1) 
y = 100*np.random.random(1) 
x = 200*np.random.random(1000)-100
b = cp.Variable(1000)
constraints = [-100<=b, b<=100, cp.sum(b)==2]
obj = cp.Minimize( cp.square(y-x@b) )
prob = cp.Problem(obj, constraints) 
val = prob.solve()
print(f"Objective value {val}")
print("b values: {0}".format(b.value))