neural-network - 可视化自动编码器输出
问题描述
我提出了一个非常菜鸟的问题,但我被困住了……我用 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)。
谁能告诉我如何从重建的张量中获得图像?
太感谢了!
解决方案
首先,您必须将张量广播到128x28x28
:
reconstructed = x.reshape(128, 1, 28, 28)
然后,您可以使用torchvision的函数将其中一个批处理元素转换为PIL图像。下面将显示第一张图片:
import torchvision.transforms as T
img = T.ToPILImage()(reconstructed[0])
img.show()