Home > database >  CVXPY, least-squares Optimization, wrong constraint formulation
CVXPY, least-squares Optimization, wrong constraint formulation

Time:01-04

First of all, I'm sorry if my questions doesn't make sens, I am new using CVXPY library and I don't understand everything :/

I am trying to solve a minimization problem that I thought would be easy handle. I got a matrix S dimensions (9,7) with known coefficients, B dimensions (1,7) with known coefficients, Alpha dimensions (1,7) what I need to find, with various constraints :

  • Alpha must be positive
  • The sum of all the coefficients of Alpha must be equal to 1

I need to optimize Alpha such as : A @ Alpha-B=0. I discovered CVXPY and thought least square optimization was perfect for this issue.

This is the code I wrote :

Alpha = cp.Variable(7)
objective = cp.Minimize(cp.sum_squares(S @ Alpha - B))
constraints = [0 <= Alpha, Alpha<=1, np.sum(Alpha.value)==1]
prob = cp.Problem(objective, constraints)

result = prob.solve()

print(Alpha.value)

With

S= np.array([[0.03,0.02,0.072,0.051,0.058,0.0495,0.021 ],
 [0.0295, 0.025 , 0.1  ,  0.045 , 0.064 , 0.055 , 0.032 ],
 [0.02  , 0.018 , 0.16  , 0.032 , 0.054 , 0.064 , 0.025 ],
 [0.0195, 0.03  , 0.144 , 0.027 , 0.04  , 0.06  , 0.04  ],
 [0.02  , 0.0315, 0.156 , 0.0295 ,0.027 , 0.0615 ,0.05  ],
 [0.021 , 0.033 , 0.168 , 0.03  , 0.0265 ,0.063 , 0.09  ],
 [0.02  , 0.05  , 0.28  , 0.039 , 0.035 , 0.055 , 0.04  ],
 [0.021 , 0.03 ,  0.22  , 0.0305, 0.0255, 0.057 , 0.009 ],
 [0.0195, 0.008 , 0.2 ,   0.021 , 0.01 ,  0.048 , 0.0495]])

B=np.array([0.1015, 0.0888, 0.0911, 0.0901, 0.0945, 0.0909, 0.078 , 0.0913,
       0.0845])

My issue is the following one :

  • Without the constraint np.sum(Alpha.value)==1, the code gives me results; but when I add the constraint it returns me
None

I presume the formulation is not good, but I have no Idea how to write it in another way? Or maybe the problem doesn't have solution? Thank you for your time

CodePudding user response:

Use just sum(Alpha) == 1. You are not supposed to use numpy functions in CVXPY expressions, you must use CVXPY functions listed in https://www.cvxpy.org/tutorial/functions/index.html

  • Related