【问题标题】:Pytorch Conv2d Autoencoder Output ShapePytorch Conv2d 自动编码器输出形状
【发布时间】:2021-03-16 18:31:54
【问题描述】:

我构建了波纹管卷积自动编码器,并尝试对其进行调整以在不增加损失的情况下获得 [NxHxW] = 1024 的编码器输出形状 (x_encoder)。目前我的输出形状是 [4, 64, 64] 有什么想法吗?

# define the NN architecture
class ConvAutoencoder(nn.Module):
    def __init__(self):
        super(ConvAutoencoder, self).__init__()
        ## encoder layers ##
        # conv layer (depth from in --> 16), 3x3 kernels
        self.conv1 = nn.Conv2d(1, 16, 3, padding=1)  
        # conv layer (depth from 16 --> 4), 3x3 kernels
        self.conv2 = nn.Conv2d(16, 4, 3, padding=1)
        # pooling layer to reduce x-y dims by two; kernel and stride of 2
        self.pool = nn.MaxPool2d(2, 2)
        
        ## decoder layers ##
        ## a kernel of 2 and a stride of 2 will increase the spatial dims by 2
        self.t_conv1 = nn.ConvTranspose2d(4, 16, 2, stride=2)
        self.t_conv2 = nn.ConvTranspose2d(16, 1, 2, stride=2)

    def forward(self, x):
        ## encode ##
        # add hidden layers with relu activation function
        # and maxpooling after
        x = F.relu(self.conv1(x))
        x = self.pool(x)
        # add second hidden layer
        x = F.relu(self.conv2(x))
        x = self.pool(x)  # compressed representation
        x_encoder = x
        ## decode ##
        # add transpose conv layers, with relu activation function
        x = F.relu(self.t_conv1(x))
        # output layer (with sigmoid for scaling from 0 to 1)
        x = F.sigmoid(self.t_conv2(x))
                
        return x, x_encoder
 

【问题讨论】:

  • 只用两个卷积层是不可能得到 1024*1024 的形状的。
  • @planet_pluto 抱歉不是 1024x1024,例如 [1,32,32] 或 [16,8,8] 可以视为 1024。

标签: pytorch artificial-intelligence conv-neural-network autoencoder


【解决方案1】:

假设 x_encoder 的形状为(torch.Size([1, 4, 64, 64]),这应该可以工作。您可以添加一个转换。步幅设置为 2 或 Conv 的层。层后跟一个池化层。检查下面的代码:

# conv layer (depth from in --> 16), 3x3 kernels
self.conv1 = nn.Conv2d(1, 16, 3, padding=1)  
# conv layer (depth from 16 --> 4), 3x3 kernels
self.conv2 = nn.Conv2d(16, 4, 3, padding=1)
# pooling layer to reduce x-y dims by two; kernel and stride of 2
self.pool = nn.MaxPool2d(2, 2)

# The changes
self.conv3 = nn.Conv2d(4, 1, 1, 2)

# or 
self.conv3 = nn.Conv2d(4, 1, 1)
self.maxpool2d = nn.MaxPool2d((2, 2))

【讨论】:

  • 我试了一下,损失剧增!
  • 您的数据是否已标准化,您尝试使用的损失函数是什么?
  • 不,我的损失是 nn.BCELoss()
【解决方案2】:

如果你想保持参数的数量,添加nn.AdaptiveAvgPool2d((N, H, W))nn.AdaptiveMaxPool2d((N, H, W))layer,代替池化层(self.pool)可以强制解码器的输出具有形状[NxHxW] .

【讨论】:

  • 是的,但是解码器输出会相应改变,与原始图像形状不同,无法训练模型。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-03
  • 2021-07-10
  • 1970-01-01
  • 1970-01-01
  • 2019-10-19
  • 2020-12-10
  • 1970-01-01
相关资源
最近更新 更多