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

Pretrained Models (VGG, ResNet, Inception, BERT)

अब हम Deep Learning में Pretrained Models की बात करेंगे, जो Transfer Learning की रीढ़ की हड्डी हैं।
ये models पहले से बहुत बड़े datasets पर train हो चुके हैं, और इन्हें विभिन्न tasks में reuse किया जा सकता है।


🔶 1. What are Pretrained Models?

Pretrained Models वे deep learning architectures होते हैं जिन्हें पहले से किसी बड़े dataset (जैसे ImageNet या Wikipedia) पर train किया गया है।
आप इन्हें reuse करके:

  • Feature Extraction कर सकते हैं
  • Fine-Tuning कर सकते हैं
  • Zero-shot tasks भी perform कर सकते हैं (कुछ models)

🎯 क्यों ज़रूरी हैं?

✅ Save time and computation
✅ बेहतर performance, खासकर छोटे datasets पर
✅ Common architectures को standard बनाना
✅ Foundation models का निर्माण


🔷 A. Pretrained Models in Computer Vision


1. VGGNet

  • 🧠 Developed by: Visual Geometry Group, Oxford
  • 📆 Year: 2014
  • 📐 Architecture: Simple CNNs with 3×3 convolutions
  • 🧱 Versions: VGG-16, VGG-19
  • ⚠️ Downside: Large number of parameters, slow
from torchvision import models
vgg = models.vgg16(pretrained=True)

2. ResNet (Residual Network)

resnet = models.resnet50(pretrained=True)

3. Inception (GoogLeNet)

  • 🧠 By: Google
  • 📆 Year: 2014
  • 🔄 Inception Module: Multiple filter sizes in parallel
  • 🧠 Deep but Efficient
  • 📊 Version: Inception-v1, v2, v3, v4
inception = models.inception_v3(pretrained=True)

🔷 B. Pretrained Models in Natural Language Processing (NLP)


4. BERT (Bidirectional Encoder Representations from Transformers)

  • 🧠 By: Google AI
  • 📆 Year: 2018
  • 🔍 Key Idea: Bidirectional context + Masked Language Modeling
  • 🌍 Trained On: Wikipedia + BookCorpus
  • ✅ Used for: Text classification, Q&A, NER, etc.
  • 🔁 Fine-tune specific to downstream tasks
from transformers import BertModel, BertTokenizer

model = BertModel.from_pretrained("bert-base-uncased")
tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")

📊 Comparison Table

ModelDomainStrengthsWeakness
VGGVisionSimplicityToo many parameters
ResNetVisionDeep + residual connectionsSlightly complex
InceptionVisionMulti-scale processingHarder to modify
BERTNLPPowerful language understandingLarge memory usage

🧠 Use Cases of Pretrained Models

TaskModel
Image ClassificationResNet, VGG
Object DetectionFaster R-CNN with ResNet
Semantic SegmentationDeepLab, U-Net
Sentiment AnalysisBERT
Machine TranslationmBERT, T5
Question AnsweringBERT, RoBERTa

📝 Practice Questions

  1. Pretrained model क्या होता है?
  2. VGG और ResNet में क्या अंतर है?
  3. Inception module का उद्देश्य क्या है?
  4. BERT किस तरीके से context को समझता है?
  5. Vision और NLP में कौन-कौन से pretrained models आम हैं?

🧠 Summary

FeatureVisionNLP
Basic CNNVGG
Deep NetworkResNetBERT
Advanced StructureInceptionTransformer variants
Librarytorchvisiontransformers (HuggingFace)

Feature Extraction vs Fine-Tuning

Transfer Learning के अंदर दो मुख्य तरीके होते हैं:
👉 Feature Extraction
👉 Fine-Tuning
आइए इन दोनों को विस्तार से समझते हैं — ताकि आप सही स्थिति में सही तरीका चुन सकें।


🔶 1. Feature Extraction क्या होता है?

Feature Extraction का अर्थ है कि हम एक pre-trained model के शुरूआती layers (convolution या transformer blocks) को freeze कर देते हैं और उन्हें features extractor की तरह उपयोग करते हैं।

📌 केवल final classification layer को नए data पर train किया जाता है।

✅ Use when:

  • आपके पास कम training data है
  • Pre-trained features आपके नए task के लिए पर्याप्त हैं
  • Model को जल्दी train करना है

🧱 Example:

from torchvision import models
import torch.nn as nn

model = models.resnet18(pretrained=True)

# Freeze all convolution layers
for param in model.parameters():
param.requires_grad = False

# Replace final classification layer
model.fc = nn.Linear(model.fc.in_features, 2)

🔶 2. Fine-Tuning क्या होता है?

Fine-Tuning में हम pre-trained model के कुछ या सभी layers को unfreeze करते हैं और उन्हें भी re-train करते हैं — ताकि वे नए task के अनुसार adjust हो सकें।

📌 यह तरीका अधिक compute-intensive है लेकिन अक्सर बेहतर results देता है।

✅ Use when:

  • आपके पास अधिक training data है
  • New task original task से काफ़ी अलग है
  • आप high accuracy चाहते हैं

🧱 Example:

# Unfreeze last few layers only (optional)
for name, param in model.named_parameters():
if "layer4" in name or "fc" in name:
param.requires_grad = True
else:
param.requires_grad = False

🔁 3. तुलना: Feature Extraction vs Fine-Tuning

FeatureFeature ExtractionFine-Tuning
Layers Frozenसभी convolutional layersकुछ या सभी layers train होते हैं
Train Timeतेज़धीरे
Data Requirementकमअधिक
Flexibilityसीमितउच्च
Performance (accuracy)ठीकबेहतर (especially for complex tasks)
जब उपयोग करेंData कम हो, similar taskData अधिक हो, अलग task हो

🧠 Visual Diagram:

[Pretrained Model]

┌─────────────┐ ┌───────────────┐
│ Conv Layers │ ───► │ Classifier │ → Output
└─────────────┘ └───────────────┘
↑ ↑
| └─ Trained (Fine-tuning)
└─ Frozen (Feature Extraction)

📝 Practice Questions:

  1. Feature extraction और fine-tuning में क्या अंतर है?
  2. Feature extraction कब उपयोग करना चाहिए?
  3. Fine-tuning को कब avoid करना चाहिए?
  4. PyTorch में किसी model के कौन से layers freeze/unfreeze होते हैं, कैसे देखें?
  5. कौन-सी technique ज्यादा computation मांगती है?

🎯 Summary

PointFeature ExtractionFine-Tuning
Training Layersकेवल classifierकुछ या सभी layers
Data Needकमज़्यादा
AccuracyModerateBetter
ComputationLowHigh
FlexibilityLowHigh