Warm tip: This article is reproduced from serverfault.com, please click

python-添加GlobalAveragePooling2D(在ResNet50之前)

(python - Add GlobalAveragePooling2D (before ResNet50))

发布于 2020-12-02 10:31:37

我正在尝试使用ResNet50将图像分类为6类,并且我想在使用图像训练ResNet50模型之前减小图像的尺寸。为此,我开始使用keras中的模型创建ResNet50模型:

ResNet = ResNet50(
    include_top= None, weights='imagenet', input_tensor=None, input_shape=([64, 109, 3]),
    pooling=None, classes=6)

然后,我创建了一个包含ResNet50的顺序模型,但在使用ResNet50之前添加了一些用于分类的最终层以及用于降维的第一层:(关于输入形状:我使用的图像的尺寸为128x217,第3层为用于ResNet所需的渠道)

model = models.Sequential()
model.add(GlobalAveragePooling2D(input_shape = ([128, 217, 3])))
model.add(ResNet)
model.add(GlobalAveragePooling2D())
model.add(Dense(units=512, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(units=256, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(units=6, activation='softmax'))

但这是行不通的,因为第一个全局平均池之后的尺寸与Resnet中的输入形状不匹配,我得到的错误是:

WARNING:tensorflow:Model was constructed with shape (None, 64, 109, 3) for input Tensor("input_6:0", shape=(None, 64, 109, 3), dtype=float32), but it was called on an input with incompatible shape (None, 3).
ValueError: Input 0 of layer conv1_pad is incompatible with the layer: expected ndim=4, found ndim=2. Full shape received: [None, 3]

我想我理解了问题所在,但是我不知道如何解决它,因为(None,3)对于ResNet50来说不是有效的输入形状。我怎样才能解决这个问题?谢谢!:)

Questioner
user14484895
Viewed
0
Adrian Stępniak 2020-12-02 21:36:43

你首先应该了解GlobalAveragePooling的实际作用。输入后不能立即应用此图层,因为它将仅给出每个通道的所有图像的最大值(在你的情况下为3个值,因为你有3个通道)。

你必须使用另一种方法来减小图像的大小(例如,简单地转换为较小的大小)。