Autoencoder
1. Introduction
An autoencoder is a type of neural network used for unsupervised learning. It learns to
compress data (encode) and then reconstruct the original input (decode). Autoencoders are
widely used in image compression, denoising, and feature extraction.
2. Data Preparation Module
Purpose: Loads and preprocesses images for training.
Code:
import torch
import [Link] as nn
import [Link] as optim
import [Link] as transforms
import [Link] as datasets
from [Link] import DataLoader
# Hyperparameters
batch_size = 32
learning_rate = 0.001
num_epochs = 5
image_size = 128
# Data Transformations
transform = [Link]([
[Link]((image_size, image_size)), # Resize images to 128x128
[Link](), # Convert images to tensor (0-1 range)
])
# Load Dataset
train_dataset = [Link](root='Data/train', transform=transform)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
3. Encoder Module
Purpose: Compresses the image into a smaller latent representation.
Code:
class Encoder([Link]):
def __init__(self):
super(Encoder, self).__init__()
[Link] = [Link](
nn.Conv2d(3, 64, kernel_size=3, stride=2, padding=1), [Link](),
nn.Conv2d(64, 128, kernel_size=3, stride=2, padding=1), [Link](),
nn.Conv2d(128, 256, kernel_size=3, stride=2, padding=1), [Link](),
)
def forward(self, x):
return [Link](x)
4. Decoder Module
Purpose: Reconstructs the original image from the encoded representation.
Code:
class Decoder([Link]):
def __init__(self):
super(Decoder, self).__init__()
[Link] = [Link](
nn.ConvTranspose2d(256, 128, kernel_size=3, stride=2, padding=1,
output_padding=1), [Link](),
nn.ConvTranspose2d(128, 64, kernel_size=3, stride=2, padding=1,
output_padding=1), [Link](),
nn.ConvTranspose2d(64, 3, kernel_size=3, stride=2, padding=1, output_padding=1),
[Link]()
)
def forward(self, x):
return [Link](x)
5. Autoencoder Module
Purpose: Combines the encoder and decoder into a single model.
Code:
class Autoencoder([Link]):
def __init__(self):
super(Autoencoder, self).__init__()
[Link] = Encoder()
[Link] = Decoder()
def forward(self, x):
encoded = [Link](x)
decoded = [Link](encoded)
return encoded, decoded
6. Training Module
Purpose: Trains the autoencoder using MSE loss.
Code:
device = 'cuda' if [Link].is_available() else 'cpu'
autoencoder = Autoencoder().to(device)
criterion = [Link]()
optimizer = [Link]([Link](), lr=learning_rate)
print("Training Autoencoder...")
for epoch in range(num_epochs):
total_loss = 0
for images, _ in train_loader:
images = [Link](device)
optimizer.zero_grad()
encoded, decoded = autoencoder(images)
loss = criterion(decoded, images)
[Link]()
[Link]()
total_loss += [Link]()
print(f"Epoch [{epoch + 1}/{num_epochs}], Loss: {total_loss / len(train_loader):.4f}")
7. GUI Interface (Gradio)
Purpose: Provides a web interface for users to upload images and see reconstructions.
Code:
import gradio as gr
from PIL import Image
def reconstruct_image(img):
img = [Link]("RGB")
img = transform(img).unsqueeze(0).to(device)
with torch.no_grad():
encoded, reconstructed = autoencoder(img)
original_np = [Link](0).permute(1, 2, 0).cpu().numpy()
reconstructed_np = [Link](0).permute(1, 2, 0).cpu().numpy()
return original_np, reconstructed_np
# Create Gradio Interface
interface = [Link](
fn=reconstruct_image,
inputs=[Link](type="pil"),
outputs=[[Link](type="numpy", label="Original Image"), [Link](type="numpy",
label="Reconstructed Image")],
title="Autoencoder Image Reconstruction",
description="Upload an image to see how the autoencoder reconstructs it."
)
[Link](share=True)