Skip to main content
 首页 » 编程设计

python之将 `dask.array` 保存为 hdf5 数据集

2024年09月07日10thcjp

我有一个 dask.array跨越多个 hdf5 文件。基本上,我想做的是对数据集进行切片并将生成的切片存储到 hdf5。到目前为止我尝试过的基本上是这样的:

In [1]: import dask.array as da 
 
In [3]: import numpy as np 
 
In [5]: xs = da.from_array(np.linspace(0, 10), chunks=10) # could be from hdf5 files 
 
In [7]: import h5py 
 
In [8]: h5f = h5py.File('/tmp/paul/foo.h5') 
 
In [9]: h5f.create_dataset(name='ham', data=xs) 
Out[9]: <HDF5 dataset "ham": shape (50,), type "<f8"> 

这很好用。然而,当我 da.concatenate多个 h5py数据集,create_dataset功能似乎卡住(线程死锁?)。注意 xs可能是一个(大概)10 GB 的数据集,跨越 10 个文件,每个文件 1 GB。

写xs 的合理方式是什么?到 h5py数据集而不求助于 da.compute和冒险MemoryError ?

请您参考如下方法:

我怀疑 h5py 库正在将您的 dask 数组转换为内存中的 numpy 数组,这可能不是您想要的。

相反,您可能需要存储功能(参见 this section in the documentation)

f = h5py.File('myfile.hdf5') 
d = f.require_dataset('/data', shape=x.shape, dtype=x.dtype) 
da.store(x, d) 

您可能还需要 to_hdf5 方法(参见 this section in the documentation)

da.to_hdf5('myfile.hdf5', '/x', x) 

您应该注意适本地分块您的 HDF5 数据集,以便它与您的 dask.array 分块对齐。如果您不想自己考虑,to_hdf5 方法将为您处理。