如何在tensorflow或keras的h5模型中查找特定层的stride/padding信息

How to find stride/padding information of a specific layer in h5 model of tensorflow or keras

我一直致力于从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会有卷积层数

模型配置作为根数据集的属性存储在 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"]

我一直在寻找完全相同的东西,这是我实现它的方式:

from tensorflow.keras.applications.resnet50 import ResNet50
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.resnet50 import preprocess_input, decode_predictions
import numpy as np

model = ResNet50(weights='resnet50_weights_tf_dim_ordering_tf_kernels.h5')


for layer in model.layers:
    if "filters" in model.get_layer(name = layer.name).get_config().keys():
        print("layer name: ",layer.name)
        print("strides: ",model.get_layer(name = layer.name).get_config()['strides'])
        print("padding: ",model.get_layer(name = layer.name).get_config()['padding'])

其中 returns 模型中每个卷积层的所有填充和步长,例如 resnet50 的第 1 层:

layer name:  conv1
strides:  (2, 2)
padding:  valid

还可以通过以下方式查看所有配置:

print("conv configuration: ",model.get_layer(name = layer.name).get_config())

您也可以使用 model.summary() 获取图层名称并将其替换为名称参数,例如:

print("CONFIG: ",model.get_layer(name = "conv1").get_config())

{'name': 'conv1', 'trainable': True, 'dtype': 'float32', 'filters': 64, 'kernel_size': (7, 7), 'strides': (2, 2), 'padding': 'valid', 'data_format': 'channels_last', 'dilation_rate': (1, 1), 'activation': 'linear', 'use_bias': True, 'kernel_initializer': {'class_name': 'VarianceScaling', 'config': {'scale': 2.0, 'mode': 'fan_in', 'distribution': 'truncated_normal', 'seed': None, 'dtype': 'float32'}}, 'bias_initializer': {'class_name': 'Zeros', 'config': {'dtype': 'float32'}}, 'kernel_regularizer': None, 'bias_regularizer': None, 'activity_regularizer': None, 'kernel_constraint': None, 'bias_constraint': None}