Файлы HDF5 в Python
Файл HDF5 расшифровывается как Hierarchical Data Format 5. Это файл с открытым исходным кодом, который удобен для хранения большого количества данных. Как следует из названия, он хранит данные в виде иерархической структуры в одном файле. Поэтому, если мы хотим быстро получить доступ к определенной части файла, а не ко всему файлу, мы можем легко сделать это с помощью HDF5. Эта функциональность не видна в обычных текстовых файлах, поэтому HDF5 становится все более популярным, поскольку является новой концепцией. Чтобы использовать HDF5, необходимо импортировать numpy. Одной из важных функций является то, что он может прикреплять мета-набор ко всем данным в файле, что обеспечивает эффективный поиск и доступ. Приступим к установке HDF5 на компьютер.
Чтобы установить HDF5, введите это в свой терминал:
pip install h5py
Мы будем использовать специальный инструмент под названием HDF5 Viewer для графического просмотра этих файлов и работы с ними. Чтобы установить HDF5 Viewer, введите этот код:
pip установить h5pyViewer
Поскольку HDF5 работает на numpy, нам также потребуется установить numpy на нашем компьютере.
python -m pip установить numpy
После того, как все установки будут выполнены, давайте посмотрим, как мы можем записать в файл HDF5.
Note: Working with HDF5 requires basic understanding of numpy and its attributes, so one must be familiar with numpy in order to understand the codes following in this article. To know more about numpy click here.
We will create a file and save a random array of numpy in it:
# Python program to demonstrate# HDF5 file import numpy as npimport h5py # initializing a random numpy arrayarr = np.random.randn(1000) # creating a filewith h5py.File("test.hdf5", "w") as f: dset = f.create_dataset("default", data = arr) |
Output:

In the above code, we first import the modules which were installed previously. Then we initialize the variable arr to a random array of numpy ranging till 1000.
Hence, we can say that this array consists of a large number of data. Next, we open the file as “write only” attribute. This means that if there isn’t any file with the name test.hdf5 then it will create one otherwise it will delete (overwrite) the content of the existing file. While opening the file, we used with instead of open as it has an upper-hand when compared to open() method. We don’t need to close a file if we open it using with Finally, we use the .create_dataset() to set the varibale dset to the array which was created earlier.
We will now read the file which we wrote above:
# open the file as "f"with h5py.File("test.hdf5", "r") as f: data = f["default"] # get the minimum value print(min(data)) # get the maximum value print(max(data)) # get the values ranging from index 0 to 15 print(data[:15]) |
Output:

Here, we open the file again but this time we open it by “read-only” attribute so that no changes can be made to the file. We set the variable data to the data we stored in the previous file. Let’s look at the output:
It may seem that there’s nothing new. It is just an array and we are printing out the numbers just as in an array. But, the variable data is not an array. It’s actually very different than array. It’s a dataset. Rather than storing data in the RAM, it saves it in hard-drive of the computer, thus maintaining a hierarchy of structures just like directories:

When the below line is used
data = f["default"]
in the previous code, we did not access the content of the file directly but created a pointer to point at our content. Let’s look at an advantage of this:
import numpy as npimport h5py arr1 = np.random.randn(10000)arr2 = np.random.randn(10000) with h5py.File("test_read.hdf5", "w") as f: f.create_dataset("array_1", data = arr1) f.create_dataset("array_2", data = arr2) |
We created two datasets but the whole procedure is same as before. A file named “test_read.hdf5” is created using the “w” attribute and it contains two datasets (array1 and array2) of random numbers. Now suppose we want to read only a selective portion of array2. For example, we want to read that part of array2 corresponding to where values of array1 are greater than 1. If we were using the conventional text files instead of HDF5 files, it would be nearly impossible to achieve this. That’s exactly were we see the power of HDF5 files:
with h5py.File("test_read.hdf5", "r") as f: d1 = f["array_1"] d2 = f["array_2"] data = d2[d1[:]>1] |
We use the [:] to create a copy of the dataset d1 into the RAM. We did this because a dataset (the data in hard-drive) cannot be compared to the integers.
Output:

So, we conclude that HDF5 files are our best tools when we are dealing with large files as it allows us selective reading and writing of files which otherwise would have consumed a lot of memory and time.

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.
Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.