【发布时间】:2021-10-04 22:35:17
【问题描述】:
我有一个 Juypter Notebook 用于处理大型矩阵 (20000x20000)。我正在运行多次迭代,但我收到一条错误消息,说每次迭代后我没有足够的 RAM。如果我重新启动内核,我可以运行下一次迭代,可能 Juypter Notebook 内存不足,因为它存储了变量(下一次迭代不需要这些变量)。有没有办法释放内存?
编辑:我不知道粗体部分是否正确。无论如何,我希望释放内存,欢迎提出任何建议。
## Outputs:
two_moons_n_of_samples = [int(_) for _ in np.repeat(20000, 10)]
for i in range(len(two_moons_n_of_samples)):
# print(f'n: {two_moons_n_of_samples[i]}')
## Generate the data and the graph
X, ground_truth, fid = synthetic_data({'type': 'two_moons', 'n': two_moons_n_of_samples[i], 'fidelity': 60, 'sigma': 0.18})
N = X.shape[0]
dist_mat = sqdist(X.T, X.T)
opt = {
'graph': 'full',
'tau': 0.004,
'type': 's'
}
LS = dense_laplacian(dist_mat, opt)
## Eigenvalues and eigenvectors
tic = time.time() ## Time how long to calculate eigenvalues/eigenvectors
V, E = np.linalg.eigh(LS)
idx = np.argsort(V)
V, E = V[idx], E[:, idx]
V = V / V.max()
decomposition_time = time.time() - tic
## Initialize u0
u0 = np.zeros(N)
for j in range(len(fid[0])):
u0[fid[0][j]] = 1
for j in range(len(fid[1])):
u0[fid[1][j]] = -1
## Initialize parameters
dt = 0.05
gamma = 0.07
max_iter = 100
## Run MAP estimation
tic = time.time()
u_eg, _ = probit_optimization_eig(E, V, u0, dt, gamma, fid, max_iter)
eg_time = time.time() - tic
## Run MAP estimation with CG
tic2 = time.time()
u_cg, _ = probit_optimization_cg(LS, u0, dt, gamma, fid, max_iter)
cg_time = time.time() - tic2
## Write to file:
with open('results2_two_moons_egvscg.txt', 'a') as f:
f.write(f'{i},{two_moons_n_of_samples[i]},{decomposition_time + eg_time},{cg_time}\n')
错误:
MemoryError: Unable to allocate 1.07 GiB for an array with shape (12000, 12000) and data type float64
---------------------------------------------------------------------------
MemoryError Traceback (most recent call last)
~\AppData\Local\Temp\2/ipykernel_2344/941022539.py in <module>
11 'type': 's'
12 }
---> 13 LS = dense_laplacian(dist_mat, opt)
14
15 ## Eigenvalues and eigenvectors
C:/Users/\util\graph\dense_laplacian.py in dense_laplacian(dist_mat, opt)
69 D_inv_sqrt = 1.0 / np.sqrt(D)
70 D_inv_sqrt = np.diag(D_inv_sqrt)
---> 71 L = np.eye(W.shape[0]) - D_inv_sqrt @ W @ D_inv_sqrt
72 # L = 0.5 * (L + L.T)
73 if opt['type'] == 'rw':
MemoryError: Unable to allocate 1.07 GiB for an array with shape (12000, 12000) and data type float64
【问题讨论】:
-
还是重写代码不浪费内存? 4M 项没有那么大。每个元素使用多少 RAM?即使使用 128 位,也就是 64MB。但是,如果每次迭代都分配一个新的矩阵副本,例如保存结果,那么您很快就会用完 RAM。每次分配一个新的 64MB 缓冲区也会浪费时间。解决方案是重用临时缓冲区而不是分配新的缓冲区
-
@PanagiotisKanavos 抱歉,这是 40M 项。而且我不确定如何重写代码或检查每个元素使用多少 RAM。每次迭代都会将单个值写入文本文件,我不需要该迭代中的任何其他内容。
-
你在使用 Numpy 吗?我猜它会自动处理这些东西
-
@user13966865 是的,我是。
-
它是 400M 但错误说无法分配一个新的 1GB 12K*12K 64 位浮点数数组。那是一个 不同的 数组。同样,重用缓冲区而不是分配新的缓冲区。并将代码和错误发布为 text,而不是图像。当您尝试 load 数据时,似乎发生了错误,但我无法在图像和评论框之间来回切换。 将代码和错误以文本形式发布!
标签: python visual-studio-code jupyter-notebook jupyter