打印出网络架构中每一层的形状

print out the shape of each layer in the net architecture

在Keras中,我们可以这样定义网络。有没有办法在每一层之后输出形状。例如,我想在定义 inputs 的行之后打印出 inputs 的形状,然后在定义 conv1 的行之后打印出 conv1 的形状,等等。

inputs = Input((1, img_rows, img_cols))
conv1 = Convolution2D(64, 3, 3, activation='relu', init='lecun_uniform', W_constraint=maxnorm(3), border_mode='same')(inputs)
conv1 = Convolution2D(64, 3, 3, activation='relu', init='lecun_uniform', W_constraint=maxnorm(3), border_mode='same')(conv1)
pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)

conv2 = Convolution2D(128, 3, 3, activation='relu', init='lecun_uniform', W_constraint=maxnorm(3), border_mode='same')(pool1)
conv2 = Convolution2D(128, 3, 3, activation='relu', init='lecun_uniform', W_constraint=maxnorm(3), border_mode='same')(conv2)
pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)

只需使用 model.summary(),即可获得漂亮的打印效果。

如果一个层只有一个节点(即如果它不是共享层),您可以通过以下方式获取其输入张量、输出张量、输入形状和输出形状:layer.input_shape

from keras.utils.layer_utils import layer_from_config

config = layer.get_config()
layer = layer_from_config(config)

来源:https://keras.io/layers/about-keras-layers/

这可能是最简单的方法:

model.layers[layer_of_interest_index].output_shape

要打印完整模型及其所有依赖项,您还可以在此处查看:https://keras.io/visualization/

我使用此命令将我的模型可视化保存为 png:

from keras.utils.visualize_util import plot
plot(model, to_file='model.png')

如果你只想打印图层形状,你可以这样做:

layer = model.layers[-1]
print(layer.output._keras_shape)

打印:(None, 1, 224, 224) # Nr.过滤器、频道、x_dim、y_dim