Auto-encoder for image reconstruction
In this problem, you will design a convolutional auto-encoder network for image reconstruction. You will use the CIFAR10 dataset for training and testing. Note that Pytorch has
pre-defined data loader for CIFAR10. The input to the auto-encoder will be an image and
you will try to reconstruct the same image as output. You will design just a two block
encoder and a two block decoder. Effectively, your auto-encoder will thus have four convolutional layers. Note that the convolutional layers in decoder will actually be transpose
convolution layers. For all these layers, use a kernel size of 3, stride of 1 and padding of
0. The number of channels in the auto-encoder should be of the following order: (input
channels, output channels) ==> (3,8), (8,8), (8,8), (8,3). For example, the first layer has
an input channels of 3 and output channels of 8. The second layer has an input channel size
of 8 and output channel size of 8 and so on. Make sure to use a suitable activation function
at required places. Use the L2 loss function.
Plot the convergence of the loss function.
Test if the auto-encoder works on the CIFAR10 test set. Visualize 10 inputs with
their corresponding 10 reconstructions.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Below is a detailed solution to the problem using PyTorch. This includes designing the convolutional auto-encoder, training it on the CIFAR10 dataset, plotting the convergence of the loss function, and visualizing inputs with their reconstructions.
Step 1: Install Required Libraries
Ensure you have PyTorch and related libraries installed. You can install them via pip if you haven't already:
bash
pip install torch torchvision matplotlib
Step 2: Import Libraries and Load CIFAR10 Dataset
python
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
import matplotlib.pyplot as plt
import numpy as np
# Define a transform to normalize the data (mean=0.5, std=0.5 for each channel)
transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
# Load CIFAR10 dataset
trainset = datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)
testset = datasets.CIFAR10(root='./data', train=False, download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=64, shuffle=False)
Step 3: Design the Convolutional Auto-encoder
python
class ConvAutoEncoder(nn.Module):
def __init__(self):
super(ConvAutoEncoder, self).__init__()
# Encoder: Two convolutional layers with ReLU activation
self.encoder = nn.Sequential(
# Layer 1: 3 input channels (RGB) -> 8 output channels, kernel size 3x3, stride 1, no padding
nn.Conv2d(3, 8, kernel_size=3, stride=1, padding=0),
nn.ReLU(), # Activation function for introducing non-linearity
# Layer 2: 8 input channels -> 8 output channels, same configuration as above
nn.Conv2d(8, 8, kernel_size=3, stride=1, padding=0)
)
# Decoder: Two transposed convolutional layers with ReLU activation
self.decoder = nn.Sequential(
# Layer 3: 8 input channels -> 8 output channels, kernel size 3x3, stride 1, no padding
nn.ConvTranspose2d(8, 8, kernel_size=3, stride=1, padding=0),
nn.ReLU(), # Activation function for introducing non-linearity
# Layer 4: 8 input channels -> 3 output channels (RGB), same configuration as above
nn.ConvTranspose2d(8, 3, kernel_size=3, stride=1, padding=0, output_padding=0)
)
def forward(self, x):
# First, encode the input
x = self.encoder(x)
# Then, decode the encoded representation to reconstruct the input
x = self.decoder(x)
return x
Step 4: Train the Auto-encoder
python
# Initialize the auto-encoder model
model = ConvAutoEncoder()
# Define the loss function (MSE) and optimizer (Adam with learning rate 0.001)
criterion = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
# Lists to store training and test loss at each epoch for plotting convergence
train_loss = []
test_loss = []
# Training loop for 10 epochs
for epoch in range(10):
running_loss = 0.0
for i, data in enumerate(trainloader, 0):
# Extract input images and discard labels (not needed for auto-encoder)
inputs, _ = data
# Zero the gradients
optimizer.zero_grad()
# Forward pass: Get the reconstructed output
outputs = model(inputs)
# Calculate the loss between original and reconstructed images
loss = criterion(outputs, inputs)
# Backward pass: Compute gradients
loss.backward()
# Update model parameters
optimizer.step()
# Accumulate the loss for this batch
running_loss += loss.item()
# Calculate average training loss for this epoch
train_loss.append(running_loss / (i+1))
print('Epoch %d, Training Loss: %.3f' % (epoch+1, running_loss / (i+1)))
# Calculate test loss for this epoch
model.eval() # Set model to evaluation mode
test_running_loss = 0.0
with torch.no_grad(): # Disable gradient computation for testing
for i, data in enumerate(testloader, 0):
inputs, _ = data
outputs = model(inputs)
loss = criterion(outputs, inputs)
test_running_loss += loss.item()
test_loss.append(test_running_loss / (i+1))
print('Epoch %d, Test Loss: %.3f' % (epoch+1, test_running_loss / (i+1)))
model.train() # Set model back to training mode
Step 5: Plot Convergence of Loss Function
python
# Plot training and test loss over epochs
plt.plot(range(1, len(train_loss)+1), train_loss, label='Training Loss')
plt.plot(range(1, len(test_loss)+1), test_loss, label='Test Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.title('Convergence of Loss Function')
plt.legend()
plt.show()
Step 6: Visualize Inputs with Reconstructions
python
# Set model to evaluation mode for inference
model.eval()
# Get a batch of test images
with torch.no_grad():
dataiter = iter(testloader)
images, _ = dataiter.next()
# Reconstruct the images using the trained auto-encoder
outputs = model(images)
# Plot the first 10 original images and their reconstructions
fig, axs = plt.subplots(2, 10, figsize=(20, 4))
for i in range(10):
# Plot original image
axs[0, i].imshow(np.transpose(images[i].numpy(), (1, 2, 0)))
axs[0, i].axis('off')
# Plot reconstructed image
axs[1, i].imshow(np.transpose(outputs[i].numpy(), (1, 2, 0)))
axs[1, i].axis('off')
plt.show()
This solution covers all aspects of the problem statement, from designing and training the convolutional auto-encoder to visualizing the input images and their reconstructions. The loss function's convergence plot provides insight into how the model's performance improves over epochs.