【发布时间】:2023-03-25 03:55:01
【问题描述】:
我的代码生成一个大小为 (1, 1, n, n, m, m) 的 numpy 数组列表,其中 n 可能在 50-100 之间变化,m 在 5-10 之间变化,具体取决于手头的情况。列表本身的长度可能高达 10,000,并且正在代码末尾使用 pickle 写入/转储。对于这些数字较高端的情况或文件大小超过 5-6 GB 的情况,我会收到 Out of Memory 错误。下面是一个虚构的例子,
import numpy as np
list, list_length = [], 1000
n = 100
m = 3
for i in range(0, list_length):
list.append(np.random.random((1, 1, n, n, m, m)))
file_path = 'C:/Users/Desktop/Temp/'
with open(file_path, 'wb') as file:
pickle.dump(list, file)
我正在寻找一种可以帮助我的方法
- 拆分数据,这样我就可以摆脱内存错误,并且
- 以后需要时以原始形式重新加入数据
我能想到的是:
for i in range(0, list_length):
data = np.random.random((1, 1, n, n, m, m))
file_path = 'C:/Users/Desktop/Temp/'+str(i)
with open(file_path, 'wb') as file:
pickle.dump(data, file)
然后结合使用:
combined_list = []
for i in range(0, list_length):
file_path = 'C:/Users/Desktop/Temp/single' + str(i)
with open(file_path, 'rb') as file:
data = pickle.load(file)
combined_list.append(data)
使用这种方式,文件大小肯定会因多个文件而减小,但也会因多个文件 I/O 操作而增加处理时间。
有没有更优雅更好的方法来做到这一点?
【问题讨论】:
标签: python python-3.x numpy file-io split