我一直在尝试将一些代码从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

这就是我使用 Python 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)

但是,它无法正常工作。你们中的任何人不知道如何使它工作吗?我很确定我的问题出在约束。而且将它与CVXOPT一起使用也将是一件很不错的事情。

最佳答案

我想我明白了,我的约束之一是错误的=),我添加了一个随机种子数以比较结果并检查实际上两种语言是否相同。我将数据留在这里,所以也许某天对某人有用;)

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 正在等待.....

关于python - 从CVX到CVXPY或CVXOPT,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30647436/

10-13 07:22