从CVX到CVXPY或CVXOPT

sil*_*gon 6 python matlab cvxopt cvx cvxpy

我一直在尝试将一些代码从Matlab传递给Python.我在Matlab上有相同的凸优化问题但是我在将它传递给CVXPY或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
Run Code Online (Sandbox Code Playgroud)

这是我尝试使用PythonCVXPY.

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)
Run Code Online (Sandbox Code Playgroud)

但是,它没有用.你们有谁知道如何让它发挥作用?我很确定我的问题在于约束.使用CVXOPT也很好.

sil*_*gon 5

我想我得到了它,我有一个约束错误=),我添加了一个随机的种子数,以便比较结果和检查两种语言实际上是相同的.我把数据留在这里,所以也许有一天这对某人有用;)

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
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

CVXOPT正在等待.....

  • 根据cvxpy,他们使用cvxopt库来解决问题.在cvxopt中,你必须以更标准的方式为你想要使用的求解器类型编写问题,而cvxpy应该根据你用于问题的结构调整你的问题(他们应该选择cvxopt的类型)求解器取决于您的问题并以标准cvxopt方式​​传递变量).在一天结束时,CVXPY是一个试图让事情变得更容易的包装器. (3认同)
  • 没错,你不能在cvxpy对象上使用像``np.sum``这样的NumPy函数. (2认同)