What is Batch Normalization

Batch Normalization (BatchNorm) एक technique है जो training को stabilize, accelerate और improve करने के लिए इस्तेमाल होती है।

यह हर layer के output (activations) को normalize कर देती है ताकि उनका distribution mean=0 और variance=1 के आस-पास रहे।

इससे gradients ज़्यादा smooth होते हैं और training तेज़ होती है।


🔁 2. क्यों ज़रूरी है?

Deep networks में, जैसे-जैसे layers बढ़ती हैं, activations का distribution shift होने लगता है — इस समस्या को कहते हैं:

📉 Internal Covariate Shift

BatchNorm इसका समाधान है — यह हर batch के output को rescale और re-center करता है।


🧮 3. Mathematical Explanation

मान लीजिए किसी layer का output x है।

Step 1: Mean और Variance निकालना

Step 2: Normalize

Step 3: Scale and Shift

यहाँ:

  • γ, β सीखने योग्य parameters हैं
  • ϵएक छोटा constant है stability के लिए

🔧 4. PyTorch Implementation

import torch.nn as nn

model = nn.Sequential(
nn.Linear(128, 64),
nn.BatchNorm1d(64), # BatchNorm for 1D input
nn.ReLU(),
nn.Linear(64, 10)
)

For images, use nn.BatchNorm2d(num_channels)


📈 5. Benefits of BatchNorm

BenefitExplanation
✅ Faster TrainingSmoother gradients → fast convergence
✅ Higher Learning RatesWithout instability
✅ Reduced Need for DropoutActs as light regularizer
✅ Mitigates Vanishing/Exploding GradientsKeeps activations in check
✅ Generalization ImprovesBetter test accuracy

🔍 6. Where to Apply?

TypeApply BatchNorm After
Linear (Dense)Linear → BatchNorm1d → Activation
Conv2D LayerConv2d → BatchNorm2d → Activation

⚠️ 7. Training vs Inference

  • During training → mean & variance per-batch
  • During inference → running average of mean & variance

PyTorch automatically handles this internally using .train() and .eval() modes.


🔁 With and Without BatchNorm (Effect on Accuracy):

EpochWithout BatchNormWith BatchNorm
562%79%
1071%87%
2076%91%

📝 Practice Questions:

  1. Batch Normalization का मुख्य उद्देश्य क्या है?
  2. Internal Covariate Shift किसे कहते हैं?
  3. PyTorch में BatchNorm1d और BatchNorm2d में क्या अंतर है?
  4. BatchNorm में γ और βका क्या role है?
  5. क्या BatchNorm dropout की तरह regularization भी करता है?

🎯 Summary:

FeatureBatchNorm Impact
Stability⬆️ Improves
Speed⬆️ Faster Training
Generalization✅ Helps prevent overfitting
Gradient Flow✅ Prevents vanishing/exploding


Weight Initialization Techniques

(वेट इनिशियलाइज़ेशन तकनीकें)


🔶 1. Weight Initialization क्या है?

📌 परिभाषा:

Weight Initialization का मतलब होता है — training शुरू करने से पहले neural network के weights को कुछ initial values देना।

अगर weights सही से initialize नहीं किए गए, तो training धीमी या पूरी तरह से fail हो सकती है — खासकर deep networks में।


🔁 2. क्यों ज़रूरी है सही initialization?

गलत Initializationसमस्या
सभी weights = 0Neurons same gradient सीखेंगे → symmetry break नहीं होगा
बहुत छोटे weightsGradient vanish होने लगेगा (Vanishing Gradient)
बहुत बड़े weightsGradient explode करने लगेगा (Exploding Gradient)

🔧 3. Common Weight Initialization Techniques


✅ A. Zero Initialization ❌ (Not Recommended)

nn.Linear(128, 64).weight.data.fill_(0)
  • Problem: All neurons learn the same thing → no learning
  • Symmetry नहीं टूटता

✅ B. Random Initialization (Normal/Uniform)

nn.init.normal_(layer.weight, mean=0.0, std=1.0)
nn.init.uniform_(layer.weight, a=-0.1, b=0.1)
  • Random values से symmetry टूटती है
  • लेकिन deep networks में gradient vanish/explode हो सकता है

✅ C. Xavier Initialization (Glorot Initializati

nn.init.xavier_uniform_(layer.weight)

✅ D. He Initialization (Kaiming Initialization)

  • Recommended for ReLU activation
  • Prevents vanishing gradients with ReLU
nn.init.kaiming_normal_(layer.weight, nonlinearity='relu')

📘 PyTorch Implementation

import torch.nn as nn

layer = nn.Linear(128, 64)

# Xavier Init
nn.init.xavier_uniform_(layer.weight)

# He Init (for ReLU)
nn.init.kaiming_normal_(layer.weight, nonlinearity='relu')

📈 Comparison Table:

MethodSuitable ForKeeps VarianceRecommended
ZeroNever
RandomShallow nets
XavierSigmoid/Tanh
HeReLU✅✅✅

🧠 Real-World Tip:

Deep networks trained with improper initialization often show:

  • No learning (loss flat रहता है)
  • NaN losses (gradient explode करता है)
  • Poor accuracy (early layers freeze हो जाते हैं)

📝 Practice Questions:

  1. Weight Initialization क्यों ज़रूरी है?
  2. Xavier Initialization किस प्रकार के activation functions के लिए उपयुक्त है?
  3. He Initialization में variance कैसे decide होता है?
  4. Zero initialization क्यों fail हो जाता है?
  5. PyTorch में He initialization कैसे implement करते हैं?

🎯 Summary:

ConceptExplanation
InitializationTraining से पहले weights की setting
XavierSigmoid/Tanh के लिए best
HeReLU के लिए best
ZeroUse नहीं करना चाहिए

Vanishing and Exploding Gradients

(घटते और फूटते ग्रेडिएंट्स की समस्या)


🔶 1. Problem Statement:

जब DNN को train किया जाता है (backpropagation के ज़रिए), तो gradients को layers के बीच backward propagate किया जाता है।

लेकिन बहुत गहरी networks में, ये gradients:

  • बहुत छोटे (near-zero) हो सकते हैं → Vanishing Gradients
  • बहुत बड़े (extremely high) हो सकते हैं → Exploding Gradients

🔷 2. Vanishing Gradient Problem

📌 क्या होता है?

Gradient values इतनी छोटी हो जाती हैं कि weights effectively update ही नहीं हो पाते
Training slow या completely stuck हो जाती है।


❗ क्यों होता है?

  • जब activation functions (जैसे Sigmoid या Tanh) के derivatives हमेशा < 1 होते हैं
  • और बहुत सी layers multiply होती हैं:

🧠 Impact:

  • Deep layers almost learn nothing
  • Early layers freeze
  • Training fails

🔷 3. Exploding Gradient Problem

📌 क्या होता है?

Gradients बहुत तेजी से बड़े हो जाते हैं
→ Weights extremely large
→ Model becomes unstable
→ Loss: NaN या infinity


❗ क्यों होता है?

  • जब weight initialization गलत हो
  • या large derivatives repeatedly multiply होते हैं

🧠 Impact:

  • Loss suddenly बहुत बड़ा
  • Model unstable
  • Numerical overflow

🔁 4. Visual Representation:

❌ Vanishing Gradient:

Layer 1 ← 0.0003
Layer 2 ← 0.0008
Layer 3 ← 0.0011
...
Final layers learn nothing

❌ Exploding Gradient:

Layer 1 ← 8000.2
Layer 2 ← 40000.9
Layer 3 ← 90000.1
...
Loss becomes NaN

✅ 5. Solutions and Fixes

ProblemSolution
Vanishing GradientReLU Activation Function
He Initialization (weights)
Batch Normalization
Residual Connections (ResNet)
Exploding GradientGradient Clipping
Proper Initialization
Lower Learning Rate

✔ Recommended Practices:

  • Use ReLU instead of Sigmoid/Tanh
  • Initialize weights with Xavier or He initialization
  • Add BatchNorm after layers
  • Use gradient clipping in training loop:
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)

🔧 PyTorch Example (Gradient Clipping):

loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
optimizer.step()

📈 Summary:

IssueCauseEffectFix
VanishingSmall gradients in deep layersNo learningReLU, He init, BatchNorm
ExplodingLarge gradientsNaN lossGradient clipping, Proper init

📝 Practice Questions:

  1. Vanishing Gradient क्या है? इसे कैसे पहचानेंगे?
  2. Exploding Gradient से model पर क्या असर पड़ता है?
  3. Activation functions gradients को कैसे affect करते हैं?
  4. Gradient Clipping क्यों जरूरी होता है?
  5. Batch Normalization इन समस्याओं को कैसे कम करता है?

Deep Neural Networks (DNN)

(डीप न्यूरल नेटवर्क्स)


🔶 1. What is a Deep Neural Network?

📌 परिभाषा:

Deep Neural Network (DNN) एक ऐसा artificial neural network होता है जिसमें एक से ज़्यादा hidden layers होते हैं।

👉 यह shallow network (जैसे simple MLP जिसमें 1 hidden layer हो) से अलग होता है क्योंकि इसमें “depth” होती है — यानी कई layers जो input से output तक data को progressively abstract करती हैं।


🧠 Structure of a DNN:

Input Layer → Hidden Layer 1 → Hidden Layer 2 → ... → Hidden Layer N → Output Layer
  • हर layer neurons का group होता है
  • Each neuron applies:

z=w⋅x+b, a=f(z)

जहाँ f कोई activation function होता है


📊 Example:

मान लीजिए एक DNN जिसमें:

  • Input Layer: 784 nodes (28×28 image pixels)
  • Hidden Layer 1: 512 neurons
  • Hidden Layer 2: 256 neurons
  • Output Layer: 10 neurons (digits 0–9 classification)

🔷 2. Why Use Deep Networks?

❓ क्यों shallow networks काफी नहीं होते?

  • Shallow networks simple problems के लिए ठीक हैं
  • लेकिन complex tasks (जैसे image recognition, NLP, audio classification) में input-output relationship बहुत nonlinear होती है

✅ Deep networks:

  • High-level features को automatically extract कर सकते हैं
  • Abstractions को hierarchy में capture करते हैं

🧠 Hierarchical Feature Learning:

LayerLearns
Layer 1Edges, curves
Layer 2Shapes, textures
Layer 3Objects, faces

🔶 DNN की Architecture क्या होती है?

Architecture का मतलब होता है कि DNN में कितनी layers हैं, हर layer में कितने neurons हैं, activation functions क्या हैं, और input-output data का flow कैसा है।


📊 High-Level Structure:

Input Layer → Hidden Layer 1 → Hidden Layer 2 → ... → Output Layer

हर layer दो चीज़ें करती है:

  1. Linear Transformation z=W⋅x+b
  2. Activation Function a=f(z)

🔷 2. Components of a DNN Architecture

ComponentDescription
Input LayerRaw input data (e.g., image pixels, features)
Hidden LayersIntermediate processing layers (more = more depth)
Output LayerFinal predictions (e.g., class scores)
Weights & BiasesParameters learned during training
Activation FunctionsAdds non-linearity (ReLU, Sigmoid, etc.)
Loss FunctionMeasures prediction error
OptimizerUpdates weights using gradients (SGD, Adam)

🧠 Typical Architecture Example (MNIST Digits):

Layer TypeShapeNotes
Input(784,)28×28 image flattened
Dense 1(784 → 512)Hidden Layer 1 + ReLU
Dense 2(512 → 256)Hidden Layer 2 + ReLU
Output(256 → 10)Digit prediction + Softmax

🧮 3. Mathematical View


🔧 4. PyTorch Code: Custom DNN Architecture

import torch.nn as nn

class DNN(nn.Module):
def __init__(self):
super(DNN, self).__init__()
self.net = nn.Sequential(
nn.Linear(784, 512), # Input to Hidden 1
nn.ReLU(),
nn.Linear(512, 256), # Hidden 1 to Hidden 2
nn.ReLU(),
nn.Linear(256, 10) # Output Layer
)

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

📈 Visualization of Architecture

[Input Layer: 784]

[Dense Layer: 512 + ReLU]

[Dense Layer: 256 + ReLU]

[Output Layer: 10 (classes)]

🔍 Key Architecture Design Questions

  1. कितनी hidden layers होनी चाहिए?
  2. हर layer में कितने neurons?
  3. कौन सा activation function चुनना है?
  4. क्या dropout, batch norm चाहिए?
  5. Loss function कौन सा है?

🎯 Summary:

ElementRole
LayersInput → Hidden(s) → Output
ActivationNon-linearity लाती है
DepthLayers की संख्या
WidthNeurons per layer
OptimizerGradient से weights update करता है

📝 Practice Questions:

  1. DNN की architecture में कौन-कौन से भाग होते हैं?
  2. Hidden layers कितनी होनी चाहिए — इससे क्या फर्क पड़ता है?
  3. Activation function का क्या महत्व है architecture में?
  4. DNN architecture में overfitting कैसे रोका जाता है?
  5. Architecture tuning कैसे किया जाता है?

🔶 Training a DNN

💡 Standard Process:

  1. Forward Pass: Prediction generate करना
  2. Loss Calculation: Prediction vs ground truth
  3. Backward Pass: Gradient computation
  4. Optimizer Step: Weights update

🚧 Challenges in Training Deep Networks:

ChallengeSolution
Vanishing GradientsReLU, BatchNorm, Residual connections
OverfittingDropout, Data Augmentation
Computational CostGPU acceleration, Mini-batch training

🔧 4. PyTorch Code: Simple DNN for Classification

import torch.nn as nn

class SimpleDNN(nn.Module):
def __init__(self):
super(SimpleDNN, self).__init__()
self.model = nn.Sequential(
nn.Linear(784, 512),
nn.ReLU(),
nn.Linear(512, 256),
nn.ReLU(),
nn.Linear(256, 10)
)

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

🔬 5. Applications of DNNs

DomainUse Case
Computer VisionImage classification, Object detection
NLPText classification, Sentiment analysis
HealthcareDisease prediction from X-rays
FinanceCredit scoring, Fraud detection
RoboticsSensor fusion, control systems

📈 Summary:

TermMeaning
DNNNeural network with 2+ hidden layers
DepthRefers to number of layers
PowerLearns complex mappings from data
ChallengesVanishing gradients, Overfitting, Compute cost

📝 Practice Questions:

  1. DNN और shallow network में क्या फर्क है?
  2. DNN के training में कौन-कौन सी steps होती हैं?
  3. Vanishing gradient क्या होता है और इसे कैसे solve किया जाता है?
  4. PyTorch में DNN implement करने का तरीका बताइए।
  5. DNN किन-किन क्षेत्रों में प्रयोग किया जाता है?

Overfitting, Underfitting and Regularization

(ओवरफिटिंग, अंडरफिटिंग और रेग्युलराइजेशन)


🔶 1. Underfitting क्या है?

📌 परिभाषा:

Underfitting तब होता है जब model training data को भी सही से नहीं सीख पाता।

🔍 संकेत:

  • High training loss
  • Low accuracy (train & test दोनों पर)
  • Model simple है या data complex

🧠 कारण:

  • Model बहुत छोटा है
  • कम training epochs
  • Features अच्छे से represent नहीं किए गए

🔶 2. Overfitting क्या है?

📌 परिभाषा:

Overfitting तब होता है जब model training data को बहुत अच्छे से याद कर लेता है, लेकिन test data पर fail हो जाता है।

🔍 संकेत:

  • Training loss बहुत low
  • Test loss बहुत high
  • Accuracy train पर high, test पर low

🧠 कारण:

  • Model बहुत complex है (बहुत सारे parameters)
  • कम data
  • ज़्यादा epochs
  • Noise को भी सीख लिया model ने

📈 Summary Table:

TypeTrain AccuracyTest AccuracyError
UnderfittingLowLowHigh Bias
OverfittingHighLowHigh Variance
Just RightHighHighLow Bias & Variance

🔧 3. Regularization Techniques

🔷 Purpose:

Regularization techniques model को generalize करने में मदद करते हैं — यानी unseen (test) data पर बेहतर perform करना।


📌 Common Regularization Methods:

✅ A. L1 & L2 Regularization:

optimizer = torch.optim.SGD(model.parameters(), lr=0.01, weight_decay=0.001)  # L2

✅ B. Dropout:

  • कुछ neurons को randomly deactivate कर दिया जाता है training के दौरान
  • इससे model सभी features पर ज़रूरत से ज़्यादा निर्भर नहीं करता
nn.Dropout(p=0.5)

✅ C. Early Stopping:

  • जैसे ही validation loss बढ़ना शुरू हो जाए — training रोक दी जाती है
  • इससे overfitting रोका जाता है

✅ D. Data Augmentation:

  • Image, text, या audio data को थोड़ा modify करके training set को बड़ा बनाना
  • इससे model को general patterns सीखने में मदद मिलती है

✅ E. Batch Normalization:

nn.BatchNorm1d(num_features)

🔁 PyTorch Example with Dropout:

import torch.nn as nn

model = nn.Sequential(
nn.Linear(100, 50),
nn.ReLU(),
nn.Dropout(p=0.5),
nn.Linear(50, 10)
)

🧠 Diagnostic Plot:

Epochs →📉 Train Loss📈 Test Loss
1–5High → LowHigh → Low
6–20LowStarts rising → Overfitting starts

🎯 Summary:

ConceptDefinitionSolution
UnderfittingModel कम सीखता हैBigger model, more training
OverfittingModel बहुत ज़्यादा सीख लेता हैRegularization
RegularizationGeneralization सुधारने की तकनीकDropout, L2, Data Augmentation

📝 Practice Questions:

  1. Underfitting और Overfitting में क्या अंतर है?
  2. Dropout कैसे काम करता है?
  3. L2 Regularization का loss function में क्या योगदान है?
  4. Early stopping क्यों काम करता है?
  5. Data augmentation overfitting से कैसे बचाता है?