DL 8
DL 8
Program:
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
from torchvision.utils import save_image
import os
# Hyperparameters
latent_dim = 100 # Size of the latent vector for the generator input
img_size = 28 # Image size (28x28 for MNIST)
batch_size = 64
num_epochs = 100
learning_rate = 0.0002
# Load dataset
train_dataset = torchvision.datasets.MNIST(root='./data', train=True, transform=transform, download=True)
train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True)
# Discriminator network
class Discriminator(nn.Module):
def __init__(self):
super(Discriminator, self).__init__()
self.model = nn.Sequential(
nn.Linear(img_size * img_size, 256),
nn.LeakyReLU(0.2),
nn.Linear(256, 128),
nn.LeakyReLU(0.2),
nn.Linear(128, 1),
nn.Sigmoid()
)
# Generator network
class Generator(nn.Module):
def __init__(self, latent_dim):
super(Generator, self).__init__()
self.model = nn.Sequential(
nn.Linear(latent_dim, 128),
nn.LeakyReLU(0.2),
nn.Linear(128, 256),
nn.LeakyReLU(0.2),
nn.Linear(256, img_size * img_size),
nn.Tanh()
)
# Training loop
for epoch in range(num_epochs):
for i, (imgs, _) in enumerate(train_loader):
real_imgs = imgs.to(device)
batch_size = real_imgs.size(0) # Get actual batch size for the last incomplete batch if any
# Train Discriminator
real_outputs = discriminator(real_imgs)
d_loss_real = criterion(real_outputs, real_labels)
# Train Generator
gen_labels = torch.ones(batch_size, 1).to(device) # Generator aims for these to be classified as real
fake_outputs = discriminator(fake_imgs)
g_loss = criterion(fake_outputs, gen_labels)
Output: