Generative Adversarial Network (GAN)
Last Updated :
01 Feb, 2025
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:
- Generator: creates synthetic data from random noise to produce data so realistic that the discriminator cannot distinguish it from real data.
- 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.

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.
.jpg)
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 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)
- 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.
- 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.
- Text-to-Image Synthesis: GANs create visuals from textual descriptions, enabling applications in AI-generated art, automated design, and content creation.
- Data Augmentation: GANs generate synthetic data to improve machine learning models, making them more robust and generalizable, especially in fields with limited labeled data.
- 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:
- 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.
- High-quality results: GANs can produce high-quality, photorealistic results in image synthesis, video synthesis, music synthesis, and other tasks.
- 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.
- 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.
Similar Reads
Deep Learning Tutorial
Deep Learning tutorial covers the basics and more advanced topics, making it perfect for beginners and those with experience. Whether you're just starting or looking to expand your knowledge, this guide makes it easy to learn about the different technologies of Deep Learning. Deep Learning is a bran
5 min read
Introduction to Deep Learning
Artificial Neural Network
Introduction to Convolution Neural Network
Introduction to Convolution Neural Network
A Convolutional Neural Network (CNN) is a type of Deep Learning neural network architecture commonly used in Computer Vision. Computer vision is a field of Artificial Intelligence that enables a computer to understand and interpret the image or visual data. When it comes to Machine Learning, Artific
10 min read
Digital Image Processing Basics
Digital Image Processing means processing digital image by means of a digital computer. We can also say that it is a use of computer algorithms, in order to get enhanced image either to extract some useful information. Digital image processing is the use of algorithms and mathematical models to proc
7 min read
Difference between Image Processing and Computer Vision
Image processing and Computer Vision both are very exciting field of Computer Science. Computer Vision: In Computer Vision, computers or machines are made to gain high-level understanding from the input digital images or videos with the purpose of automating tasks that the human visual system can do
2 min read
CNN | Introduction to Pooling Layer
Pooling layer is used in CNNs to reduce the spatial dimensions (width and height) of the input feature maps while retaining the most important information. It involves sliding a two-dimensional filter over each channel of a feature map and summarizing the features within the region covered by the fi
5 min read
CIFAR-10 Image Classification in TensorFlow
Prerequisites:Image ClassificationConvolution Neural Networks including basic pooling, convolution layers with normalization in neural networks, and dropout.Data Augmentation.Neural Networks.Numpy arrays.In this article, we are going to discuss how to classify images using TensorFlow. Image Classifi
8 min read
Implementation of a CNN based Image Classifier using PyTorch
Introduction: Introduced in the 1980s by Yann LeCun, Convolution Neural Networks(also called CNNs or ConvNets) have come a long way. From being employed for simple digit classification tasks, CNN-based architectures are being used very profoundly over much Deep Learning and Computer Vision-related t
9 min read
Convolutional Neural Network (CNN) Architectures
Convolutional Neural Network(CNN) is a neural network architecture in Deep Learning, used to recognize the pattern from structured arrays. However, over many years, CNN architectures have evolved. Many variants of the fundamental CNN Architecture This been developed, leading to amazing advances in t
11 min read
Object Detection vs Object Recognition vs Image Segmentation
Object Recognition: Object recognition is the technique of identifying the object present in images and videos. It is one of the most important applications of machine learning and deep learning. The goal of this field is to teach machines to understand (recognize) the content of an image just like
5 min read
YOLO v2 - Object Detection
In terms of speed, YOLO is one of the best models in object recognition, able to recognize objects and process frames at the rate up to 150 FPS for small networks. However, In terms of accuracy mAP, YOLO was not the state of the art model but has fairly good Mean average Precision (mAP) of 63% when
6 min read
Recurrent Neural Network
Natural Language Processing (NLP) Tutorial
Natural Language Processing (NLP) is the branch of Artificial Intelligence (AI) that gives the ability to machine understand and process human languages. Human languages can be in the form of text or audio format. Applications of NLPThe applications of Natural Language Processing are as follows: Voi
5 min read
Introduction to NLTK: Tokenization, Stemming, Lemmatization, POS Tagging
Natural Language Toolkit (NLTK) is one of the largest Python libraries for performing various Natural Language Processing tasks. From rudimentary tasks such as text pre-processing to tasks like vectorized representation of text - NLTK's API has covered everything. In this article, we will accustom o
5 min read
Word Embeddings in NLP
Word Embeddings are numeric representations of words in a lower-dimensional space, capturing semantic and syntactic information. They play a vital role in Natural Language Processing (NLP) tasks. This article explores traditional and neural approaches, such as TF-IDF, Word2Vec, and GloVe, offering i
15+ min read
Introduction to Recurrent Neural Networks
Recurrent Neural Networks (RNNs) work a bit different from regular neural networks. In neural network the information flows in one direction from input to output. However in RNN information is fed back into the system after each step. Think of it like reading a sentence, when you're trying to predic
12 min read
Recurrent Neural Networks Explanation
Today, different Machine Learning techniques are used to handle different types of data. One of the most difficult types of data to handle and the forecast is sequential data. Sequential data is different from other types of data in the sense that while all the features of a typical dataset can be a
8 min read
Sentiment Analysis with an Recurrent Neural Networks (RNN)
Recurrent Neural Networks (RNN) are to the rescue when the sequence of information is needed to be captured (another use case may include Time Series, next word prediction, etc.). Due to its internal memory factor, it remembers past sequences along with current input which makes it capable to captur
7 min read
Short term Memory
In the wider community of neurologists and those who are researching the brain, It is agreed that two temporarily distinct processes contribute to the acquisition and expression of brain functions. These variations can result in long-lasting alterations in neuron operations, for instance through act
5 min read
What is LSTM - Long Short Term Memory?
Long Short-Term Memory (LSTM) is an enhanced version of the Recurrent Neural Network (RNN) designed by Hochreiter & Schmidhuber. LSTMs can capture long-term dependencies in sequential data making them ideal for tasks like language translation, speech recognition and time series forecasting. Unli
8 min read
Long Short Term Memory Networks Explanation
Prerequisites: Recurrent Neural Networks To solve the problem of Vanishing and Exploding Gradients in a Deep Recurrent Neural Network, many variations were developed. One of the most famous of them is the Long Short Term Memory Network(LSTM). In concept, an LSTM recurrent unit tries to "remember" al
7 min read
LSTM - Derivation of Back propagation through time
Long Short-Term Memory (LSTM) are a type of neural network designed to handle long-term dependencies by handling the vanishing gradient problem. One of the fundamental techniques used to train LSTMs is Backpropagation Through Time (BPTT) where we have sequential data. In this article we summarize ho
4 min read
Text Generation using Recurrent Long Short Term Memory Network
LSTMs are a type of neural network that are well-suited for tasks involving sequential data such as text generation. They are particularly useful because they can remember long-term dependencies in the data which is crucial when dealing with text that often has context that spans over multiple words
6 min read