Introduction to RNNs

(रीकरेंट न्यूरल नेटवर्क का परिचय)


🔶 1. What is an RNN?

RNN (Recurrent Neural Network) एक ऐसा neural network है जो input के रूप में मिलने वाले sequence data को process करता है, और past inputs की जानकारी को याद रखकर अगले outputs तय करता है।

Simple terms में:
RNNs “memory” रखते हैं और इससे वो time-dependent problems solve कर सकते हैं।


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

Traditional Neural Networks (जैसे MLP या CNN) हर input को independent मानते हैं।

लेकिन sequential data (जैसे भाषा, मौसम का डेटा, stock prices) में ऐसा नहीं होता —
पहले शब्द या डेटा का अगली स्थिति पर प्रभाव होता है।

🧠 RNN इस dependency को capture करने में सक्षम है।


📈 3. Examples of Sequence Tasks:

ApplicationInputOutput
Sentiment AnalysisSentenceSentiment
Machine TranslationSentence in EnglishSentence in Hindi
Speech RecognitionAudio SignalText
Time Series ForecastingPast valuesFuture value

🧱 4. RNN Architecture:

Basic Structure:

x₁ → [RNN Cell] → h₁  
x₂ → [RNN Cell] → h₂
x₃ → [RNN Cell] → h₃
... and so on

हर step पर output ht निर्भर करता है:

जहाँ:


🔁 5. RNN Memory Concept:

RNN में hidden state hth_tht​ एक प्रकार की memory की तरह काम करता है।
हर नए input के साथ यह update होता है — जिससे model को context याद रहता है।


🔄 6. Unrolling an RNN:

RNN को एक loop में चलाया जाता है, लेकिन हम इसे unroll कर सकते हैं:

x1 → [ ] → h1  
x2 → [ ] → h2
x3 → [ ] → h3

→ यह loop-based representation है जिसमें एक ही cell बार-बार चलता है।


🔧 7. PyTorch Code: Basic RNN Example

import torch
import torch.nn as nn

rnn = nn.RNN(input_size=10, hidden_size=20, num_layers=1, batch_first=True)

input = torch.randn(5, 3, 10) # (batch, sequence, input_size)
h0 = torch.zeros(1, 5, 20) # (num_layers, batch, hidden_size)

output, hn = rnn(input, h0)

print(output.shape) # → [5, 3, 20]
print(hn.shape) # → [1, 5, 20]

⚠️ 8. Limitations of Vanilla RNN

ProblemReason
Vanishing GradientLong-term dependencies भूल जाते हैं
Exploding GradientGradient बहुत बढ़ जाता है
Short Memoryकेवल कुछ पिछले steps को याद रख पाता है

👉 इसका समाधान है: LSTM और GRU (अगले topics में आएगा)


📘 Summary:


📝 Practice Questions:

  1. RNN किस प्रकार की समस्याओं को हल करने के लिए उपयुक्त है?
  2. Hidden state का क्या काम होता है RNN में?
  3. RNN को unroll करना क्या होता है?
  4. RNN के कौन-कौन से limitations हैं?
  5. PyTorch में एक simple RNN कैसे implement करते हैं?


Famous CNN Architectures (LeNet, AlexNet, VGG, ResNet)


🔶 1. LeNet-5 (1998) – By Yann LeCun

🕰 वर्ष: 1998
👤 Developer: Yann LeCun, Léon Bottou, Yoshua Bengio, Patrick Haffner

📌 विवरण:

LeNet-5 को Yann LeCun ने विकसित किया था, और इसे पहली बार बैंकिंग सिस्टम में ZIP code पढ़ने के लिए उपयोग किया गया।
यह architecture CNN की पहली वास्तविक success story मानी जाती है।

📚 महत्व:

  • MNIST जैसे digit recognition datasets पर काफी सफल रहा
  • पहली बार convolution, pooling, और fully connected layers का इस्तेमाल एक structure में किया गया
  • यह काम Bell Labs में किया गया था

📌 Use Case: Handwritten digit recognition (MNIST)

🧱 Architecture:

Input: 32x32 Grayscale Image  
→ Conv (6 filters, 5x5)
→ Avg Pooling
→ Conv (16 filters, 5x5)
→ Avg Pooling
→ Flatten
→ FC (120)
→ FC (84)
→ Output (10 classes)

✅ Highlights:

  • पहली सफल CNN architecture
  • बहुत कम parameters
  • आज भी MNIST जैसे tasks पर उपयोगी

🔶 2. AlexNet (2012) – By Alex Krizhevsky et al.

📌 Use Case: ImageNet Large Scale Visual Recognition Challenge (ILSVRC)

🕰 वर्ष: 2012
👤 Developer: Alex Krizhevsky, Ilya Sutskever, Geoffrey Hinton
🏫 संस्थान: University of Toronto

📌 विवरण:

AlexNet ने 2012 में ImageNet Large Scale Visual Recognition Challenge (ILSVRC) में हिस्सा लिया और बाकी सभी models से बहुत आगे निकल गया — 15.3% error से सीधे 10.1% पर आया।

📚 महत्व:

  • Deep Learning की mainstream लोकप्रियता इसी model से शुरू हुई
  • First CNN जिसने GPU का उपयोग करके बहुत बड़ा dataset train किया
  • Introduced ReLU, Dropout, और Data Augmentation

🧱 Architecture:

Input: 224x224x3 Image  
→ Conv1 (96 filters, 11x11, stride 4)
→ MaxPool
→ Conv2 (256 filters, 5x5)
→ MaxPool
→ Conv3 (384 filters, 3x3)
→ Conv4 (384 filters, 3x3)
→ Conv5 (256 filters, 3x3)
→ MaxPool
→ Flatten
→ FC (4096)
→ FC (4096)
→ FC (1000)

✅ Highlights:

  • ReLU activation introduced
  • Used Dropout and Data Augmentation
  • Trained on GPU
  • Won ILSVRC 2012 with huge margin

🔶 3. VGGNet (2014) – By Oxford (Simonyan & Zisserman)

📌 Use Case: ImageNet Classification

🕰 वर्ष: 2014
👤 विकासकर्ता: Karen Simonyan & Andrew Zisserman
🏫 संस्थान: University of Oxford – Visual Geometry Group (VGG)

📌 विवरण:

VGGNet ने convolution layers को एक uniform pattern (3×3 filters) में रखा, जिससे deeper networks को design करना सरल हो गया।

📚 महत्व:

  • Depth बढ़ाने से accuracy कैसे improve होती है, यह दिखाया
  • आज भी कई pre-trained models और transfer learning में उपयोग किया जाता है
  • VGG-16 और VGG-19 के रूप में दो variants प्रसिद्ध हैं

🧱 Architecture (VGG-16):

Input: 224x224x3  
→ (Conv 3x3, 64) ×2
→ MaxPool
→ (Conv 3x3, 128) ×2
→ MaxPool
→ (Conv 3x3, 256) ×3
→ MaxPool
→ (Conv 3x3, 512) ×3
→ MaxPool
→ (Conv 3x3, 512) ×3
→ MaxPool
→ Flatten
→ FC (4096)
→ FC (4096)
→ FC (1000)

✅ Highlights:

  • Simple, uniform design
  • Uses only 3×3 convolution filters
  • Very deep (~16–19 layers)
  • More accurate than AlexNet, but slower

🔶 4. ResNet (2015) – By Microsoft Research

📌 Use Case: Deep classification without degradation

🕰 वर्ष: 2015
👤 विकासकर्ता: Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
🏢 संस्थान: Microsoft Research

📌 विवरण:

ResNet ने deep learning की सबसे बड़ी समस्या — Vanishing Gradient — को solve किया, जिससे 100+ layers वाले deep networks train हो सके।

📚 महत्व:

  • Introduced Residual (Skip) Connections, जिससे deep models भी सीख सकते हैं
  • 2015 ILSVRC में 1st position हासिल की
  • आज के अधिकांश deep vision models (e.g., Faster R-CNN, Mask R-CNN, ResNeXt) ResNet के foundation पर बने हैं

🧱 Key Innovation: Residual Connections

Output = F(x) + x

🧱 Architecture (ResNet-50):

  • Uses bottleneck blocks:
    • Conv1x1 → Conv3x3 → Conv1x1
    • Shortcut connections (skip layers)
  • Total ~50 layers
  • Variants: ResNet-18, 34, 50, 101, 152

✅ Highlights:

  • Solves vanishing gradient problem
  • Enables very deep networks (100+ layers)
  • Won ILSVRC 2015

📊 Comparison Table:

ModelYearLayersKey FeatureUse Case
LeNet1998~7SimplicityDigit Recognition
AlexNet20128ReLU, GPU, DropoutLarge-scale image classification
VGG-16201416Uniform 3×3 filtersImageNet
ResNet-50201550Residual connectionsDeep classification

📈 Visual Insight:

  • LeNet → Basic template
  • AlexNet → CNN popularized
  • VGG → Depth with simplicity
  • ResNet → Deepest with performance

🔧 PyTorch Example: Load Pretrained ResNet

from torchvision import models

model = models.resnet50(pretrained=True)

📝 Practice Questions:

  1. LeNet और AlexNet में क्या अंतर है?
  2. VGG architecture में सभी convolutions का आकार 3×3 क्यों रखा गया?
  3. ResNet में residual connection का क्या लाभ है?
  4. AlexNet को GPU पर क्यों train किया गया था?
  5. ResNet को 100+ layers तक train करना कैसे संभव हो पाया?

🎯 Summary:

ArchitectureBest ForKey Contribution
LeNetSimple tasksCNN base design
AlexNetComplex imagesReLU, GPU training
VGGClean structureDeep with uniformity
ResNetUltra-deep netsSkip connections

Use of CNN in Image Classification

(छवि वर्गीकरण में CNN का उपयोग)


🔶 1. Image Classification क्या है?

📌 परिभाषा:

Image Classification एक ऐसा task है जिसमें input image को एक predefined class में classify किया जाता है।

उदाहरण: एक model को बताना कि image में dog है या cat


🎯 2. CNN क्यों बेहतर है Image Classification के लिए?

CNN में मौजूद:

  • Convolution layers → local patterns और textures पहचानती हैं
  • Pooling layers → size reduce कर feature को concentrate करती हैं
  • Dense layers → final decision लेती हैं

👉 ये सब मिलकर CNN को image data पर बहुत सक्षम बना देती हैं।


🧠 3. Typical Image Classification Pipeline (Using CNN)

[Input Image]

Convolution Layers (Feature Extraction)

ReLU + Pooling Layers

Flatten Layer

Fully Connected (Dense) Layers

Softmax (Output → Class Probabilities)

📷 4. Real-world Examples:

DatasetClassesApplication
MNIST10 (digits)Handwritten digit recognition
CIFAR-1010 (animals, vehicles)Object classification
ImageNet1000+Large-scale classification

🔍 5. Feature Hierarchy in CNN:

Layer DepthLearns What
Shallow (1-2)Edges, corners, color blobs
Mid (3-4)Textures, patterns
Deep (5+)Objects, faces, full shapes

🔧 6. PyTorch Code Example: CNN for Image Classification (CIFAR-10)

import torch.nn as nn

class CIFAR10CNN(nn.Module):
def __init__(self):
super(CIFAR10CNN, self).__init__()
self.net = nn.Sequential(
nn.Conv2d(3, 32, 3, padding=1),
nn.ReLU(),
nn.MaxPool2d(2, 2),
nn.Conv2d(32, 64, 3, padding=1),
nn.ReLU(),
nn.MaxPool2d(2, 2),
nn.Flatten(),
nn.Linear(64 * 8 * 8, 128),
nn.ReLU(),
nn.Linear(128, 10) # 10 output classes for CIFAR-10
)

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

📊 7. Output Layer (Softmax)

nn.Softmax(dim=1)
  • Converts raw outputs (logits) to probabilities
  • Highest probability class is the predicted label

📈 8. Training Process (Overview)

StepDescription
Data PreparationImage resize, normalization
Forward PassPrediction
Loss CalculationCrossEntropyLoss
Backward PassGradients calculate
OptimizationSGD, Adam, etc.
EvaluationAccuracy, Precision, Recall

✅ 9. Advantages of CNNs in Image Classification

BenefitExplanation
Local Feature ExtractionCaptures spatial hierarchy
Translation InvariancePosition of object doesn’t matter
Parameter EfficiencyFilters shared across image
End-to-End LearningNo need for manual feature extraction

📝 Practice Questions:

  1. CNN image classification में कैसे मदद करता है?
  2. एक simple CNN architecture लिखिए जो 10-class classification कर सके।
  3. Feature map क्या होता है?
  4. CNN में object recognition की hierarchy क्या होती है?
  5. PyTorch में prediction probabilities कैसे निकाली जाती हैं?

🎯 Summary:

ConceptUse in Classification
ConvolutionExtract features from images
PoolingDownsample and focus on important parts
Dense LayersFinal decision making
SoftmaxClass probability distribution
CNNEnd-to-end feature learning system

CNN Layers (Convolution, Pooling, Flatten, Dense)

(CNN में Layers कैसे काम करती हैं?)


🔶 1. Overview of CNN Architecture

CNN का उद्देश्य raw images से automatically important features निकालना और उन्हें classification, detection या segmentation के लिए इस्तेमाल करना होता है।

CNN typically निम्नलिखित layers में बँटा होता है:

[Input Image]

Convolution Layer

Activation (ReLU)

Pooling Layer

(Repeat Conv + Pool) ...

Flatten Layer

Dense Layer(s)

Output (e.g. Softmax)

🧩 2. Detailed Explanation of Each Layer


✅ A. Convolution Layer

  • Input image से features extract करता है
  • Multiple filters apply होते हैं
  • Output = Feature Maps

Math: y=w∗x+b

PyTorch:

nn.Conv2d(in_channels=3, out_channels=16, kernel_size=3, stride=1, padding=1)


✅ B. Activation Function (ReLU)

  • Non-linearity introduce करता है
  • Negative values को 0 कर देता है

f(x)=max⁡(0,x)

PyTorch:

nn.ReLU()

✅ C. Pooling Layer (MaxPooling or AvgPooling)

  • Feature map को compress करता है
  • Important features retain करता है
  • Overfitting reduce करता है

Types:

  • Max Pooling: Max value select करता है
  • Average Pooling: Average लेता है

PyTorch:

nn.MaxPool2d(kernel_size=2, stride=2)

✅ D. Flatten Layer

  • 2D feature maps को 1D vector में convert करता है
  • ताकि Dense Layer उसे process कर सके

Example:

Shape: (Batch, Channels, Height, Width) → (Batch, Features)

PyTorch:

x = x.view(x.size(0), -1)

✅ E. Fully Connected (Dense) Layer

  • Neural network के traditional layer
  • Classification या regression करता है

PyTorch:

nn.Linear(in_features=512, out_features=10)

📊 CNN Architecture Diagram (Example)

Input: 32x32x3 (RGB Image)

Conv (3x3, 16 filters) → 32x32x16

ReLU

MaxPool (2x2) → 16x16x16

Conv (3x3, 32 filters) → 16x16x32

ReLU

MaxPool (2x2) → 8x8x32

Flatten → 2048

Dense → 128

Output → 10 classes

🔧 3. PyTorch Code (Simple CNN Model)

import torch.nn as nn

class SimpleCNN(nn.Module):
def __init__(self):
super(SimpleCNN, self).__init__()
self.conv_layers = nn.Sequential(
nn.Conv2d(3, 16, 3, padding=1), # Conv1
nn.ReLU(),
nn.MaxPool2d(2, 2), # Pool1
nn.Conv2d(16, 32, 3, padding=1),# Conv2
nn.ReLU(),
nn.MaxPool2d(2, 2) # Pool2
)
self.fc_layers = nn.Sequential(
nn.Flatten(),
nn.Linear(32 * 8 * 8, 128), # Flatten to Dense
nn.ReLU(),
nn.Linear(128, 10) # Output
)

def forward(self, x):
x = self.conv_layers(x)
x = self.fc_layers(x)
return x

📈 Summary Table:

LayerPurposeOutput Shape
ConvFeatures extract(H, W, Filters)
ReLUNon-linearitySame as input
PoolingDownsample(H/2, W/2, Filters)
FlattenVector बनाना(1D features)
DensePredict classesOutput classes

📝 Practice Questions:

  1. Convolution layer में filter क्या करता है?
  2. MaxPooling और AveragePooling में क्या फर्क है?
  3. Flatten क्यों ज़रूरी होता है CNN में?
  4. Dense Layer का काम क्या होता है CNN में?
  5. PyTorch में CNN model define करने का तरीका बताइए।

What is Convolution

(कन्वोल्यूशन क्या है?)


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

Convolution एक mathematical operation है जो दो functions (या arrays) को combine करता है ताकि तीसरा function निकाला जा सके जो दोनों का अर्थपूर्ण interaction बताता है।

Deep Learning में, convolution का उपयोग image से features निकालने के लिए किया जाता है — जैसे edges, patterns, curves आदि।


🧮 Convolution in Math (1D):

जहाँ:

  • x = input
  • w = filter/kernel
  • ∗ = convolution operation

📸 2. Convolution in Images (2D Case)

✅ Image = 2D Matrix of Pixels

✅ Filter/Kernel = Small matrix (e.g. 3×3, 5×5)

Operation:

  • Filter को image के ऊपर slide किया जाता है (called stride)
  • हर जगह पर input और filter के corresponding values multiply और sum होते हैं
  • Result: एक नया feature map तैयार होता है

🧠 Example (3×3 Filter over 5×5 Image):

Input Image (5×5):
1 1 1 0 0
0 1 1 1 0
0 0 1 1 1
0 0 1 1 0
0 1 1 0 0

Filter (3×3):
1 0 1
0 1 0
1 0 1

Apply convolution → Output feature map (3×3)


🔁 Steps:

  1. Filter top-left पर रखें
  2. Overlapping values का element-wise product लें
  3. उनका sum लें → यह output feature का एक value बनेगा
  4. Filter को आगे move करें (stride से)
  5. Repeat until entire image covered

🔍 3. Why Convolution?

FeatureBenefit
LocalityNearby pixels के relationships capture होते हैं
Parameter SharingSame filter पूरे image पर use होता है → कम parameters
Translation InvarianceObject कहीं भी हो, features detect होते हैं

🖼 4. Visual Summary:

[Input Image]

[Filter/Kernel Slides]

[Feature Map Generated]

🔧 5. PyTorch Code Example:

import torch
import torch.nn as nn

conv = nn.Conv2d(in_channels=1, out_channels=1, kernel_size=3, stride=1, padding=0)

# Dummy input image: 1 channel, 1 image of size 5x5
input = torch.randn(1, 1, 5, 5)

output = conv(input)
print(output.shape) # → torch.Size([1, 1, 3, 3])

🎯 Summary:

TermMeaning
ConvolutionOperation to extract features
Kernel/FilterSmall matrix that slides over image
Feature MapOutput of convolution
StrideStep size of filter movement
PaddingExtra pixels added to retain size

📝 Practice Questions:

  1. Convolution operation image पर कैसे काम करता है?
  2. Kernel क्या होता है? इसका आकार क्यों छोटा रखा जाता है?
  3. Convolution में parameter sharing का क्या फायदा होता है?
  4. PyTorch में 2D convolution कैसे implement किया जाता है?
  5. Padding और stride का output shape पर क्या असर पड़ता है?