【问题标题】:Visualize Autoencoder Output可视化自动编码器输出
【发布时间】:2021-03-18 03:25:21
【问题描述】:

我提出了一个非常菜鸟的问题,但我被困住了...... 我用 Pytorch 创建了一个自动编码器,并用典型的 MNIST 数据集等对其进行了训练:

class Autoencoder(nn.Module):
    def __init__(self, **kwargs):
        super().__init__()
        self.encoder_hidden_layer = nn.Linear(
            in_features=kwargs["input_shape"], out_features=kwargs["embedding_dim"]
        )
        self.encoder_output_layer = nn.Linear(
            in_features=kwargs["embedding_dim"], out_features=kwargs["embedding_dim"]
        )
        self.decoder_hidden_layer = nn.Linear(
            in_features=kwargs["embedding_dim"], out_features=kwargs["embedding_dim"]
        )
        self.decoder_output_layer = nn.Linear(
            in_features=kwargs["embedding_dim"], out_features=kwargs["input_shape"]
        )

    def forward(self, features):
        activation = self.encoder_hidden_layer(features)
        activation = torch.relu(activation)

        code = self.encoder_output_layer(activation)
        code = torch.relu(code)
        
        activation = self.decoder_hidden_layer(code)
        activation = torch.relu(activation)

        activation = self.decoder_output_layer(activation)
        reconstructed = torch.relu(activation)

        return reconstructed

model = Autoencoder(input_shape=784, embedding_dim=128)

criterion = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr=0.0001) 

我现在想要的是可视化重建的图像,但我不知道该怎么做。我知道这很简单,但我找不到方法。我知道输出的形状是[128,784],因为batch_size 是128,而784 是28x28(x1channel)。

谁能告诉我如何从重建的张量中获取图像?

非常感谢!

【问题讨论】:

    标签: neural-network pytorch data-visualization autoencoder


    【解决方案1】:

    首先你必须将张量广播到128x28x28

    reconstructed = x.reshape(128, 1, 28, 28)
    

    然后,您可以使用torchvision 的函数将其中一个批处理元素转换为PIL 图像。下面将显示第一张图片:

    import torchvision.transforms as T
    img = T.ToPILImage()(reconstructed[0])
    img.show()
    

    【讨论】:

    • 非常感谢!太简单!现在还有一个问题:如何在 Jupyter Notebook 中显示图像?因为它是在我的 PC 的应用程序中打开的。而且,如何每次都显示相同的示例?我的意思是,对于每个 epoch,看看自动编码器是如何在同一张图像上改进的。非常感谢!!
    • 这个stackoverflow.com/a/26649884/6331369 可以让你在 Jupyter 中预览你的图像。您可以在每个时期打开数组中第一批的第一张图像。最后,您将能够显示该数组的每个元素。
    • 再次感谢您!你太棒了!
    猜你喜欢
    • 2019-06-11
    • 1970-01-01
    • 2021-04-23
    • 1970-01-01
    • 2021-03-16
    • 2018-04-02
    • 2011-09-15
    • 2019-10-01
    • 1970-01-01
    相关资源
    最近更新 更多