在 Keras 中,Conv2DTranspose 和 Conv2D 有什么区别

In Keras what is the difference between Conv2DTranspose and Conv2D

我目前正在使用 Tensorflow 2 和 Keras 构建 GAN,并注意到许多用于生成器和鉴别器的现有神经网络在 Keras 中使用 Conv2D 和 Conv2DTranspose。

我正在努力寻找可以从功能上解释两者之间差异的内容。谁能解释一下在 Keras 中制作 NN 的这两个不同选项是什么意思?

Conv2D对输入应用卷积运算,相反,Conv2DTranspose对输入应用反卷积运算。

例如:

x = tf.random.uniform((1,3,3,1))
conv2d = tf.keras.layers.Conv2D(1,2)(x)
print(conv2d.shape)
# (1, 2, 2, 1)
conv2dTranspose = tf.keras.layers.Conv2DTranspose(1,2)(x)
print(conv2dTranspose.shape)
# (1, 4, 4, 1)

Conv2D主要用于检测特征,例如,在自动编码器模型的编码器部分,它可能会缩小你的输入形状。
相反,Conv2DTranspose 用于创建特征,例如,在用于构建图像的自动编码器模型的解码器部分。正如您在上面的代码中看到的,它使输入形状变大了。

例如:

kernel = tf.constant_initializer(1.)
x = tf.ones((1,3,3,1))
conv = tf.keras.layers.Conv2D(1,2, kernel_initializer=kernel)
y = tf.ones((1,2,2,1))
de_conv = tf.keras.layers.Conv2DTranspose(1,2, kernel_initializer=kernel)

conv_output = conv(x)
print("Convolution\n---------")
print("input  shape:",x.shape)
print("output shape:",conv_output.shape)
print("input  tensor:",np.squeeze(x.numpy()).tolist())
print("output tensor:",np.around(np.squeeze(conv_output.numpy())).tolist())
'''
Convolution
---------
input  shape: (1, 3, 3, 1)
output shape: (1, 2, 2, 1)
input  tensor: [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]]
output tensor: [[4.0, 4.0], [4.0, 4.0]]
'''
de_conv_output = de_conv(y)
print("De-Convolution\n------------")
print("input  shape:",y.shape)
print("output shape:",de_conv_output.shape)
print("input  tensor:",np.squeeze(y.numpy()).tolist())
print("output tensor:",np.around(np.squeeze(de_conv_output.numpy())).tolist())
'''
De-Convolution
------------
input  shape: (1, 2, 2, 1)
output shape: (1, 3, 3, 1)
input  tensor: [[1.0, 1.0], [1.0, 1.0]]
output tensor: [[1.0, 2.0, 1.0], [2.0, 4.0, 2.0], [1.0, 2.0, 1.0]]
'''

如果您想知道如何 Conv2DTranspose 放大输入,请看这里: