我试图从Python中读取hdf5文件中的数据.我可以使用读取hdf5文件h5py,但我无法弄清楚如何访问文件中的数据.
import h5py
import numpy as np
f1 = h5py.File(file_name,'r+')
Run Code Online (Sandbox Code Playgroud)
这有效,文件被读取.但是如何访问文件对象中的数据f1呢?
Mar*_*oma 89
import h5py
filename = 'file.hdf5'
with h5py.File(filename, 'r') as f:
# List all groups
print("Keys: %s" % f.keys())
a_group_key = list(f.keys())[0]
# Get the data
data = list(f[a_group_key])
Run Code Online (Sandbox Code Playgroud)
#!/usr/bin/env python
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('group_name', data=data_matrix)
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅h5py文档.
对于您的应用程序,以下可能很重要:
另请参见:数据序列化格式的比较
如果您正在寻找一种制作配置文件的方法,您可能希望阅读我的简短文章Python中的配置文件
小智 18
你可以使用熊猫.
import pandas as pd
pd.read_hdf(filename,key)
Run Code Online (Sandbox Code Playgroud)
Dak*_*ksh 10
读取文件
import h5py
f = h5py.File(file_name, mode)
Run Code Online (Sandbox Code Playgroud)
通过打印存在的HDF5组来研究文件的结构
for key in f.keys():
print(key) #Names of the groups in HDF5 file.
Run Code Online (Sandbox Code Playgroud)
提取数据
#Get the HDF5 group
group = f[key]
#Checkout what keys are inside that group.
for key in group.keys():
print(key)
data = group[some_key_inside_the_group].value
#Do whatever you want with data
#After you are done
f.close()
Run Code Online (Sandbox Code Playgroud)
小智 7
要将 .hdf5 文件的内容作为数组读取,您可以执行以下操作
> import numpy as np
> myarray = np.fromfile('file.hdf5', dtype=float)
> print(myarray)
Run Code Online (Sandbox Code Playgroud)
小智 7
这是我刚刚编写的一个简单函数,它读取由 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
Run Code Online (Sandbox Code Playgroud)
https://gist.github.com/Attila94/fb917e03b04035f3737cc8860d9e9f9b。
尚未对其进行彻底测试,但对我有用。
使用下面的代码读取数据并将其转换为 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)
Run Code Online (Sandbox Code Playgroud)
将数据集值读入 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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
159183 次 |
| 最近记录: |