如何为python中的重复优化约束减少已用内存?

问题描述

我有以下简化形式的数学优化问题:

min ∑Pxy
s.t. Pxy≥Pyz,∀x,y,z
Pxy ∈ {0,1}

此问题具有X Y Z约束。我编写以下代码来执行优化。我想到的唯一方法是引入两个新矩阵,这些矩阵通过与向量Pxy和Pyz相乘来重复约束。这些矩阵的大小为(XYZ * YZ)和(XYZ * XY)。随着问题规模的增加,这些矩阵的大小将变得巨大,而我的RAM无法处理。是否可以以较少的内存约束来重新编写此代码? (可能更少的内存使用量可能会导致更快的速度。)

以下代码使用了Google colab上的所有RAM并崩溃了! (虽然优化问题很容易并且可以手动解决)

import cvxpy as cp
import numpy as np

np.random.seed(55)
X_max,Y_max,Z_max = 70,70,50

P_yz = np.random.choice([0,1],size=(Y_max,Z_max),p=[9./10,1./10])
P_yz = P_yz.reshape(-1)

z_repetition = np.zeros((X_max,Z_max,X_max,Y_max),dtype=np.int8)
for x in range(X_max):
  for y in range(Y_max):
    for z in range(Z_max):
      z_repetition[x,z,x,y] = 1
z_repetition = z_repetition.reshape(X_max * Y_max * Z_max,-1)

x_repetition = np.zeros((X_max,dtype=np.int8)
for x in range(X_max):
  for y in range(Y_max):
    for z in range(Z_max):
      x_repetition[x,z] = 1
x_repetition = x_repetition.reshape(X_max * Y_max * Z_max,-1)

P_xy = cp.Variable((X_max * Y_max),boolean=True)
constraints = [] 
constraints.append(z_repetition * P_xy >= np.matmul(x_repetition,P_yz))
problem = cp.Problem(cp.Minimize(cp.sum(P_xy)),constraints) 
objective = problem.solve(verbose=True)
# print(P_xy.value.reshape(X_max,-1))

解决方法

由于@sascha的评论,我使用ConnectionID Assessment ReviewDate ecfa663b-3dd2-4aef-b25c-e43dd6b82enb Assessment One 2020-09-21T00:00:00 ecfa663b-3dd2-4aef-b25c-e43dd6b82enb Assessment Two 2020-09-21T18:15:36 ecfa663b-3dd2-4aef-b25c-e43dd6b82enb Assessment Three 2020-09-21T18:12:35 重新编写了代码,并且解决了内存问题。

我将修改后的代码发布在这里:

scipy.sparse.coo_matrix

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...