我是 PyTorch 的新手,想要制作一个带有 255x255 RGB 图像的简单自动编码器来使用它,但是输出形状与输入形状不同。
这是模型
class AutoEncoder(nn.Module):
def __init__(self) -> None:
super().__init__()
self.encoder = nn.Sequential(
nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, padding=1),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2),
nn.Conv2d(in_channels=32, out_channels=128, kernel_size=3, padding=1),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2)
)
self.decoder = nn.Sequential(
nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, padding=1),
nn.ReLU(),
nn.ConvTranspose2d(in_channels=128, out_channels=32, kernel_size=3, output_padding=1),
nn.ReLU(),
nn.ConvTranspose2d(in_channels=32, out_channels=3, kernel_size=3, output_padding=1),
nn.Sigmoid()
)
def forward(self, x):
x = self.encoder(x)
x = self.decoder(x)
return x
这是 torchsummary 包给出的形状
----------------------------------------------------------------
Layer (type) Output Shape Param #
================================================================
Conv2d-1 [-1, 32, 255, 255] 896
ReLU-2 [-1, 32, 255, 255] 0
MaxPool2d-3 [-1, 32, 127, 127] 0
Conv2d-4 [-1, 128, 127, 127] 36,992
ReLU-5 [-1, 128, 127, 127] 0
MaxPool2d-6 [-1, 128, 63, 63] 0
Conv2d-7 [-1, 128, 63, 63] 147,584
ReLU-8 [-1, 128, 63, 63] 0
ConvTranspose2d-9 [-1, 32, 66, 66] 36,896
ReLU-10 [-1, 32, 66, 66] 0
ConvTranspose2d-11 [-1, 3, 69, 69] 867
Sigmoid-12 [-1, 3, 69, 69] 0
我从另一篇文章中看到,解码器部分中的
output_padding
选项有助于输出形状,但它对我不起作用。
我不知道问题可能是什么,来自 Tensorflow,我会使用 Upscale 层,但从我所看到的来看,这不是在 PyTorch 中执行此操作的方法。
有人可以向我解释为什么我的形状与我当前的模型不同吗?谢谢
控制输入放大的主要参数是
stride=
。将 stride=2
设置为 kernel_size=2
将使输入大小恰好加倍。
在您的情况下,将
stride=2
与 kernel_size=3
一起使用,可以对每个上卷积层进行 加倍 + 1 大小转换。第一层将产生大小为 2 x 63 + 1 = 127
的输出,第二层将产生 2 x 127 + 1 = 255
。
示例:
x = torch.rand(1, 128, 63, 63) #the ouput from Conv2d-7 is shaped (63, 63)
x = nn.ConvTranspose2d(128, 32, kernel_size=3, stride=2)(x) #2h + 1 upconv
print(x.shape)
#out> torch.Size([1, 32, 127, 127])
x = nn.ConvTranspose2d(32, 3, kernel_size=3, stride=2)(x) #2h + 1 upconv
print(x.shape)
#out> torch.Size([1, 3, 255, 255])