如何在 Python 中读取 HDF5 文件

2025-03-13 09:16:00
admin
原创
15
摘要:问题描述:我正在尝试使用 Python 从 hdf5 文件读取数据。我可以使用 读取 hdf5 文件h5py,但我不知道如何访问文件中的数据。我的代码import h5py import numpy as np f1 = h5py.File(file_name,'r+') 这有效并且文...

问题描述:

我正在尝试使用 Python 从 hdf5 文件读取数据。我可以使用 读取 hdf5 文件h5py,但我不知道如何访问文件中的数据。

我的代码

import h5py    
import numpy as np    
f1 = h5py.File(file_name,'r+')    

这有效并且文件被读取。但是我如何访问文件对象内的数据f1


解决方案 1:

阅读 HDF5

import h5py
filename = "file.hdf5"

with h5py.File(filename, "r") as f:
    # Print all root level object names (aka keys) 
    # these can be group or dataset names 
    print("Keys: %s" % f.keys())
    # get first object name/key; may or may NOT be a group
    a_group_key = list(f.keys())[0]

    # get the object type for a_group_key: usually group or dataset
    print(type(f[a_group_key])) 

    # If a_group_key is a group name, 
    # this gets the object names in the group and returns as a list
    data = list(f[a_group_key])

    # If a_group_key is a dataset name, 
    # this gets the dataset values and returns as a list
    data = list(f[a_group_key])
    # preferred methods to get dataset values:
    ds_obj = f[a_group_key]      # returns as a h5py dataset object
    ds_arr = f[a_group_key][()]  # returns as a numpy array

写入 HDF5

import h5py

# Create random data
import numpy as np
data_matrix = np.random.uniform(-1, 1, size=(10, 3))

# Write data to HDF5
with h5py.File("file.hdf5", "w") as data_file:
    data_file.create_dataset("dataset_name", data=data_matrix)

有关更多信息,请参阅h5py 文档。

替代方案

  • JSON:适合编写人类可读的数据;非常常用(读取和写入)

  • CSV:超级简单格式(读写)

  • pickle:一种 Python 序列化格式(读写)

  • MessagePack(Python 包):更紧凑的表示(读取和写入)

  • HDF5(Python 包):适用于矩阵(读写)

  • XML:也存在 叹息 (读写)

对于您的应用程序,以下内容可能很重要:

  • 其他编程语言的支持

  • 读写性能

  • 紧凑性(文件大小)

另请参阅:数据序列化格式比较

如果你正在寻找创建配置文件的方法,你可能需要阅读我的短文《Python 中的配置文件》

解决方案 2:

读取文件

import h5py

f = h5py.File(file_name, mode)

通过打印存在的 HDF5 组来研究文件的结构

for key in f.keys():
    print(key) #Names of the root level object names in HDF5 file - can be groups or datasets.
    print(type(f[key])) # get the object type: usually group or dataset

提取数据

#Get the HDF5 group; key needs to be a group name from above
group = f[key]

#Checkout what keys are inside that group.
for key in group.keys():
    print(key)

# This assumes group[some_key_inside_the_group] is a dataset, 
# and returns a np.array:
data = group[some_key_inside_the_group][()]
#Do whatever you want with data

#After you are done
f.close()

解决方案 3:

你可以使用 Pandas。

import pandas as pd
pd.read_hdf(filename,key)

解决方案 4:

这是我刚刚编写的一个简单函数,它读取由 keras 中的 save_weights 函数生成的 .hdf5 文件并返回包含层名称和权重的字典:

def read_hdf5(path):

    weights = {}

    keys = []
    with h5py.File(path, 'r') as f: # open file
        f.visit(keys.append) # append all keys to list
        for key in keys:
            if ':' in key: # contains data if ':' in key
                print(f[key].name)
                weights[f[key].name] = f[key].value
    return weights

https://gist.github.com/Attila94/fb917e03b04035f3737cc8860d9e9f9b

尚未彻底测试过,但对我来说它有用。

解决方案 5:

要将 .hdf5 文件的内容读取为数组,可以执行以下操作

> import numpy as np 
> myarray = np.fromfile('file.hdf5', dtype=float)
> print(myarray)

解决方案 6:

使用以下代码读取数据并转换为 numpy 数组

import h5py
f1 = h5py.File('data_1.h5', 'r')
list(f1.keys())
X1 = f1['x']
y1=f1['y']
df1= np.array(X1.value)
dfy1= np.array(y1.value)
print (df1.shape)
print (dfy1.shape)

将数据集值读入 numpy 数组的首选方法:

import h5py
# use Python file context manager:
with h5py.File('data_1.h5', 'r') as f1:
    print(list(f1.keys()))  # print list of root level objects
    # following assumes 'x' and 'y' are dataset objects
    ds_x1 = f1['x']  # returns h5py dataset object for 'x'
    ds_y1 = f1['y']  # returns h5py dataset object for 'y'
    arr_x1 = f1['x'][()]  # returns np.array for 'x'
    arr_y1 = f1['y'][()]  # returns np.array for 'y'
    arr_x1 = ds_x1[()]  # uses dataset object to get np.array for 'x'
    arr_y1 = ds_y1[()]  # uses dataset object to get np.array for 'y'
    print (arr_x1.shape)
    print (arr_y1.shape)

解决方案 7:

如果您在 hdf 文件中命名了数据集,那么您可以使用以下代码在 numpy 数组中读取和转换这些数据集:

import h5py
file = h5py.File('filename.h5', 'r')

xdata = file.get('xdata')
xdata= np.array(xdata)

如果您的文件位于不同的目录中,您可以在前面添加路径'filename.h5'

解决方案 8:

阅读

使用visititems中的函数h5py。回调函数会在整个层次结构中调用:组和数据集。

import h5py

# Open the HDF5 file in read mode
file_path = 'your_file.h5'

with h5py.File(file_path, 'r') as file:
    # Function to recursively print the HDF5 dataset hierarchy
    def print_hdf5_item(name, obj):
        # name is in path format like /group1/group2/dataset
        if isinstance(obj, h5py.Group):
            # Do something like creating a dictionary entry
            print(f'Group: {name}')
        elif isinstance(obj, h5py.Dataset):
            # Do something with obj like converting to a pandas.Series 
            # and storing to a dictionary entry
            print(f'Dataset: {name}')

    # Visit all items in the HDF5 file and print their names
    file.visititems(print_hdf5_item)

或使用pandas.read_hdf

import pandas as pd
df = pd.read_hdf('./store.h5')

请注意,您的数据可能无法直接映射到 DataFrame。前一种选择更灵活。


写作

如果使用Pandas,你可以使用pandas.DataFrame.to_hdf

# df is a DataFrame object
df.to_hdf('database.h5', 'group/subgroup', table=True, mode='a')

解决方案 9:

from keras.models import load_model 

h= load_model('FILE_NAME.h5')

解决方案 10:

您需要做的是创建一个数据集。如果您查看快速入门指南,它会告诉您需要使用文件对象来创建数据集。然后f.create_dataset您就可以读取数据了。文档中对此进行了解释。

解决方案 11:

使用来自这个问题和最新文档的一些答案,我能够使用提取我的数值数组

import h5py
with h5py.File(filename, 'r') as h5f:
    h5x = h5f[list(h5f.keys())[0]]['x'][()]

在我的例子中,其中'x'只是 X 坐标。

解决方案 12:

使用这个对我来说很好用


    weights = {}

    keys = []
    with h5py.File("path.h5", 'r') as f: 
        f.visit(keys.append) 
        for key in keys:
            if ':' in key: 
                print(f[key].name)     
                weights[f[key].name] = f[key][()]
    return weights

print(read_hdf5())

如果你使用的是 h5py<='2.9.0' 那么你可以使用


    weights = {}

    keys = []
    with h5py.File("path.h5", 'r') as f: 
        f.visit(keys.append) 
        for key in keys:
            if ':' in key: 
                print(f[key].name)     
                weights[f[key].name] = f[key].value
    return weights

print(read_hdf5())

解决方案 13:

我推荐一个 h5py 的包装器,H5Attr它允许您通过诸如group.dataset(相当于原始的group['dataset'])和 IPython/Jupyter 制表符补全等属性轻松加载 hdf5 数据。

代码在这里。下面是一些使用示例,你可以自己尝试下面的代码

# create example HDF5 file for this guide
import h5py, io
file = io.BytesIO()
with h5py.File(file, 'w') as fp:
    fp['0'] = [1, 2]
    fp['a'] = [3, 4]
    fp['b/c'] = 5
    fp.attrs['d'] = 's'

# import package
from h5attr import H5Attr

# open file
f = H5Attr(file)

# easy access to members, with tab completion in IPython/Jupyter
f.a, f['a']

# also work for subgroups, but note that f['b/c'] is more efficient
# because it does not create f['b']
f.b.c, f['b'].c, f['b/c']

# access to HDF5 attrs via a H5Attr wrapper
f._attrs.d, f._attrs['d']

# show summary of the data
f._show()
# 0   int64 (2,)
# a   int64 (2,)
# b/  1 members

# lazy (default) and non-lazy mode
f = H5Attr(file)
f.a  # <HDF5 dataset "a": shape (2,), type "<i8">

f = H5Attr(file, lazy=False)
f.a  # array([3, 4])
相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   1572  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1355  
  信创产品在政府采购中的占比分析随着信息技术的飞速发展以及国家对信息安全重视程度的不断提高,信创产业应运而生并迅速崛起。信创,即信息技术应用创新,旨在实现信息技术领域的自主可控,减少对国外技术的依赖,保障国家信息安全。政府采购作为推动信创产业发展的重要力量,其对信创产品的采购占比情况备受关注。这不仅关系到信创产业的发展前...
信创和国产化的区别   0  
  信创,即信息技术应用创新产业,旨在实现信息技术领域的自主可控,摆脱对国外技术的依赖。近年来,国货国用信创发展势头迅猛,在诸多领域取得了显著成果。这一发展趋势对科技创新产生了深远的推动作用,不仅提升了我国在信息技术领域的自主创新能力,还为经济社会的数字化转型提供了坚实支撑。信创推动核心技术突破信创产业的发展促使企业和科研...
信创工作   0  
  信创技术,即信息技术应用创新产业,旨在实现信息技术领域的自主可控与安全可靠。近年来,信创技术发展迅猛,对中小企业产生了深远的影响,带来了诸多不可忽视的价值。在数字化转型的浪潮中,中小企业面临着激烈的市场竞争和复杂多变的环境,信创技术的出现为它们提供了新的发展机遇和支撑。信创技术对中小企业的影响技术架构变革信创技术促使中...
信创国产化   0  
热门文章
项目管理软件有哪些?
云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用