Python 2.7 中的 CVXPY 矩阵乘法

CVXPY matrix multipication in Python 2.7

我正在使用 CVXPY 代码 here。我想 运行 它在 Python 2.7 而不是 Python 3. 运算符 @ 似乎在 Python 上工作 3. 让它在 python 2.7 上工作,我把代码修改为

import cvxpy as cp
import numpy as np

n = 3
p = 3
np.random.seed(1)
C = np.random.randn(n, n)
A = []
b = []
for i in range(p):
   A.append(np.random.randn(n, n))
b.append(np.random.randn())

X = cp.Variable((n,n), symmetric=True)
# The operator >> denotes matrix inequality.
constraints = [X >> 0] 
prob = cp.Problem(cp.Minimize(np.matmul(C,X)), constraints)
prob.solve()

我用 numpy.matmul 代替 @ 的地方。但是,它给了我这个错误 "ValueError: matmul: Input operand 1 does not have enough dimensions"

我的问题是如何 运行 此代码 here 在 python 2.7(而不是 Python 3)中成功。

您需要对 cvxpy 变量使用 cvxpy 运算符,换句话说,您不能对 cvxpy 变量执行 np.matmul。您可以只使用 * 运算符。 cvxpy 会将其视为矩阵乘法。试试这个,

C = np.random.randn(2, n)
C * X

你会得到:

Expression(AFFINE, UNKNOWN, (2, 3))