簡體   English   中英

讀取大的.h5文件時出現內存錯誤

[英]Memory error while reading a large .h5 file

我已經從numpy數組創建了一個.h5

h5f = h5py.File('/data/debo/jetAnomaly/AtlasData/dijets/mergedRoot/miniTrees/JZ3W.h5', 'w')
h5f.create_dataset('JZ3WPpxpypz', data=all, compression="gzip")

HDF5數據集“ JZ3WPpxpypz”:形狀(19494500,376),類型為“ f8”

但是在將.h5文件讀取到numpy數組時出現內存錯誤

filename = '/data/debo/jetAnomaly/AtlasData/dijets/mergedRoot/miniTrees/JZ3W.h5'
h5 = h5py.File(filename,'r')

h5.keys()

[u'JZ3WPpxpypz']

data = h5['JZ3WPpxpypz']

如果我嘗試查看數組,它將給我內存錯誤

data[:]

---------------------------------------------------------------------------
MemoryError                               Traceback (most recent call last)
<ipython-input-33-629f56f97409> in <module>()
----> 1 data[:]

h5py/_objects.pyx in h5py._objects.with_phil.wrapper()

h5py/_objects.pyx in h5py._objects.with_phil.wrapper()

/home/debo/env_autoencoder/local/lib/python2.7/site-packages/h5py/_hl/dataset.pyc in __getitem__(self, args)
    560         single_element = selection.mshape == ()
    561         mshape = (1,) if single_element else selection.mshape
--> 562         arr = numpy.ndarray(mshape, new_dtype, order='C')
    563 
    564         # HDF5 has a bug where if the memory shape has a different rank

MemoryError: 

有什么內存有效的方法可以將.h5文件讀取到numpy數組中?

謝謝Debo

您無需調用numpy.ndarray()即可獲取數組。 嘗試這個:

arr = h5['JZ3WPpxpypz'][:]
# or
arr = data[:]

添加[:]將返回數組(與data變量不同-它僅引用HDF5數據集)。 兩種方法都應為您提供與原始數組相同的dtype和形狀的數組。 您還可以使用numpy切片操作來獲取數組的子集。

需要進行澄清。 我忽略了numpy.ndarray()在打印data[:]的過程中被調用。 以下是類型檢查,以顯示這兩次調用的收益差異:

# check type for each variable:
data = h5['JZ3WPpxpypz']
print (type(data))
# versus
arr = data[:]
print (type(arr))

輸出將如下所示:

<class 'h5py._hl.dataset.Dataset'>
<class 'numpy.ndarray'>

通常,h5py數據集的行為類似於numpy數組(根據設計)。 但是,它們並不相同 當您嘗試通過此調用( data[:] )打印數據集內容時,h5py嘗試使用numpy.ndarray()在后台將數據集轉換為numpy數組。 如果您有一個較小的數據集或足夠的內存,它會起作用。

arr = h5['JZ3WPpxpypz'][:] :調用arr = h5['JZ3WPpxpypz'][:]使用不調用numpy.ndarray()的進程創建numpy數組。

當數據集非常大時,您可能會遇到無法使用arr= h5f['dataset'][:]創建數組的情況,因為數據集太大而無法作為numpy數組放入內存。 發生這種情況時,您可以創建h5py數據集對象,然后使用切片符號訪問數據的子集,例如以下簡單示例:

data = h5['JZ3WPpxpypz']
arr1 = data[0:100000]
arr2 = data[100000:200000])
# etc

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM