DCGAN & StyleGAN

अब हम GANs की दुनिया के दो सबसे शक्तिशाली और लोकप्रिय versions की ओर बढ़ते हैं —
🌀 DCGAN (Deep Convolutional GAN) और 🎨 StyleGAN

ये दोनों GAN architectures image generation में breakthrough साबित हुए हैं।


🔶 1. DCGAN (Deep Convolutional GAN)

📌 परिचय:

DCGAN एक Convolutional आधारित GAN architecture है जिसे 2015 में Radford, Metz, and Chintala ने प्रस्तावित किया था।

🎯 “यह पहला scalable और stable GAN architecture था जो high-quality images generate कर सका।”


🧠 Key Features:

विशेषताविवरण
📦 Conv LayersGenerator और Discriminator दोनों में Convolutional layers
🧹 No PoolingPooling की जगह stride और transposed conv
🔍 BatchNormStability और convergence के लिए
📈 ReLU & LeakyReLUActivation functions
🔥 SimplicitySimple architecture + Amazing results

🧱 DCGAN Architecture:

Generator:

Input: Random noise vector (z)
→ Fully connected layer
→ Transposed Conv + BatchNorm + ReLU
→ Transposed Conv + BatchNorm + ReLU
→ Transposed Conv + Tanh
→ Output: Fake image

Discriminator:

Input: Image (real/fake)
→ Conv + BatchNorm + LeakyReLU
→ Conv + BatchNorm + LeakyReLU
→ Flatten
→ Fully connected layer + Sigmoid
→ Output: Real/Fake Probability

🔧 PyTorch Library Support:

nn.ConvTranspose2d   # For upsampling (Generator)
nn.Conv2d # For downsampling (Discriminator)
nn.BatchNorm2d # For stability
nn.Tanh / nn.LeakyReLU

🧪 Applications:

  • Handwritten digits (MNIST)
  • Anime faces, bedrooms, shoes
  • Prototype generation for design

🔷 2. StyleGAN (Style-based GAN)

📌 परिचय:

StyleGAN को NVIDIA ने 2018 में Introduce किया था (Karras et al.).
यह अब तक का सबसे realistic face generator माना जाता है।

🎯 “This Person Does Not Exist” जैसी websites StyleGAN पर आधारित हैं।


🧠 Key Features:

विशेषताविवरण
🎨 Style-based architectureNoise vector को style vectors में बदलना
🧬 Progressive GrowingLow-res से high-res तक धीरे-धीरे training
🧠 AdaINAdaptive Instance Normalization for style control
🌈 Latent Space ControlFace features को tune करना (e.g., smile, age)
📸 High-Res1024×1024 तक की photo-quality image generation

🧱 StyleGAN Architecture (Simplified)

Input: Random vector z  
→ Mapping Network → Style vector w
→ Synthesis Network
→ Starts from constant image
→ Multiple conv blocks
→ AdaIN modulation
→ Output: High-quality image

🔁 Style Mixing:

StyleGAN अलग-अलग layers पर अलग-अलग styles apply करके
face blending और feature control करता है।

LayerControls
Early layersPose, layout
Mid layersFacial features
Late layersSkin tone, hair texture, color

🧪 Applications:

क्षेत्रउपयोग
🎭 Face GenerationHyper-realistic faces
🖼️ Art & DesignStyle morphing
🎮 Game DevCharacter creation
🎥 Movie FXVirtual avatars
🔬 BiologySynthetic cell generation

🔍 DCGAN vs StyleGAN

FeatureDCGANStyleGAN
Year20152018
ArchitectureCNN-basedStyle-based
Output QualityGoodUltra-Realistic
ControlNoneHigh (Style mixing)
Latent VectorDirectly usedTransformed via Mapping
ApplicationsSimple image genHuman faces, art, avatars
TrainingStableComplex, resource-heavy

📝 Practice Questions:

  1. DCGAN में Generator और Discriminator कैसे काम करते हैं?
  2. StyleGAN में style control कैसे किया जाता है?
  3. DCGAN और StyleGAN में क्या फर्क है?
  4. AdaIN क्या होता है और क्यों जरूरी है?
  5. Progressive Growing क्या है?

📌 Summary Table

ModelUseKey Feature
DCGANSimple image generationCNN-based Generator
StyleGANHigh-resolution faces, artStyle control, AdaIN, mixing

Training Process of GAN

अब हम समझते हैं GAN का Training Process, जो deep learning में सबसे रोचक और चुनौतीपूर्ण processes में से एक है।
यह एक दो neural networks के बीच का “game” है — Generator vs Discriminator, जो एक-दूसरे को हराने की कोशिश करते हैं।


🔶 1. Overview: GAN कैसे Train होता है?

GAN दो parts से मिलकर बनता है:

Modelकाम
🎨 Generator (G)नकली data generate करता है
🕵️‍♂️ Discriminator (D)Decide करता है कि data असली है या नकली

दोनों को बारी-बारी से train किया जाता है — Discriminator असली और नकली data में फर्क करना सीखता है, और Generator उसे बेवकूफ बनाने की कोशिश करता है।


🔁 2. Training Process Step-by-Step:

✅ Step 1: Real Data और Noise Prepare करें

  • एक mini-batch असली data x∼pdata​ से लें
  • Generator के लिए random noise vector z∼N(0,1) generate करें

✅ Step 2: Generator से Fake Data बनाएँ

  • Generator को noise vector zinput दें
  • वह fake sample generate करेगा: x^=G(z)

✅ Step 3: Discriminator को Train करें

  • उसे real data xxx और fake data x^ दोनों input दें
  • D को binary classification करना सिखाएँ:
    • D(x)→1
    • D(G(z))→0
  • Loss Function (Binary Cross-Entropy):

Discriminator के parameters को update करें


✅ Step 4: Generator को Train करें

  • अब Generator को better fake data generate करने के लिए update करें
  • उसके लिए Discriminator को fool करना लक्ष्य होता है:
  • Generator के parameters को update करें
    (Discriminator को freeze करके)

✅ Step 5: Repeat…

  • Step 1 से 4 को कई epochs तक repeat करें
  • धीरे-धीरे Generator realistic data generate करने लगेगा
  • और Discriminator उसे पहचानने में fail होने लगेगा (50% confidence)

🧠 PyTorch-Style Training Loop (Pseudo Code)

for epoch in range(num_epochs):
for real_data in dataloader:

# --- Train Discriminator ---
z = torch.randn(batch_size, latent_dim)
fake_data = generator(z)

real_pred = discriminator(real_data)
fake_pred = discriminator(fake_data.detach())

d_loss = loss_fn(real_pred, ones) + loss_fn(fake_pred, zeros)
d_optimizer.zero_grad()
d_loss.backward()
d_optimizer.step()

# --- Train Generator ---
z = torch.randn(batch_size, latent_dim)
fake_data = generator(z)
fake_pred = discriminator(fake_data)

g_loss = loss_fn(fake_pred, ones) # Want discriminator to say "real"
g_optimizer.zero_grad()
g_loss.backward()
g_optimizer.step()

⚠️ 3. Challenges in GAN Training

ProblemExplanation
❌ Mode CollapseGenerator बार-बार same output देता है
❌ Non-ConvergenceLosses oscillate करते रहते हैं
❌ Vanishing GradientsDiscriminator बहुत strong हो जाता है
✅ SolutionLearning rate tuning, label smoothing, Wasserstein GAN, etc.

📊 4. When is Training Successful?

  • Generated data बहुत realistic लगने लगे
  • Discriminator की accuracy 50% के आसपास होने लगे (confused!)
  • Losses stabilize हो जाएँ

📌 Summary Table

StepDescription
1️⃣Noise vector से fake data generate करें
2️⃣Real और fake data से Discriminator train करें
3️⃣Discriminator को fix करके Generator train करें
4️⃣पूरे process को बार-बार repeat करें (epochs)
दोनों networks धीरे-धीरे बेहतर होते हैं

📝 Practice Questions:

  1. GAN में training loop कैसे चलता है?
  2. Generator और Discriminator को alternate कैसे train करते हैं?
  3. GAN का objective function क्या होता है?
  4. GAN training में challenges क्या हैं?
  5. Mode collapse से कैसे बचा जा सकता है?

Generator vs Discriminator

अब हम GAN (Generative Adversarial Network) के दो सबसे महत्वपूर्ण components की तुलना करेंगे:
🎭 Generator vs Discriminator
ये दोनों एक-दूसरे के विरोधी हैं, लेकिन साथ में मिलकर GAN को powerful बनाते हैं।


🔶 1. GAN का मूल विचार (Core Idea)

GAN architecture में दो models होते हैं:

  1. Generator (G) — नकली data बनाता है
  2. Discriminator (D) — बताता है कि data असली है या नकली

इन दोनों models का उद्देश्य होता है एक-दूसरे को beat करना।
👉 यही competition GAN को smart और creative बनाता है।


🧠 2. Role of Generator (G)

FeatureDescription
🛠️ कामRandom noise से synthetic data generate करता है
🎯 Goalइतना realistic data बनाना कि Discriminator उसे पहचान ना सके
🔄 InputRandom vector z∼N(0,1)
📤 OutputFake image / data sample G(z)
🧠 सीखता हैकैसे असली data की नकल की जाए

“Generator एक कलाकार है — जो नकली चित्र बनाता है।”


🔧 Example:

z = torch.randn(64, 100)  # Random noise
fake_images = generator(z) # Generated samples

🧠 3. Role of Discriminator (D)

FeatureDescription
🛠️ कामReal और fake data में भेद करना
🎯 Goalसही-सही पहचानना कि data असली है या नकली
🔄 InputData sample (real or fake)
📤 OutputProbability: Real (1) या Fake (0)
🧠 सीखता हैअसली और नकली data के अंतर

“Discriminator एक जज है — जो असली और नकली पहचानता है।”


🔧 Example:

real_score = discriminator(real_images)      # Output close to 1
fake_score = discriminator(fake_images) # Output close to 0

🔁 4. GAN Training Dynamics

चरणविवरण
1️⃣ Generator एक नकली image बनाता हैGenerator random noise vector z∼N(0,1)को लेकर fake image G(z) produce करता है।
2️⃣ Discriminator असली और नकली दोनों samples पर prediction करता हैDiscriminator को एक batch असली data x और fake data G(z)का मिलता है, और वह predict करता है कि कौन सा sample असली है और कौन नकली।
3️⃣ Discriminator की loss को minimize किया जाता हैDiscriminator को train किया जाता है ताकि वह असली samples को 1 और नकली samples को 0 classify कर सके (binary classification)।
4️⃣ अब Generator की बारी है — वो अपनी trick और smart बनाता हैGenerator को train किया जाता है ताकि उसका fake output ऐसा हो कि Discriminator उसे “real” समझे। यानी वह Discriminator की prediction को गलत करने की कोशिश करता है।
5️⃣ यह process बार-बार दोहराई जाती है (adversarial loop)इस adversarial game में दोनों models better होते जाते हैं। Generator बेहतर fake samples बनाता है, और Discriminator उन्हें पकड़ने में तेज़ होता है।

👉 इस loop से दोनों models बेहतर होते जाते हैं।


⚔️ 5. Comparison Table

FeatureGenerator (G)Discriminator (D)
उद्देश्यनकली data बनानाअसली और नकली में अंतर करना
InputNoise vector zData sample x
OutputFake sample (image, text, etc.)Probability (real or fake)
TargetDiscriminator को धोखा देनाGenerator को पकड़ना
Learns fromDiscriminator के feedback सेReal vs fake examples से
Neural Net TypeGenerator network (decoder जैसा)Classifier network (binary)

📊 Visualization

Noise (z)

[ Generator ]

Fake Data ───► [ Discriminator ] ◄─── Real Data

Predicts: Real or Fake?

📝 Practice Questions

  1. Generator और Discriminator में क्या अंतर है?
  2. Generator क्या generate करता है और किस input से?
  3. Discriminator क्या predict करता है?
  4. GAN training में दोनों networks एक-दूसरे से कैसे सीखते हैं?
  5. GAN में कौन-सा component output generate करता है?

🧠 Summary

Componentकामलक्ष्य
Generatorनकली data बनानाDiscriminator को धोखा देना
DiscriminatorReal/Fake पहचाननाFake को पकड़ना
मिलकरGAN training को एक game में बदलते हैंRealistic data synthesis

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