python - 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.
如何解决这个问题?
解决方案
似乎 cvxpy 不支持超过 2 个维度,这是您在使用 和 进行索引时arr
所做的u
事情。v
w
作为替代方案,您可以简单地重塑这些索引变量,使它们是一维的:
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,))
推荐阅读
- excel - VBA ByRef 参数类型不匹配不一致?
- c++11 - 如何将构建器对象写入 C++ 中 Cap'n Proto 中的输出流对象而不是文件?
- azure-devops - VSTS CD 阶段任务总是一次性打印日志
- apache-spark - Spark JDBC连接将主键解释为可为空
- c - 如何在 C 语言中同时使用 writefds 和 readfds 进行多客户端服务器通信程序?
- visual-studio-2017 - Visual Studio 2017 中文本编辑器的分词器
- rx-java - RxJava:阻塞单个 vs 先阻塞
- nsnumber - NSNumber 的 stringValue 打印我们不想要的其他字符串
- python - 从较小的包裹中填写订单?
- c# - 如何对存储在 txt、csv、xls、xlsx 文件中的数据应用验证