CVX to CVXPY or CVXOPT

I am trying to pipe some code from Matlab to Python. I have the same problem with convex optimization working on Matlab, but I have problems passing it to CVXPY or CVXOPT.

n = 1000;
i = 20;
y = rand(n,1);
A = rand(n,i);
cvx_begin
variable x(n);
variable lambda(i);
minimize(sum_square(x-y));
subject to
    x == A*lambda;
    lambda >= zeros(i,1);
    lambda'*ones(i,1) == 1;
cvx_end

      

This is what I have tried with Python and CVXPY .

import numpy as np
from cvxpy import *

# Problem data.
n = 100
i = 20
np.random.seed(1)
y = np.random.randn(n)
A = np.random.randn(n, i)

# Construct the problem.
x = Variable(n)
lmbd = Variable(i)
objective = Minimize(sum_squares(x - y))
constraints = [x == np.dot(A, lmbd),
               lmbd <= np.zeros(itr),
               np.sum(lmbd) == 1]

prob = Problem(objective, constraints)

print("status:", prob.status)
print("optimal value", prob.value)

      

However, it doesn't work. Does any of you know how to make it work? I'm pretty sure my problem is with limitations . And it would also be nice to have it with CVXOPT.

+3


source to share


1 answer


I think I got it, I had one of the constraints wrong =), I added a random number of seeds to compare the results and check what is actually the same in both languages. I am leaving the data here, so maybe it will be useful to someone someday;)

Matlab

rand('twister', 0);
n = 100;
i = 20;
y = rand(n,1);
A = rand(n,i);
cvx_begin
variable x(n);
variable lmbd(i);
minimize(sum_square(x-y));
subject to
    x == A*lmbd;
    lmbd >= zeros(i,1);
    lmbd'*ones(i,1) == 1;
cvx_end

      



CVXPY

import numpy as np
from cvxpy import *

# random seed
np.random.seed(0)

# Problem data.
n = 100
i = 20
y = np.random.rand(n)
# A = np.random.rand(n, i)  # normal
A = np.random.rand(i, n).T  # in this order to test random numbers

# Construct the problem.
x = Variable(n)
lmbd = Variable(i)
objective = Minimize(sum_squares(x - y))
constraints = [x == A*lmbd,
               lmbd >= np.zeros(i),
               sum_entries(lmbd) == 1]

prob = Problem(objective, constraints)
result = prob.solve(verbose=True)

      

CVXOPT is pending .....

+3


source







All Articles