python - 用于构建自动编码器的 keras.Flatten 的逆

标签 python keras autoencoder

我的目标是构建一个卷积自动编码器,将输入图像编码为大小为 (10,1) 的平面向量。 .我遵循了 keras 的示例 documentation并根据我的目的对其进行了修改。不幸的是,模型是这样的:

input_img = Input(shape=(28, 28, 1))

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 = Flatten()(x)

encoded = Dense(units = 10, activation = 'relu')(x)


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

autoencoder = Model(input_img, decoded)

给我
ValueError: Input 0 is incompatible with layer conv2d_39: expected ndim=4, found ndim=2

我想我应该在我的解码器中添加一些层来反转 Flatten 的效果,但不确定是哪一层。你能帮我吗?

最佳答案

为什么要为向量提供特定的 (10,1) 形状?
然后您尝试使用大小为 3x3 的内核对其进行卷积,这实际上没有意义。

卷积层采用的形状具有高度、宽度和 channel 。密集层的输出必须重新整形,这可以通过 Reshape 层来完成。
然后,您可以使用单 channel 将其整形为例如 5x2。

encoded = Reshape((5, 2, 1))(encoded)

关于python - 用于构建自动编码器的 keras.Flatten 的逆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61711898/

相关文章:

python - 如何在 Python 中启动后台进程?

python - 'generator' 类型的对象没有 len()

python - 如何解决 "ValueError: A ` Concatenate` 层需要具有匹配形状的输入(除了连接轴之外)”?

python - 如何将 Keras Sequential CNN 的训练数据转换为正确的张量形状?

lstm - 注意力对自动编码器有意义吗?

python - 通过在列表的开头而不是尾部添加来扩展 python 列表的最佳解决方案?

python - python脚本中使用awk时的格式问题

python - 尝试复制 Python 结果时 Keras 错误

python - 如何将 2 个 keras 模型的输出连接到一个单独的层?

python - 自定义 keras 回调和改变变分自动编码器损失函数中正则化项的权重 (beta)