如何在 Python 中读取 HDF5 文件
- 2025-03-13 09:16:00
- admin 原创
- 5
问题描述:
我正在尝试使用 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])