Introduction to GANs (Generative Adversarial Networks)

अब हम deep learning की सबसे क्रांतिकारी और रचनात्मक तकनीक को समझने जा रहे हैं —
🎭 Generative Adversarial Networks (GANs)

यह deep learning का एक ऐसा क्षेत्र है जो machines को नई चीजें “create” करना सिखाता है — जैसे इंसानों की तरह तस्वीरें बनाना, आर्टिफिशियल आवाज़ें, नए फैशन डिज़ाइन, और यहां तक कि पूरी दुनिया की नक़ल करना।

🔶 1. What is a GAN?

GANs एक तरह का generative model है जो deep learning का उपयोग करके नई data instances generate करता है
GAN architecture में दो neural networks होते हैं जो एक-दूसरे के खिलाफ (adversarial) train होते हैं:

🎯 “एक network generate करता है, दूसरा उसे judge करता है।”


🔁 2. GAN Structure

        Noise (z)

[Generator Network]

Fake Data (x̂)

[Discriminator Network]
↑ ↓
Real Data (x) Real or Fake?

🔹 Generator (G):

  • Random noise से fake data generate करता है
  • इसका उद्देश्य है Discriminator को धोखा देना

🔹 Discriminator (D):

  • असली और नकली data के बीच अंतर करने की कोशिश करता है
  • इसका उद्देश्य है fake data को पकड़ना

🧠 3. Game Between Generator and Discriminator

  • Generator चाहता है कि Discriminator को धोखा दे
  • Discriminator चाहता है कि वो सही-सही असली और नकली data पहचान ले

👉 इसे कहा जाता है minimax game:


🔬 4. क्यों GANs ख़ास हैं?

FeatureDescription
🎨 Creativityनई images, art, music बना सकते हैं
🧠 LearningUnsupervised (no labels)
🎯 High-Quality OutputExtremely realistic images
🏆 CompetitionGenerator vs Discriminator improves quality

🔧 5. PyTorch GAN Skeleton (Basic Idea)

# Generator
class Generator(nn.Module):
def __init__(self):
super().__init__()
self.net = nn.Sequential(
nn.Linear(100, 128),
nn.ReLU(),
nn.Linear(128, 784),
nn.Tanh()
)

def forward(self, z):
return self.net(z)

# Discriminator
class Discriminator(nn.Module):
def __init__(self):
super().__init__()
self.net = nn.Sequential(
nn.Linear(784, 128),
nn.LeakyReLU(0.2),
nn.Linear(128, 1),
nn.Sigmoid()
)

def forward(self, x):
return self.net(x)

📊 6. Real-World Applications of GANs

AreaExample
🎨 Art & Designनई paintings, filters
👨‍🎨 DeepFakeFace swap, video editing
🖼️ Super-ResolutionLow-res → High-res images
🧪 HealthcareSynthetic medical data
🎮 GamingEnvironment generation
🌎 SimulationVirtual world synthesis
🧑‍🏫 Data AugmentationSynthetic training data

📝 Practice Questions:

  1. GAN क्या होता है और इसमें कौन-कौन से components होते हैं?
  2. Generator और Discriminator का क्या रोल होता है?
  3. GAN का objective function क्या है?
  4. GANs किस-किस क्षेत्र में उपयोग किए जा रहे हैं?
  5. GAN training को unstable क्यों कहा जाता है?

🧠 Summary

ConceptDescription
GANGenerative Adversarial Network
GeneratorFake data create करता है
DiscriminatorFake और real में अंतर करता है
OutputSynthetic but realistic data
Use CasesImage generation, deepfake, super-resolution, etc.

Applications — Denoising & Dimensionality Reduction

अब हम Autoencoders के दो प्रायोगिक उपयोगों (applications) को विस्तार से समझेंगे —
🔹 Denoising
🔹 Dimensionality Reduction

ये दोनों real-world problems में बहुत उपयोगी हैं और deep learning की शक्ति को बख़ूबी दर्शाते हैं।


🔶 1. Application 1: Denoising Autoencoder

❓ What is it?

Denoising Autoencoder (DAE) एक ऐसा Autoencoder है जो noisy input को clean output में बदलना सीखता है।

🎯 “Input को जानबूझकर corrupt किया जाता है और model को सिखाया जाता है कि वह clean version reconstruct करे।”


📦 Working:

   Original Image (x)
↓ Add Noise
Noisy Input (x̃)

[Encoder + Decoder]

Clean Output (x̂)

Model learns to minimize:


🔧 Example in PyTorch:

def add_noise(imgs, noise_factor=0.3):
noisy_imgs = imgs + noise_factor * torch.randn_like(imgs)
return torch.clip(noisy_imgs, 0., 1.)

You then train autoencoder with (noisy_img, original_img) pairs.


🧠 Use Cases:

UseDescription
🖼️ Image DenoisingRemove noise from pictures
📄 Document CleanupClean scanned papers
📢 Audio DenoisingRemove background noise
🧠 MedicalRemove sensor noise in ECG, MRI, etc.

🔶 2. Application 2: Dimensionality Reduction

❓ What is it?

Autoencoder compresses high-dimensional data into a low-dimensional latent representation, similar to PCA (Principal Component Analysis) — but with non-linear capabilities.

🎯 “Autoencoder = Non-linear, trainable PCA”


📦 Example:

| Input | 784-dim vector (28×28 image)
| Encoder | Reduces it to 2D or 3D latent code
| Decoder | Reconstructs full image
| Output | Use latent codes for clustering, visualization, etc.


🔧 PyTorch Sketch:

# Encoder output is just 2D
self.encoder = nn.Sequential(
nn.Linear(784, 128),
nn.ReLU(),
nn.Linear(128, 2) # 2D Latent Space
)

🧠 Use Cases:

UseDescription
📊 Data VisualizationCompress to 2D for t-SNE / plots
🔍 ClusteringGroup similar inputs (e.g., digits, faces)
⚡ Fast InferenceWork on lower-dimensional features
📈 Feature ExtractionUse compressed codes for ML models
🎮 Game AICompress game states

📝 Practice Questions:

  1. Denoising Autoencoder क्या है और कैसे काम करता है?
  2. Noise हटाने के लिए Autoencoder को कैसे train किया जाता है?
  3. Dimensionality reduction में Autoencoder और PCA में क्या अंतर है?
  4. Latent space का क्या role है?
  5. Low-dimensional representation किन real-world problems में काम आता है?

📌 Summary

ApplicationInputOutputBenefit
DenoisingNoisy imageClean imageNoise removal
Dimensionality ReductionHigh-dim dataLow-dim featuresVisualization, clustering, compression

Variational Autoencoders (VAE)

अब हम Autoencoders की एक शक्तिशाली और probabilistic form को समझेंगे —
🔮 Variational Autoencoders (VAE)
जो deep generative models की दुनिया में एक foundation की तरह माने जाते हैं।


🔶 1. What is a Variational Autoencoder?

VAE एक तरह का Autoencoder है, जो ना केवल input को compress करता है,
बल्कि उसे एक probability distribution में encode करता है।

🎯 “VAE compress करता है input को एक distribution के रूप में, जिससे हम new data generate कर सकते हैं।”


🧠 2. Traditional Autoencoder vs VAE

FeatureAutoencoderVariational Autoencoder
OutputReconstruct inputReconstruct + Sample new
Latent VectorFixed valuesProbability distribution
GenerationNoYes (Generative model)
LearningDeterministicProbabilistic
RegularizationNoneKL Divergence

🔬 3. VAE Structure

Diagram:

        Input x

[Encoder Network]

Latent Distribution (μ, σ)

Sampling (z ~ N(μ, σ))

[Decoder Network]

Reconstructed x̂

🧮 4. Latent Distribution

VAE encoder predicts:

  • Mean vector μ
  • Log-variance log⁡σ2

From these, we sample latent variable

👉 इसे कहते हैं reparameterization trick
ताकि gradient backpropagation संभव हो।


🧮 5. VAE Loss Function

VAE का कुल loss दो हिस्सों से मिलकर बनता है:

L=Reconstruction Loss+ KL Divergence Loss

✅ Reconstruction Loss:

✅ KL Divergence Loss:


🔧 6. PyTorch Sketch

class VAE(nn.Module):
def __init__(self, input_dim, hidden_dim, latent_dim):
super(VAE, self).__init__()
self.fc1 = nn.Linear(input_dim, hidden_dim)
self.mu = nn.Linear(hidden_dim, latent_dim)
self.log_var = nn.Linear(hidden_dim, latent_dim)
self.decoder = nn.Sequential(
nn.Linear(latent_dim, hidden_dim),
nn.ReLU(),
nn.Linear(hidden_dim, input_dim),
nn.Sigmoid()
)

def encode(self, x):
h = F.relu(self.fc1(x))
return self.mu(h), self.log_var(h)

def reparameterize(self, mu, log_var):
std = torch.exp(0.5 * log_var)
eps = torch.randn_like(std)
return mu + eps * std

def forward(self, x):
mu, log_var = self.encode(x)
z = self.reparameterize(mu, log_var)
return self.decoder(z), mu, log_var

📊 7. Applications of VAE

ApplicationDescription
✅ Image GenerationNew samples create करना
✅ Data ImputationMissing values भरना
✅ Representation LearningCompressed features
✅ Anomaly DetectionRare patterns पकड़ना
✅ Drug DesignMolecule generation

🎨 8. Generated Sample Example (MNIST)

Train VAE on MNIST, then sample new digits by:

z = torch.randn(1, latent_dim)
generated = model.decoder(z)

👉 ऐसा output real handwritten digit जैसा दिखेगा, despite not being in the original dataset.


📝 Practice Questions:

  1. VAE क्या है और Autoencoder से कैसे अलग है?
  2. Latent vector के लिए reparameterization क्यों ज़रूरी है?
  3. VAE का loss function किन भागों में बँटा होता है?
  4. KL divergence का क्या उद्देश्य होता है?
  5. VAE से synthetic data कैसे generate किया जाता है?

🎯 Summary

FeatureDescription
VAEProbabilistic autoencoder
Encoder Outputμ और σ (mean & std)
Samplingz = μ + σ * ε
LossReconstruction + KL divergence
Use CasesGeneration, anomaly detection, compression

Encoder-Decoder Structure

अब हम Deep Learning की सबसे शक्तिशाली और बहुप्रयुक्त संरचना को विस्तार से समझते हैं —
🔁 Encoder-Decoder Structure
जिसका उपयोग NLP, Image Captioning, Machine Translation, Autoencoders आदि में बड़े पैमाने पर किया जाता है।


🔶 1. What is the Encoder-Decoder Architecture?

Encoder-Decoder एक ऐसा framework है जिसमें model दो मुख्य भागों में बँटा होता है:

  1. Encoder: Input data को एक compact और meaningful representation (context vector या latent vector) में बदलता है।
  2. Decoder: उसी compact representation से नया output sequence या data generate करता है।

🎯 “Encoder compress करता है, Decoder expand करता है।”


🧱 2. Structural Flow

 Input Sequence / Data

[Encoder]

Latent Representation

[Decoder]

Output Sequence / Data

🔄 3. Encoder-Decoder is a General Pattern

Use CaseInputOutputEncoder-Decoder
TranslationEnglish sentenceFrench sentence
Image CaptioningImage featuresText sentence
AutoencoderImageReconstructed image
ChatbotUser queryResponse
Speech-to-textAudioText

🔧 4. Components of Encoder-Decoder

🔹 Encoder:

  • Sequence of layers (CNNs, RNNs, Transformers, etc.)
  • Learns to encode features from input
  • Outputs context/latent vector: h=f(x)

🔹 Decoder:

  • Takes the latent vector as input
  • Generates output step-by-step (esp. in sequence models)
  • Uses:

🧠 5. Why Use Encoder-Decoder?

AdvantageDescription
✅ GeneralizableWorks for images, text, audio
✅ FlexibleInput/output length may differ
✅ ModularEncoder & Decoder can be designed separately
✅ ReusabilityEncoder can be shared across tasks

🧪 6. Variants of Encoder-Decoder

TypeExampleDomain
CNN-CNNAutoencodersVision
CNN-RNNImage CaptioningVision + NLP
RNN-RNNMachine TranslationNLP
Transformer-TransformerBERT, T5NLP
ViT-GPTBLIP, FlamingoVision+Language

🔧 PyTorch Skeleton Example

class Encoder(nn.Module):
def __init__(self, input_dim, hidden_dim):
super().__init__()
self.linear = nn.Linear(input_dim, hidden_dim)

def forward(self, x):
return self.linear(x)

class Decoder(nn.Module):
def __init__(self, hidden_dim, output_dim):
super().__init__()
self.linear = nn.Linear(hidden_dim, output_dim)

def forward(self, x):
return self.linear(x)

# Sample use
encoder = Encoder(784, 128)
decoder = Decoder(128, 784)

x = torch.randn(1, 784)
latent = encoder(x)
output = decoder(latent)

📝 Practice Questions:

  1. Encoder-Decoder structure क्या होता है?
  2. इसका प्रयोग किन किन क्षेत्रों में होता है?
  3. Encoder और Decoder के कार्य में क्या अंतर है?
  4. Autoencoder और Sequence-to-Sequence में ये संरचना कैसे लागू होती है?
  5. Encoder-Decoder में latent representation क्या है?

📌 Summary

ComponentFunction
EncoderInput को compact form में बदलता है
Latent VectorInput का encoded meaning
DecoderLatent vector से output generate करता है
UsesTranslation, Captioning, Chatbots, etc.

What is an Autoencoder?

अब हम एक और महत्वपूर्ण और रोचक deep learning तकनीक को समझेंगे —
📦 Autoencoder
जिसका उपयोग representation learning, dimensionality reduction, और unsupervised learning में होता है।


🔶 1. Definition (परिभाषा):

Autoencoder एक ऐसा neural network है जिसे input को ही output के रूप में reproduce करने के लिए train किया जाता है — लेकिन इस प्रक्रिया में यह data के compressed और meaningful features सीखता है।

🎯 “Autoencoder खुद से feature सीखता है — बिना किसी label के।”


🧠 2. Structure of Autoencoder

Autoencoder में तीन मुख्य भाग होते हैं:

  1. Encoder: Input को compress करता है (latent space में)
  2. Latent Space: Data का compressed representation
  3. Decoder: Compressed data को reconstruct करता है

Diagram:

      Input

[Encoder]

Compressed Code (Latent Vector)

[Decoder]

Reconstructed Output

🧮 3. Objective (Loss Function)

Autoencoder को train करने का उद्देश्य है:

जहाँ:

  • x: Original input
  • x^: Reconstructed output
  • L: Mean Squared Error (या कोई और loss)

🧱 4. Types of Autoencoders

TypeDescription
🔹 Vanilla AutoencoderBasic encoder-decoder structure
🔹 Sparse AutoencoderRegularization to learn sparse codes
🔹 Denoising AutoencoderNoisy input → Clean reconstruction
🔹 Variational Autoencoder (VAE)Probabilistic latent space
🔹 Convolutional AutoencoderCNN-based encoder-decoder for images

🔧 5. PyTorch Example (Basic Autoencoder)

import torch.nn as nn

class Autoencoder(nn.Module):
def __init__(self):
super(Autoencoder, self).__init__()
self.encoder = nn.Sequential(
nn.Linear(784, 128),
nn.ReLU(),
nn.Linear(128, 32),
)
self.decoder = nn.Sequential(
nn.Linear(32, 128),
nn.ReLU(),
nn.Linear(128, 784),
nn.Sigmoid()
)

def forward(self, x):
x = self.encoder(x)
x = self.decoder(x)
return x

📊 6. Applications of Autoencoders

ApplicationDescription
✅ Dimensionality Reductionजैसे PCA से बेहतर
✅ Image DenoisingNoise हटाना
✅ Anomaly DetectionOutlier data पकड़ना
✅ Data CompressionLatent representation
✅ Image ColorizationBlack & white → Color
✅ Feature ExtractionFor downstream tasks

🔄 7. Difference from PCA

PCAAutoencoder
LinearNon-linear
No trainingTrained via gradient descent
Limited capacityLearn complex structure
Fixed basisFlexible learned features

📝 Practice Questions:

  1. Autoencoder क्या होता है?
  2. Autoencoder में latent space का क्या महत्व है?
  3. Vanilla और Denoising Autoencoder में क्या अंतर है?
  4. Autoencoder का loss function क्या होता है?
  5. Autoencoder का प्रयोग कहाँ किया जा सकता है?

🎯 Summary

FeatureDescription
Input = OutputLearns to reconstruct data
Unsupervisedकोई label नहीं चाहिए
Encoder + DecoderCompress और reconstruct करता है
ApplicationsCompression, denoising, anomaly detection