【发布时间】:2018-03-25 11:18:54
【问题描述】:
我在计算 numpy 中对于 RAM(~100G)来说太大的数组的平均值时遇到了问题。
我已经研究过使用np.memmap,但不幸的是,我的数组作为数据集存储在 hdf5 文件中。根据我的尝试,np.memmap 不接受 hdf5 数据集作为输入。TypeError: coercing to Unicode: need string or buffer, Dataset found
那么我怎样才能以有效的方式从磁盘调用内存映射数组上的np.mean?当然,我可以遍历数据集的某些部分,每个部分都适合内存。
但是,这感觉太像一种解决方法,我也不确定它是否会达到最佳性能。
这里有一些示例代码:
data = np.randint(0, 255, 100000*10*10*10, dtype=np.uint8)
data.reshape((100000,10,10,10)) # typically lot larger, ~100G
hdf5_file = h5py.File('data.h5', 'w')
hdf5_file.create_dataset('x', data=data, dtype='uint8')
def get_mean_image(filepath):
"""
Returns the mean_array of a dataset.
"""
f = h5py.File(filepath, "r")
xs_mean = np.mean(f['x'], axis=0) # memory error with large enough array
return xs_mean
xs_mean = get_mean_image('./data.h5')
【问题讨论】:
-
我会继续对
h5py数据集进行分块读取。让它工作。然后您可以测试迭代是否真的在花费您的时间。对于大型数组,内存管理的成本可能会超过迭代的成本。 -
你是对的,它实际上并没有花那么多钱。唯一的麻烦是你必须编码的循环,所以它不是那么优雅。谢谢!