首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从CVX到CVXPY或CVXOPT

从CVX到CVXPY或CVXOPT
EN

Stack Overflow用户
提问于 2015-06-04 15:02:01
回答 1查看 13.2K关注 0票数 12

我一直在尝试将一些代码从Matlab传递到Python。我在Matlab上也有同样的凸优化问题,但是我在将它传递给CVXPY或CVXOPT时遇到了问题。

代码语言:javascript
复制
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所做的尝试。

代码语言:javascript
复制
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的话,那就太好了。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-06-04 19:04:53

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

Matlab

代码语言:javascript
复制
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

代码语言:javascript
复制
import numpy as np
import cvxpy as cp

# 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 = cp.Variable(n)
lmbd = cp.Variable(i)
objective = cp.Minimize(cp.sum_squares(x - y))
constraints = [x == A*lmbd,
               lmbd >= np.zeros(i),
               cp.sum(lmbd) == 1]

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

CVXOPT正在等待.

票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30647436

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档