首页 > 解决方案 > 如何在tensorflow或keras的h5模型中查找特定层的步幅/填充信息

问题描述

我一直致力于从 h5 文件中提取卷积层信息,其中包括神经网络模型。我已经能够在 h5 文件中提取有关卷积层数的信息,但我看不到获取有关步幅大小或填充信息的方法。我一直在使用 h5py 来读取 h5 模型。

这是我用来在 h5 中查找卷积层数和权重矩阵的代码

f = h5py.File(weight_file_path)
layers_counter=0
if len(f.attrs.items()):
        print("{} contains: ".format(weight_file_path))
        print("Root attributes:")
        for layer, g in f.items():
           print("  {}".format(layer))
           print("    Attributes:")
           for key, value in g.attrs.items():
               print("      {}: {}".format(key, value))
               print("    Dataset:")
               for p_name in g.keys():
                   param = g[p_name]
                   matrix=param.value #It will be weights matrix
                   matrix_size=a.shape     #It is matrix size
                   if len(matrix_size)>3:
                       layers_counter=layers_counter+1

执行后,layers_counter将有多个卷积层。

标签: tensorflowkerash5py

解决方案


模型配置作为根数据集的属性存储为 HDF5 文件中的 JSON,您可以使用以下代码获取它:

import h5py
import json

model_h5 = h5py.File(filename, 'r')

model_config = model_h5["/"].attrs["model_config"]
config_dict = json.loads(model_config)

然后,您可以索引config_dict以获取所需的配置参数,例如,config_dict["config"]["layers"][1]["config"]["strides"]用于第一个卷积层。


推荐阅读