Skip to main content
 首页 » 编程设计

python之合并 hdf5 检查点文件

2024年10月01日9JustinYoung

我使用以下代码合并所有由 keras 生成的 hdf5 文件。

import h5py 
 
output_file = h5py.File('output.h5', 'w') 
 
#keep track of the total number of rows 
total_rows = 0 
import os 
 
file_list = os.listdir(os.getcwd()) 
 
for n, f in enumerate(file_list): 
  your_data = h5py.File(n, 'r+') 
  total_rows = total_rows + your_data.shape[0] 
  total_columns = your_data.shape[1] 
 
  if n == 0: 
    #first file; create the dummy dataset with no max shape 
    create_dataset = output_file.create_dataset("Name", (total_rows, total_columns), maxshape=(None, None)) 
    #fill the first section of the dataset 
    create_dataset[:,:] = your_data 
    where_to_start_appending = total_rows 
 
  else: 
    #resize the dataset to accomodate the new data 
    create_dataset.resize(total_rows, axis=0) 
    create_dataset[where_to_start_appending:total_rows, :] = your_data 
    where_to_start_appending = total_rows 
 
output_file.close() 

它抛出以下错误。

expected str bytes or osPathLike objects.

为什么会这样?我怎样才能合并来自 keras 的所有 hdf5 数据集?

请您参考如下方法:

您正在像处理数据集一样处理 HDF5- 文件。

f = h5py.File(n, 'r+') 
your_data=f["Name_of_Dataset"] #open a dataset 
total_rows = total_rows + your_data.shape[0] 

如果你不知道数据集的名称,你可以按如下方式获取它

Dataset_Names=f.keys() 

您还可以通过根据您的访问模式设置 block 大小来提高性能。现在您拥有了自动分块功能,如果您使用可调整大小的数据集,它会默认启用。