Keras加载VGG16时include_top=False为何缺失层形状?
为什么Keras中VGG16设置include_top=False时看不到层的具体形状?
先看我在Keras中加载模型并打印摘要的代码:
model = applications.VGG16(include_top=True) print(model.summary())
此时能看到所有层的具体形状:
Layer (type) Output Shape Param # ================================================================= input_1 (InputLayer) (None, 224, 224, 3) 0 _________________________________________________________________ block1_conv1 (Conv2D) (None, 224, 224, 64) 1792 _________________________________________________________________ block1_conv2 (Conv2D) (None, 224, 224, 64) 36928 _________________________________________________________________ block1_pool (MaxPooling2D) (None, 112, 112, 64) 0 ...
但当设置include_top=False时,所有层的空间维度都变成了None:
Layer (type) Output Shape Param # ================================================================= input_1 (InputLayer) (None, None, None, 3) 0 _________________________________________________________________ block1_conv1 (Conv2D) (None, None, None, 64) 1792 _________________________________________________________________ block1_conv2 (Conv2D) (None, None, None, 64) 36928 _________________________________________________________________ block1_pool (MaxPooling2D) (None, None, None, 64) 0 ...
请问这是什么原因?是否是我的操作出现了问题?
解答
这完全不是你的操作问题,是Keras预训练模型的设计逻辑导致的,具体原因如下:
- 当
include_top=True时,VGG16会附带针对ImageNet数据集训练的顶部全连接层,而全连接层的输入维度是固定的(对应ImageNet标准的224×224输入尺寸),所以整个网络的输入和各层输出形状都被固定死了,summary()自然能显示具体的空间维度数值。 - 当
include_top=False时,模型被设计成支持任意合法尺寸的输入图像(只要输入尺寸能被后续池化操作的步长整除),Keras用None来表示这种可变的空间维度,这样你可以根据自己的任务需求传入不同大小的输入(比如300×300、512×512等),模型都能正常处理。 - 如果想要在
include_top=False时看到具体的层形状,你只需要在加载模型时显式指定input_shape参数即可,比如:
这样网络的输入维度被固定,各层的输出形状也会显示具体的数值。model = applications.VGG16(include_top=False, input_shape=(224, 224, 3)) print(model.summary())
内容的提问来源于stack exchange,提问作者corwin
相关产品推荐
相关产品推荐

