programing

numpy 배열을 h5py로 입력 및 출력

css3 2023. 9. 12. 20:10

numpy 배열을 h5py로 입력 및 출력

출력이 a인 파이썬 코드가 있습니다.enter image description here항목이 모두 유형인 size matrixfloat. 내선번호와 함께 저장하면.dat파일 크기는 500MB 입니다. 저는 그것을 사용해서 읽었습니다.h5py파일 크기를 상당히 줄입니다.그래서 제가 2D Numpy 배열을 가지고 있다고 가정해 보겠습니다.A. h5py 파일에 저장하려면 어떻게 해야 합니까?또한 배열로 조작을 해야 하는데 같은 파일을 읽고 다른 코드로 numpy 배열로 입력하는 방법은 무엇입니까?

h5py는 데이터셋 및 그룹 모델을 제공합니다.전자는 기본적으로 배열이고 후자는 디렉토리라고 생각할 수 있습니다.각각의 이름이 붙여졌습니다.API 및 예제에 대한 설명서를 살펴봐야 합니다.

http://docs.h5py.org/en/latest/quick.html

모든 데이터를 미리 생성하고 hdf5 파일에 저장하려는 간단한 예는 다음과 같습니다.

In [1]: import numpy as np
In [2]: import h5py
In [3]: a = np.random.random(size=(100,20))
In [4]: h5f = h5py.File('data.h5', 'w')
In [5]: h5f.create_dataset('dataset_1', data=a)
Out[5]: <HDF5 dataset "dataset_1": shape (100, 20), type "<f8">

In [6]: h5f.close()

그런 다음 다음 '를 사용하여 해당 데이터를 다시 로드할 수 있습니다.

In [10]: h5f = h5py.File('data.h5','r')
In [11]: b = h5f['dataset_1'][:]
In [12]: h5f.close()

In [13]: np.allclose(a,b)
Out[13]: True

반드시 문서를 확인해야 합니다.

http://docs.h5py.org

hdf5 파일에 대한 쓰기는 h5py 또는 pytables에 따라 달라집니다(각각 hdf5 파일 사양 상단에 있는 서로 다른 python API가 있음).numpy에서 기본적으로 제공하는 다른 간단한 이진 형식도 살펴봐야 합니다.np.save,np.savez기타:

http://docs.scipy.org/doc/numpy/reference/routines.io.html

파일 열기/닫기를 보다 깨끗하게 처리하고 메모리 누수를 방지하는 방법:

준비:

import numpy as np
import h5py

data_to_write = np.random.random(size=(100,20)) # or some such

쓰기:

with h5py.File('name-of-file.h5', 'w') as hf:
    hf.create_dataset("name-of-dataset",  data=data_to_write)

읽기:

with h5py.File('name-of-file.h5', 'r') as hf:
    data = hf['name-of-dataset'][:]

언급URL : https://stackoverflow.com/questions/20928136/input-and-output-numpy-arrays-to-h5py