I have a convex optimization problem I am trying to solve with cvxpy. Given a 1 x n
row vector y
and an m x n
matrix C
, I want to find a scalar b
and a 1 x m
row vector a
such that the sum of squares of y - (aC + b(aC @ aC))
is as small as possible (the @
denotes element wise multiplication). In addition, all entires in a
must be nonnegative and sum to 1 and -100 <= b <= 100
. Below is my attempt to solve this using cvxpy.
import numpy as np
import cvxpy as cvx
def find_a(y, C, b_min=-100, b_max=100):
b = cvx.Variable()
a = cvx.Variable( (1,C.shape[0]) )
aC = a * C # this should be matrix multiplication
x = (aC + cvx.multiply(b, cvx.square(aC)))
objective = cvx.Minimize ( cvx.sum_squares(y - x) )
constraints = [0. <= a,
a <= 1.,
b_min <= b,
b <= b_max,
cvx.sum(a) == 1.]
prob = cvx.Problem(objective, constraints)
result = prob.solve()
print a.value
print result
y = np.asarray([[0.10394265, 0.25867508, 0.31258457, 0.36452763, 0.36608997]])
C = np.asarray([
[0., 0.00169811, 0.01679245, 0.04075472, 0.03773585],
[0., 0.00892802, 0.03154158, 0.06091544, 0.07315024],
[0., 0.00962264, 0.03245283, 0.06245283, 0.07283019],
[0.04396226, 0.05245283, 0.12245283, 0.18358491, 0.23886792]])
find_a(y, C)
I keep getting a DCPError: Problem does not follow DCP rules.
error when I try to solve for a
. I am thinking that either my function is not really convex, or I do not understand how to construct the proper cvxpy Problem
. Any help would be greatly appreciated.