gpt4 book ai didi

Pytorch 卷积自动编码器

转载 作者:行者123 更新时间:2023-12-04 01:49:38 30 4
gpt4 key购买 nike

如何构建卷积自动编码器的解码器部分?假设我有这个

(输入 -> conv2d -> maxpool2d -> maxunpool2d -> convTranspose2d -> 输出):

# CIFAR images shape = 3 x 32 x 32

class ConvDAE(nn.Module):
def __init__(self):
super().__init__()

# input: batch x 3 x 32 x 32 -> output: batch x 16 x 16 x 16
self.encoder = nn.Sequential(
nn.Conv2d(3, 16, 3, stride=1, padding=1), # batch x 16 x 32 x 32
nn.ReLU(),
nn.BatchNorm2d(16),
nn.MaxPool2d(2, stride=2) # batch x 16 x 16 x 16
)

# input: batch x 16 x 16 x 16 -> output: batch x 3 x 32 x 32
self.decoder = nn.Sequential(
# this line does not work
# nn.MaxUnpool2d(2, stride=2, padding=0), # batch x 16 x 32 x 32
nn.ConvTranspose2d(16, 16, 3, stride=2, padding=1, output_padding=1), # batch x 16 x 32 x 32
nn.ReLU(),
nn.BatchNorm2d(16),
nn.ConvTranspose2d(16, 3, 3, stride=1, padding=1, output_padding=0), # batch x 3 x 32 x 32
nn.ReLU()
)

def forward(self, x):
print(x.size())
out = self.encoder(x)
print(out.size())
out = self.decoder(out)
print(out.size())
return out

Pytorch 特定问题: 为什么我不能在解码器部分使用 MaxUnpool2d。这给了我以下错误:

TypeError: forward() missing 1 required positional argument: 'indices'

以及概念性问题:我们是否应该在解码器中执行与在编码器中执行的操作相反的操作?我看到了一些实现,它们似乎只关心解码器输入和输出的维度。 Herehere是一些例子。

最佳答案

对于问题的 torch 部分,unpool 模块具有从池化模块返回的索引作为必需的位置参数,这些索引将通过 return_indices=True 返回。所以你可以做

class ConvDAE(nn.Module):
def __init__(self):
super().__init__()

# input: batch x 3 x 32 x 32 -> output: batch x 16 x 16 x 16
self.encoder = nn.Sequential(
nn.Conv2d(3, 16, 3, stride=1, padding=1), # batch x 16 x 32 x 32
nn.ReLU(),
nn.BatchNorm2d(16),
nn.MaxPool2d(2, stride=2, return_indices=True)
)

self.unpool = nn.MaxUnpool2d(2, stride=2, padding=0)

self.decoder = nn.Sequential(
nn.ConvTranspose2d(16, 16, 3, stride=2, padding=1, output_padding=1),
nn.ReLU(),
nn.BatchNorm2d(16),
nn.ConvTranspose2d(16, 3, 3, stride=1, padding=1, output_padding=0),
nn.ReLU()
)

def forward(self, x):
print(x.size())
out, indices = self.encoder(x)
out = self.unpool(out, indices)
out = self.decoder(out)
print(out.size())
return out

至于问题的一般部分,我认为最先进的技术不是使用对称解码器部分,因为已经证明 devonvolution/transposed convolution 会产生棋盘效应,并且许多方法倾向于使用上采样模块反而。您将通过 PyTorch channel 更快地找到更多信息。

关于Pytorch 卷积自动编码器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53858626/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com