如何在CVXPY中设置半正参数(矩阵)?

时间:2018-09-12 07:41:56

标签: python cvxpy

我想通过热启动来设置cvx.Parameter来检查性能是否有所改善,

cvxpy.error.DCPError: Problem does not follow DCP rules.

我的代码在这里:

import time 
import numpy as np
import cvxpy as cvx


m = 300
x = cvx.Variable((m, 1))
p_cov = cvx.Parameter((m, m))
prob = cvx.Problem(cvx.Maximize(-cvx.quad_form(x, p_cov)), [x>=0, cvx.sum(x)==1])

for _ in range(10):
    df_return = np.random.randn(m, m+1)
    cov = np.cov(df_return)
    p_cov.value = cov
    t1 = time.time()
    prob.solve(warm_start=True)
    t2 = time.time()
    print("Solve time:", round(t2-t1, 2))

我认为关键是p_cov应该是一个半正矩阵,但是我不能解决它。期待您的帮助,谢谢!

1 个答案:

答案 0 :(得分:1)

您是对的!您只需要告诉cvxpy p_cov是正半定号。

p_cov = cvx.Parameter((m, m), PSD=True)

DCP现在可以计算该表达式的正确性质:

cvx.quad_form(x, p_cov)

哪个是

Expression(CONVEX, NONNEGATIVE, (1, 1))

代替:

Expression(UNKNOWN, UNKNOWN, (1, 1))

Advanced Features中查找更多文档。