【问题标题】:Keras: Specify shape of output correctly (for Convolutional Autoencoder)Keras:正确指定输出的形状(用于卷积自动编码器)
【发布时间】:2018-09-12 12:14:43
【问题描述】:

在 Keras 我有模型

input_img = Input(shape=(150, 360, 3))

x = Conv2D(16, (3, 3), activation='relu', padding='same')(input_img)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
encoded = MaxPooling2D((2, 2), padding='same')(x)

# at this point the representation is autoencoder.layers[6].output_shape = (None, 19, 45, 8)

x = Conv2D(8, (3, 3), activation='relu', padding='same')(encoded)
x = UpSampling2D((2, 2))(x)
x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
x = UpSampling2D((2, 2))(x)                                      #10
x = Conv2D(16, (3, 3), activation='relu', padding='same')(x)
x = UpSampling2D((2, 2))(x)                                     
decoded = Conv2D(3, (3, 3), activation='sigmoid', padding='same')(x)

autoencoder = Model(input_img, decoded)
autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')

最终的形状是

autoencoder.layers[13].output_shape
(None, 152, 360, 3)

这并不奇怪,因为层的设置以及我只能使用整数来表示层 MaxPooling2DUpSampling2D 的大小。但是我该如何处理呢?

如何恢复(150, 360, 3)的形状?

【问题讨论】:

    标签: python tensorflow keras autoencoder


    【解决方案1】:

    问题是高度维度 (150) 不能被 8 整除。

    解决方案 1: 这可能不是最好的解决方案,但您可以在最后一个 UpSampling2D 层之后添加一个Cropping2D 层:

    x = UpSampling2D((2, 2))(x)
    x = Cropping2D(cropping=(1, 0))(x)
    decoded = Conv2D(3, (3, 3), activation='sigmoid', padding='same')(x)
    

    通过使用此操作,您基本上是在告诉模型忽略最后一个 UpSampling2D 输出的第一行和最后一行。

    解决方案 2:您也可以使用ZeroPadding2D 填充输入图像,使其高度为 152:

    input_img = Input(shape=(150, 360, 3))
    x = ZeroPadding2D(padding=(1, 0))(input_img)
    x = Conv2D(16, (3, 3), activation='relu', padding='same')(x)
    

    这样,高度尺寸可以被8整除。

    【讨论】:

    • 谢谢 - 是的,我也发现了问题。解决方案是我的烦恼;-)。这听起来像是一个解决方案,但似乎还不理想。具有正确数量的输出神经元的密集层怎么样?也许在中间,在编码之后?
    • 我认为瓶颈中的密集层无济于事(您仍然会遇到同样的问题,因为没有任何整数xx*8=150)。我认为解码器中的裁剪并不是什么大问题(网络会自行发现丢弃的神经元是无用的)。我添加了另一种可能的解决方案,以防它看起来对您更有吸引力。如果你对其中任何一个都不满意,我相信你应该改变架构。
    猜你喜欢
    • 2017-01-04
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 2017-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-08
    相关资源
    最近更新 更多