The Wayback Machine - https://web.archive.org/web/20250304001848/https://www.geeksforgeeks.org/generative-adversarial-network-gan/
Open In App

Generative Adversarial Network (GAN)

Last Updated : 01 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Generative Adversarial Networks (GANs) were introduced by Ian Goodfellow and his colleagues in 2014. GANs are a class of neural networks that autonomously learn patterns in the input data to generate new examples resembling the original dataset.

GAN’s architecture consists of two neural networks:

  1. Generator: creates synthetic data from random noise to produce data so realistic that the discriminator cannot distinguish it from real data.
  2. Discriminator: acts as a critic, evaluating whether the data it receives is real or fake.

They use adversarial training to produce artificial data that is identical to actual data.

Generative-Adverarial-network-Gans


The two networks engage in a continuous game of cat and mouse: the Generator improves its ability to create realistic data, while the Discriminator becomes better at detecting fakes. Over time, this adversarial process leads to the generation of highly realistic and high-quality data.

Detailed Architecture of GANs

Let’s explore the generator and discriminator model of GANs in detail:

1. Generator Model

The generator is a deep neural network that takes random noise as input to generate realistic data samples (e.g., images or text). It learns the underlying data distribution by adjusting its parameters through backpropagation.

The generator’s objective is to produce samples that the discriminator classifies as real. The loss function is:

[Tex]J_{G} = -\frac{1}{m} \Sigma^m _{i=1} log D(G(z_{i}))[/Tex]

Where,

  • [Tex]J_G[/Tex] measure how well the generator is fooling the discriminator.
  • log [Tex]D(G(z_i) )[/Tex]represents log probability of the discriminator being correct for generated samples.
  • The generator aims to minimize this loss, encouraging the production of samples that the discriminator classifies as real [Tex](log D(G(z_i))[/Tex], close to 1.

2. Discriminator Model

The discriminator acts as a binary classifier, distinguishing between real and generated data. It learns to improve its classification ability through training, refining its parameters to detect fake samples more accurately.

When dealing with image data, the discriminator often employs convolutional layers or other relevant architectures suited to the data type. These layers help extract features and enhance the model’s ability to differentiate between real and generated samples.

The discriminator reduces the negative log likelihood of correctly classifying both produced and real samples. This loss incentivizes the discriminator to accurately categorize generated samples as fake and real samples with the following equation:

[Tex]J_{D} = -\frac{1}{m} \Sigma_{i=1}^m log\; D(x_{i}) – \frac{1}{m}\Sigma_{i=1}^m log(1 – D(G(z_{i}))[/Tex]

  • [Tex]J_D[/Tex] assesses the discriminator’s ability to discern between produced and actual samples.
  • The log likelihood that the discriminator will accurately categorize real data is represented by [Tex]logD(x_i)[/Tex].
  • The log chance that the discriminator would correctly categorize generated samples as fake is represented by [Tex]log⁡(1-D(G(z_i)))[/Tex].

By minimizing this loss, the discriminator becomes more effective at distinguishing between real and generated samples.

MinMax Loss

GANs follow a minimax optimization where the generator and discriminator are adversaries:

[Tex]min_{G}\;max_{D}(G,D) = [\mathbb{E}_{x∼p_{data}}[log\;D(x)] + \mathbb{E}_{z∼p_{z}(z)}[log(1 – D(g(z)))][/Tex]
Where,

  • G is generator network and is D is the discriminator network
  • Actual data samples obtained from the true data distribution [Tex]p_{data}(x) [/Tex] are represented by x.
  • Random noise sampled from a previous distribution [Tex]p_z(z) [/Tex](usually a normal or uniform distribution) is represented by z.
  • D(x) represents the discriminator’s likelihood of correctly identifying actual data as real.
  • D(G(z)) is the likelihood that the discriminator will identify generated data coming from the generator as authentic.

The generator aims to minimize the loss, while the discriminator tries to maximize its classification accuracy.

gans_gfg-(1)

How does a GAN work?

Let’s understand how the generator (G) and discriminator (D) complete to improve each other over time:

1. Generator’s First Move

G takes a random noise vector as input. This noise vector contains random values and acts as the starting point for G’s creation process. Using its internal layers and learned patterns, G transforms the noise vector into a new data sample, like a generated image.

2. Discriminator’s Turn

D receives two kinds of inputs:

  • Real data samples from the training dataset.
  • The data samples generated by G in the previous step.

D’s job is to analyze each input and determine whether it’s real data or something G cooked up. It outputs a probability score between 0 and 1. A score of 1 indicates the data is likely real, and 0 suggests it’s fake.

3. Adversarial Learning

  • If the discriminator correctly classifies real data as real and fake data as fake, it strengthens its ability slightly.
  • If the generator successfully fools the discriminator, it receives a positive update, while the discriminator is penalized.

5. Generator’s Improvement

Every time the discriminator misclassifies fake data as real, the generator learns and improves. Over multiple iterations, the generator produces more convincing synthetic samples.

6. Discriminator’s Adaptation

The discriminator continuously refines its ability to distinguish real from fake data. This ongoing duel between the generator and discriminator enhances the overall model’s learning process.

7. Training Progression

  • As training continues, the generator becomes highly proficient at producing realistic data.
  • Eventually, the discriminator struggles to distinguish real from fake, indicating that the GAN has reached a well-trained state.
  • At this point, the generator can be used to generate high-quality synthetic data for various applications.

Types of GANs

1. Vanilla GAN

Vanilla GAN is the simplest type of GAN. It consists of:

  • A generator and a discriminator, both are built using multi-layer perceptrons (MLPs).
  • The model optimizes its mathematical formulation using stochastic gradient descent (SGD).

While Vanilla GANs serve as the foundation for more advanced GAN models, they often struggle with issues like mode collapse and unstable training.

2. Conditional GAN (CGAN)

Conditional GANs (CGANs) introduce an additional conditional parameter to guide the generation process. Instead of generating data randomly, CGANs allow the model to produce specific types of outputs.

Working of CGANs:

  • A conditional variable (y) is fed into both the generator and the discriminator.
  • This ensures that the generator creates data corresponding to the given condition (e.g., generating images of specific objects).
  • The discriminator also receives the labels to help distinguish between real and fake data.

3. Deep Convolutional GAN (DCGAN)

Deep Convolutional GANs (DCGANs) are among the most popular and widely used types of GANs, particularly for image generation.

What Makes DCGAN Special?

  • Uses Convolutional Neural Networks (CNNs) instead of simple multi-layer perceptrons (MLPs).
  • Max pooling layers are replaced with convolutional stride, making the model more efficient.
  • Fully connected layers are removed, allowing for better spatial understanding of images.

DCGANs have been highly successful in generating high-quality images, making them a go-to choice for deep learning researchers.

4. Laplacian Pyramid GAN (LAPGAN)

Laplacian Pyramid GAN (LAPGAN) is designed to generate ultra-high-quality images by leveraging a multi-resolution approach.

Working of LAPGAN:

  • Uses multiple generator-discriminator pairs at different levels of the Laplacian pyramid.
  • Images are first downsampled at each layer of the pyramid and upscaled again using Conditional GANs (CGANs).
  • This process allows the image to gradually refine details, reducing noise and improving clarity.

Due to its ability to generate highly detailed images, LAPGAN is considered a superior approach for photorealistic image generation.

5. Super Resolution GAN (SRGAN)

Super-Resolution GAN (SRGAN) is specifically designed to increase the resolution of low-quality images while preserving details.

Working of SRGAN:

  • Uses a deep neural network combined with an adversarial loss function.
  • Enhances low-resolution images by adding finer details, making them appear sharper and more realistic.
  • Helps reduce common image upscaling errors, such as blurriness and pixelation.

Implementation of Generative Adversarial Network (GAN) using PyTorch

Let’s explore the implementation of a Generative Adversarial Network (GAN). Our GAN will be trained on the CIFAR-10 dataset to generate realistic images.

Step 1: Importing Required Libraries

First, we import the necessary libraries for building and training our GAN.

Python
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
from torchvision import datasets, transforms
import matplotlib.pyplot as plt
import numpy as np

# Set device
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

The model will utilize a GPU if available; otherwise, it will default to CPU.

Step 2: Defining Image Transformations

We use PyTorch’s transforms to normalize and convert images into tensors before feeding them into the model.

Python
# Define a basic transform
transform = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])

Step 3: Loading the CIFAR-10 Dataset

The CIFAR-10 dataset is loaded with predefined transformations. A DataLoader is created to process the dataset in mini-batches of 32 images, shuffled for randomness.

Python
train_dataset = datasets.CIFAR10(root='./data',\
              train=True, download=True, transform=transform)
dataloader = torch.utils.data.DataLoader(train_dataset, \
                                batch_size=32, shuffle=True)

Step 4: Defining GAN Hyperparameters

Key hyperparameters are defined:

  • latent_dim – Dimensionality of the noise vector.
  • lr – Learning rate of the optimizer.
  • beta1, beta2 – Adam optimizer coefficients.
  • num_epochs – Total training iterations.
Python
# Hyperparameters
latent_dim = 100
lr = 0.0002
beta1 = 0.5
beta2 = 0.999
num_epochs = 10

Step 5: Building the Generator

The generator takes a random latent vector (z) as input and transforms it into an image through convolutional, batch normalization, and upsampling layers. The final output uses Tanh activation to ensure pixel values are within the expected range.

Python
# Define the generator
class Generator(nn.Module):
    def __init__(self, latent_dim):
        super(Generator, self).__init__()

        self.model = nn.Sequential(
            nn.Linear(latent_dim, 128 * 8 * 8),
            nn.ReLU(),
            nn.Unflatten(1, (128, 8, 8)),
            nn.Upsample(scale_factor=2),
            nn.Conv2d(128, 128, kernel_size=3, padding=1),
            nn.BatchNorm2d(128, momentum=0.78),
            nn.ReLU(),
            nn.Upsample(scale_factor=2),
            nn.Conv2d(128, 64, kernel_size=3, padding=1),
            nn.BatchNorm2d(64, momentum=0.78),
            nn.ReLU(),
            nn.Conv2d(64, 3, kernel_size=3, padding=1),
            nn.Tanh()
        )

    def forward(self, z):
        img = self.model(z)
        return img

Step 6: Building the Discriminator

The discriminator is a binary classifier that distinguishes between real and generated images. It consists of convolutional layers, batch normalization, dropout, and LeakyReLU activation to improve learning stability.

Python
# Define the discriminator
class Discriminator(nn.Module):
    def __init__(self):
        super(Discriminator, self).__init__()

        self.model = nn.Sequential(
        nn.Conv2d(3, 32, kernel_size=3, stride=2, padding=1),
        nn.LeakyReLU(0.2),
        nn.Dropout(0.25),
        nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1),
        nn.ZeroPad2d((0, 1, 0, 1)),
        nn.BatchNorm2d(64, momentum=0.82),
        nn.LeakyReLU(0.25),
        nn.Dropout(0.25),
        nn.Conv2d(64, 128, kernel_size=3, stride=2, padding=1),
        nn.BatchNorm2d(128, momentum=0.82),
        nn.LeakyReLU(0.2),
        nn.Dropout(0.25),
        nn.Conv2d(128, 256, kernel_size=3, stride=1, padding=1),
        nn.BatchNorm2d(256, momentum=0.8),
        nn.LeakyReLU(0.25),
        nn.Dropout(0.25),
        nn.Flatten(),
        nn.Linear(256 * 5 * 5, 1),
        nn.Sigmoid()
    )

    def forward(self, img):
        validity = self.model(img)
        return validity

Step 7: Initializing GAN Components

  • Generator and Discriminator are initialized on the available device (GPU or CPU).
  • Binary Cross-Entropy (BCE) Loss is chosen as the loss function.
  • Adam optimizers are defined separately for the generator and discriminator with specified learning rates and betas.
Python
# Define the generator and discriminator
# Initialize generator and discriminator
generator = Generator(latent_dim).to(device)
discriminator = Discriminator().to(device)
# Loss function
adversarial_loss = nn.BCELoss()
# Optimizers
optimizer_G = optim.Adam(generator.parameters()\
                         , lr=lr, betas=(beta1, beta2))
optimizer_D = optim.Adam(discriminator.parameters()\
                         , lr=lr, betas=(beta1, beta2))

Step 8: Training the GAN

  • The discriminator is trained to differentiate between real and fake images.
  • The generator is trained to produce realistic images that fool the discriminator.
  • The loss is backpropagated using Adam optimizers, and the model updates its parameters.
  • Progress tracking: Loss values for both networks are printed, and generated images are displayed every 10 epochs for visual inspection.
Python
# Training loop
for epoch in range(num_epochs):
    for i, batch in enumerate(dataloader):
       # Convert list to tensor
        real_images = batch[0].to(device) 
        # Adversarial ground truths
        valid = torch.ones(real_images.size(0), 1, device=device)
        fake = torch.zeros(real_images.size(0), 1, device=device)
        # Configure input
        real_images = real_images.to(device)

        # ---------------------
        #  Train Discriminator
        # ---------------------
        optimizer_D.zero_grad()
        # Sample noise as generator input
        z = torch.randn(real_images.size(0), latent_dim, device=device)
        # Generate a batch of images
        fake_images = generator(z)

        # Measure discriminator's ability 
        # to classify real and fake images
        real_loss = adversarial_loss(discriminator\
                                     (real_images), valid)
        fake_loss = adversarial_loss(discriminator\
                                     (fake_images.detach()), fake)
        d_loss = (real_loss + fake_loss) / 2
        # Backward pass and optimize
        d_loss.backward()
        optimizer_D.step()

        # -----------------
        #  Train Generator
        # -----------------

        optimizer_G.zero_grad()
        # Generate a batch of images
        gen_images = generator(z)
        # Adversarial loss
        g_loss = adversarial_loss(discriminator(gen_images), valid)
        # Backward pass and optimize
        g_loss.backward()
        optimizer_G.step()
        # ---------------------
        #  Progress Monitoring
        # ---------------------
        if (i + 1) % 100 == 0:
            print(
                f"Epoch [{epoch+1}/{num_epochs}]\
                        Batch {i+1}/{len(dataloader)} "
                f"Discriminator Loss: {d_loss.item():.4f} "
                f"Generator Loss: {g_loss.item():.4f}"
            )
    # Save generated images for every epoch
    if (epoch + 1) % 10 == 0:
        with torch.no_grad():
            z = torch.randn(16, latent_dim, device=device)
            generated = generator(z).detach().cpu()
            grid = torchvision.utils.make_grid(generated,\
                                        nrow=4, normalize=True)
            plt.imshow(np.transpose(grid, (1, 2, 0)))
            plt.axis("off")
            plt.show()

Output:

Epoch [10/10] Batch 1300/1563 Discriminator Loss: 0.4473 Generator Loss: 0.9555
Epoch [10/10] Batch 1400/1563 Discriminator Loss: 0.6643 Generator Loss: 1.0215
Epoch [10/10] Batch 1500/1563 Discriminator Loss: 0.4720 Generator Loss: 2.5027

gan-Geeksforgeeks

GAN Output

We have successfully implemented a GAN in PyTorch and trained it on CIFAR-10. The generator learns to create realistic images, while the discriminator helps in refining them through adversarial training.

Application Of Generative Adversarial Networks (GANs)

  1. Image Synthesis & Generation: GANs generate realistic images, avatars, and high-resolution visuals by learning patterns from training data. They are widely used in art, gaming, and AI-driven design.
  2. Image-to-Image Translation: GANs can transform images between domains while preserving key features. Examples include converting day images to night, sketches to realistic images, or changing artistic styles.
  3. Text-to-Image Synthesis: GANs create visuals from textual descriptions, enabling applications in AI-generated art, automated design, and content creation.
  4. Data Augmentation: GANs generate synthetic data to improve machine learning models, making them more robust and generalizable, especially in fields with limited labeled data.
  5. High-Resolution Image Enhancement: GANs upscale low-resolution images, improving clarity for applications like medical imaging, satellite imagery, and video enhancement.

Advantages of GAN

The advantages of the GANs are as follows:

  1. Synthetic data generation: GANs can generate new, synthetic data that resembles some known data distribution, which can be useful for data augmentation, anomaly detection, or creative applications.
  2. High-quality results: GANs can produce high-quality, photorealistic results in image synthesis, video synthesis, music synthesis, and other tasks.
  3. Unsupervised learning: GANs can be trained without labeled data, making them suitable for unsupervised learning tasks, where labeled data is scarce or difficult to obtain.
  4. Versatility: GANs can be applied to a wide range of tasks, including image synthesis, text-to-image synthesis, image-to-image translation, anomaly detection, data augmentation, and others.

Generative Adversarial Network (GAN) – FAQs

What is a Generative Adversarial Network(GAN)?

A GAN consists of two neural networks:

  • Generator: Creates new data samples.
  • Discriminator: Evaluates whether the generated samples are real or fake.

They train together through an adversarial process to improve data generation quality.

What are the main applications of GAN?

Application of GANs: Generating images and videos, transferring styles, enhancing data, translating images to other images, producing realistic synthetic data for machine learning model training.

What challenges do GAN face?

GANs can be difficult to train due to:

  • Training instability – Balancing the generator and discriminator is tricky.
  • Mode collapse – The generator may produce only a few types of outputs instead of diverse samples.
  • High computational cost – Requires powerful hardware for training.

How are GAN evaluated?

GANs are assessed based on the quality, diversity, and realism of their generated samples. Common evaluation metrics include:

  • Fréchet Inception Distance (FID) – Measures similarity to real images.
  • Inception Score (IS) – Evaluates the variety and clarity of generated images.

Can GAN be used for tasks other than image generation?

Yes, different tasks can be assigned to GANs. Text, music, 3D models, and other things have all been generated with them. The usefulness of conditional GANs is expanded by enabling the creation of specific content under certain input conditions.



Next Article

Similar Reads

three90RightbarBannerImg