首页 > 解决方案 > CVXPY 对二维数组的约束,同时引用了 3 个元素

问题描述

我有一个S大小为 VxV 的矩阵。我想对它施加以下形式的几个约束:约束. 我试图这样做,但这段代码遇到了问题ValueError: Atoms must be at most 2D.

我整理了一个简化的问题示例:

def ILP_example(scores):
    V = scores.shape[0]
    u, v, w = np.meshgrid(range(V), range(V), range(V))

    arr = cp.Variable(scores.shape)

    objective = cp.Maximize(
        cp.sum(cp.multiply(scores, arr))
    )
    constraints = [
        arr[u, v]           + arr[v, w]          - arr[u, w]          <= 1,
      ]
    prob = cp.Problem(objective, constraints)
    prob.solve()
    return

尝试运行它,例如ILP_example(np.random.rand(5, 5))导致错误ValueError: Atoms must be at most 2D.如何解决这个问题?

标签: pythonnumpymatrixconstraintscvxpy

解决方案


似乎 cvxpy 不支持超过 2 个维度,这是您在使用 和 进行索引时arr所做的u事情。vw

作为替代方案,您可以简单地重塑这些索引变量,使它们是一维的:

u, v, w = [x.reshape(-1) for x in np.meshgrid(range(V), range(V), range(V))]

然后这工作得很好:

constraints = [arr[u, v] + arr[v, w] + arr[u, w] <= 1]

arr[u, v]现在是一个 125 长度的向量:

Expression(AFFINE, UNKNOWN, (125,))

推荐阅读