Introduction of PyTorch

आपने TensorFlow और Keras सीख लिया — अब बारी है PyTorch की, जो research और flexibility के लिए Deep Learning community में सबसे लोकप्रिय framework है।

PyTorch एक open-source deep learning framework है जिसे Facebook AI Research Lab (FAIR) ने 2016 में विकसित किया।

यह framework खासकर researchers और advanced developers के बीच पसंदीदा है, क्योंकि यह:

  • Dynamic computation graph प्रदान करता है (runtime पर बदलता है)
  • Pythonic और NumPy जैसा syntax देता है
  • GPU acceleration आसानी से करता है

🔑 Features:

FeatureDescription
🧮 Dynamic GraphsReal-time control (ज़्यादा flexibility)
📊 Tensor LibraryNumPy जैसे operations with GPU support
🧠 AutogradAutomatic gradient calculation
🔧 Modular APINeural nets = Modules
🖥️ GPU ReadyCUDA support

🔶 2. PyTorch Installation

pip install torch torchvision

🔷 3. Tensors in PyTorch

Tensors are multi-dimensional arrays (similar to NumPy arrays) but with GPU support.

import torch

x = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
print(x.shape) # torch.Size([2, 2])
print(x + x) # Tensor addition
print(x @ x.T) # Matrix multiplication

✅ Use GPU:

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
x = x.to(device)

🔷 4. Autograd – Automatic Differentiation

x = torch.tensor(2.0, requires_grad=True)
y = x**3 + 2*x
y.backward()
print(x.grad) # dy/dx = 3x^2 + 2 = 3*2^2 + 2 = 14

🔷 5. Building a Simple Neural Network

🔨 Step 1: Import Libraries

🔨 Step 1: Import Libraries

import torch
import torch.nn as nn
import torch.optim as optim

🔨 Input and Output for XOR

X = torch.tensor([[0.,0.],[0.,1.],[1.,0.],[1.,1.]])
y = torch.tensor([[0.],[1.],[1.],[0.]])

🔨 Step 2: Define Model


class MyNet(nn.Module):
def __init__(self):
super(MyNet, self).__init__()
self.fc1 = nn.Linear(2, 4)
self.fc2 = nn.Linear(4, 1)

def forward(self, x):
x = torch.relu(self.fc1(x))
return torch.sigmoid(self.fc2(x))

🔨 Step 3: Instantiate Model

model = MyNet()

🔨 Step 4: Define Loss and Optimizer

criterion = nn.BCELoss()
optimizer = optim.Adam(model.parameters(), lr=0.01)

🔨 Step 5: Train the Model

for epoch in range(100):
y_pred = model(X)
loss = criterion(y_pred, y)

optimizer.zero_grad()
loss.backward()
optimizer.step()

print(f"Epoch {epoch}, Loss: {loss.item()}")

🔧 Important PyTorch Modules

ModuleDescription
torch.TensorMain data structure
torch.nnFor building neural nets
torch.nn.functionalActivation functions, loss functions
torch.optimOptimizers like Adam, SGD
torch.utils.dataDataset and DataLoader tools
torchvisionImage datasets and transformations

🔷 6. Example: XOR with MLP

X = torch.tensor([[0.,0.],[0.,1.],[1.,0.],[1.,1.]])
y = torch.tensor([[0.],[1.],[1.],[0.]])

model = nn.Sequential(
nn.Linear(2, 4),
nn.ReLU(),
nn.Linear(4, 1),
nn.Sigmoid()
)

loss_fn = nn.BCELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.1)

for epoch in range(2000):
y_pred = model(X)
loss = loss_fn(y_pred, y)

optimizer.zero_grad()
loss.backward()
optimizer.step()

if epoch % 200 == 0:
print(f"Epoch {epoch}, Loss: {loss.item()}")

📝 Practice Questions:

  1. PyTorch और TensorFlow में मुख्य अंतर क्या है?
  2. PyTorch में tensor कैसे बनाते हैं?
  3. Autograd का उपयोग gradient के लिए कैसे करते हैं?
  4. एक simple model class कैसे बनाते हैं?
  5. Sequential API और custom model class में क्या फर्क है?

🧠 Summary Table

ConceptExplanation
TensorPyTorch का data container (NumPy + GPU)
AutogradAutomatic differentiation
nn.ModuleNeural network architecture का base class
OptimizerParameters को update करता है
Loss FunctionModel की गलती measure करता है

TensorFlow and Keras Basics

अब जब आपने Deep Learning के theory और models (जैसे CNN, RNN, BERT) अच्छे से समझ लिए हैं —
तो अगला practical step है:
⚙️ TensorFlow और Keras के साथ Deep Learning models बनाना सीखना।


🔷 1. TensorFlow क्या है?

TensorFlow एक open-source deep learning framework है जिसे Google ने बनाया है।
यह numerical computation और large-scale machine learning models के लिए design किया गया है।

🧠 TensorFlow का नाम “Tensor” (data structure) + “Flow” (computation graph) से आया है।


✅ Key Features:

FeatureDetail
📊 Automatic DifferentiationGradient calculation
🧮 GPU/TPU Supportतेज़ computation
🧠 High-level + Low-level APIsFlexibility
🔧 DeploymentAndroid, Web, Edge devices
🤝 EcosystemTF Hub, TF Lite, TF.js, TF-Serving

🔷 2. Keras क्या है?

Keras एक high-level deep learning API है, जो TensorFlow के ऊपर चलता है।
यह models को लिखना, train करना और debug करना बहुत आसान बना देता है।

🎯 “Keras = Simplicity + Productivity + Modularity”


✅ Keras क्यों चुनें?

BenefitReason
🚀 Easy to LearnPythonic syntax
🧩 ModularLayers, Optimizers, Loss अलग-अलग
🧠 PowerfulAdvanced models possible
🔧 Fast prototypingजल्दी result देखने के लिए
🔌 TF BackendTensorFlow की ताकत use करता है

🔷 3. Tensor, Model, and Layer Basics

🔹 Tensor:

Multidimensional array (जैसे NumPy array, लेकिन GPU-compatible)

import tensorflow as tf
x = tf.constant([[1, 2], [3, 4]])
print(x.shape) # (2, 2)

🔹 Layer:

Neural network का एक building block (Dense, Conv2D, LSTM)

from tensorflow.keras.layers import Dense
dense = Dense(units=64, activation='relu')

🔹 Model:

Input से Output तक का पूरा network architecture

from tensorflow.keras.models import Sequential

model = Sequential([
Dense(128, activation='relu'),
Dense(10, activation='softmax')
])

🔷 4. Keras में Model बनाना (Step-by-Step)

✅ Step 1: Import

import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense

✅ Step 2: Model Define

model = Sequential([
Dense(64, activation='relu', input_shape=(100,)),
Dense(10, activation='softmax')
])

✅ Step 3: Compile

model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)

✅ Step 4: Train

model.fit(x_train, y_train, epochs=10, batch_size=32)

✅ Step 5: Evaluate

model.evaluate(x_test, y_test)

🧪 Example: Simple Binary Classifier

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense

model = Sequential([
Dense(16, activation='relu', input_shape=(2,)),
Dense(1, activation='sigmoid')
])

model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

model.fit(X_train, y_train, epochs=20)

🔧 Useful Layers in Keras

LayerUse
DenseFully connected layer
Conv2DImage convolution layer
LSTM / GRUSequence modeling
DropoutRegularization
FlattenInput flattening
EmbeddingWord embedding for NLP

🧠 Visualization: Model Summary

model.summary()

📝 Practice Questions:

  1. TensorFlow और Keras में क्या अंतर है?
  2. Sequential model क्या होता है?
  3. Model को compile करने में किन चीज़ों की ज़रूरत होती है?
  4. Dense layer क्या है?
  5. एक simple 3-layer model का कोड लिखिए।

🧠 Summary Table

ConceptDescription
TensorFlowGoogle का ML framework
KerasEasy high-level API
TensorMultidimensional data
LayerModel का हिस्सा (Dense, Conv)
ModelComplete NN architecture

Transformers and BERT

अब हम NLP के सबसे क्रांतिकारी अविष्कारों की ओर बढ़ते हैं —
🚀 Transformers और BERT — जिन्होंने NLP की दुनिया को पूरी तरह बदल दिया है।


🔶 1. Transformers: Introduction

Transformer architecture 2017 में Google ने पेश किया, पेपर:

📄 “Attention is All You Need” — Vaswani et al.

इसने Recurrent Networks (RNN, LSTM) की dependency को हटा दिया और NLP को पूरी तरह से revolutionize कर दिया।


📐 Transformer की Key Idea: Self-Attention

हर word sentence के बाकी सभी words के context को साथ में समझता है, न कि केवल पिछले शब्दों को।


🔧 Architecture Overview

Transformer दो मुख्य हिस्सों में बंटा होता है:

[Encoder] →→→→→→→→→ [Decoder]
PartRole
EncoderInput text को समझना (e.g., sentence meaning)
DecoderOutput generate करना (e.g., translation, caption)

Note: BERT सिर्फ Encoder यूज़ करता है, GPT सिर्फ Decoder।


🔁 Self-Attention Mechanism

हर शब्द input में बाकी सभी शब्दों से relate करता है:

Sentence: "The cat sat on the mat"
"cat" → attends to "the", "sat", "mat" etc. via attention scores

🔢 Attention Equation:

जहाँ:

  • Q: Query
  • K: Key
  • V: Value
  • dk: Key vector dimension

⚙️ Transformer के Components:

ComponentExplanation
🔹 Multi-Head AttentionParallel attention layers for better learning
🔹 Positional EncodingSequence order की जानकारी add करता है
🔹 Feedforward NetworkLinear + non-linear layers
🔹 Layer NormalizationStable training
🔹 Residual ConnectionsGradient flow बनाए रखता है

🧠 2. BERT: Bidirectional Encoder Representations from Transformers

📄 “BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding” – Devlin et al., 2018


🎯 मुख्य उद्देश्य:

  • Language Understanding — Chatbots, Q&A, classification

🔧 कैसे काम करता है?

  • BERT केवल Transformer Encoder architecture पर आधारित है।
  • यह दोनों तरफ के context को एक साथ पढ़ता है — इसलिए Bidirectional है।

📊 Pretraining Tasks:

  1. Masked Language Modeling (MLM)
    • Sentence में कुछ शब्दों को mask किया जाता है, और model को predict करना होता है।
    textCopyEditInput: "The [MASK] is shining" Output: "sun"
  2. Next Sentence Prediction (NSP)
    • दो sentences दिए जाते हैं — model को यह predict करना होता है कि दूसरा sentence पहले के बाद आता है या नहीं।

📦 Pretrained BERT Models:

VariantDescription
bert-base-uncasedLowercase English, 12 layers
bert-large-uncased24 layers, large model
DistilBERTLightweight, faster
Multilingual BERT100+ languages

🔧 BERT Applications:

TaskExample
✅ Sentiment Analysis“I love this product!” → Positive
🧠 Question Answering“Where is Taj Mahal?” → “Agra”
✍️ Named Entity Recognition“Barack Obama is from USA” → Person, Country
💬 ChatbotsIntent understanding
📃 Text ClassificationNews, spam, legal docs

🧰 Example: HuggingFace Transformers

from transformers import BertTokenizer, BertModel

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

inputs = tokenizer("I love deep learning", return_tensors="pt")
outputs = model(**inputs)

🧠 Transformer vs BERT

AspectTransformerBERT
TypeGeneral architecturePretrained NLP model
StructureEncoder + DecoderOnly Encoder
DirectionDependsBidirectional
ApplicationTranslation, captioningUnderstanding, classification

📈 Transformers & BERT Impact

AreaImpact
📚 ResearchNLP को neural-level accuracy
🗣️ ChatbotsSmarter conversations
🧾 Legal/MedicalAutomated document understanding
🧠 AI ModelsFoundation for GPT, T5, RoBERTa, etc.

📝 Practice Questions:

  1. Transformer architecture में self-attention का क्या role है?
  2. BERT bidirectional क्यों है?
  3. Masked Language Modeling का मतलब क्या है?
  4. BERT किन NLP tasks के लिए use होता है?
  5. HuggingFace से BERT कैसे load करते हैं?

🧠 Summary Table

TermDescription
TransformerSequence model using attention mechanism
BERTBidirectional encoder for NLP tasks
MLMMask words and predict
NSPPredict sentence relationship
ApplicationsQ&A, classification, chatbot, NER

Sequence Models for Text (RNN, LSTM)

NLP की एक महत्वपूर्ण category — Sequence Models — की ओर बढ़ते हैं।
Text data inherently sequential होता है (हर word का order matter करता है), और इसी कारण हमें ऐसे models की ज़रूरत होती है जो sequence को याद रख सकें


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

Text = शब्दों का क्रम (sequence of words):
जैसे: "मैं स्कूल जा रहा हूँ।"
यहाँ “जा रहा” और “जा रही” में फर्क होता है — क्रम मायने रखता है।

🧠 Sequence models का कार्य है – इस क्रम और संदर्भ को समझना।


🔁 2. Recurrent Neural Network (RNN)

📌 उद्देश्य:

  • ऐसे model बनाना जो पिछले शब्दों का context याद रखकर अगला शब्द समझें या predict करें।

🔧 Working (Step-by-step):

हर समय step पर input आता है (word) और hidden state update होता है:

x₁ → x₂ → x₃ ...
↓ ↓ ↓
h₁ → h₂ → h₃ → Output

यह hidden state ht पिछली जानकारी को अगली word processing में उपयोग करता है।


⚠️ RNN की सीमाएं (Limitations)

समस्याविवरण
❌ Vanishing Gradientलंबे sentences में पिछले context की जानकारी खो जाती है
❌ Fixed memoryपुराने शब्दों को ठीक से नहीं याद रख पाता
❌ Slow trainingSequential nature के कारण parallelization कठिन

🔄 3. LSTM (Long Short-Term Memory)

LSTM, RNN का एक बेहतर version है — जिसे इस समस्या को हल करने के लिए 1997 में Hochreiter & Schmidhuber ने प्रस्तावित किया।


📌 Core Idea:

LSTM में एक special memory cell होता है जो decide करता है कि कौन-सी जानकारी याद रखनी है, कौन-सी भूलनी है, और कौन-सी update करनी है।


🧠 Key Components of LSTM:

GateRole
🔒 Forget Gateक्या भूलना है
🔓 Input Gateक्या जोड़ना है
📤 Output Gateअगले step में क्या भेजना है

📊 LSTM Architecture (Flow)

Input xₜ → [Forget Gate, Input Gate, Output Gate] → Cell State → Output hₜ

LSTM sequence को ज़्यादा देर तक याद रखने में सक्षम होता है।


🔢 Equations (Simplified):


🧪 Practical Example:

📌 Use Case: Text Generation

  • Input: “The sun”
  • Output: “The sun is shining brightly today…”

LSTM last words को याद रखकर अगला word predict करता है।


🧰 Python Code Example (PyTorch)

import torch.nn as nn

class LSTMModel(nn.Module):
def __init__(self, vocab_size, embed_dim, hidden_dim):
super().__init__()
self.embedding = nn.Embedding(vocab_size, embed_dim)
self.lstm = nn.LSTM(embed_dim, hidden_dim, batch_first=True)
self.fc = nn.Linear(hidden_dim, vocab_size)

def forward(self, x):
x = self.embedding(x)
out, _ = self.lstm(x)
out = self.fc(out)
return out

🤖 RNN vs LSTM Comparison

FeatureRNNLSTM
MemoryShortLong
GatesNoYes (forget, input, output)
Vanishing GradientCommonHandled
Use CaseSimple patternsComplex sequences

📈 Applications of Sequence Models

TaskUse
🔤 Language ModelingNext word prediction
✍️ Text GenerationPoetry, story generation
📧 Spam DetectionSequential classification
🎧 Speech RecognitionAudio-to-text
🧠 Sentiment AnalysisReview understanding
💬 ChatbotsHuman-like conversation

📝 Practice Questions:

  1. Sequence model की जरूरत NLP में क्यों पड़ती है?
  2. RNN का drawback क्या है?
  3. LSTM कैसे context याद रखता है?
  4. LSTM में तीन मुख्य gates कौन से हैं?
  5. एक छोटा सा PyTorch LSTM model का code लिखिए।

🧠 Summary Table

TermMeaning
RNNSequence modeling network
LSTMLong-memory capable RNN
GatesDecide memory control
ApplicationText, audio, time-series
LimitationRNN: short memory; LSTM: handles long-term context

Word Embeddings (Word2Vec, GloVe)

ब हम Natural Language Processing (NLP) का एक बहुत ही महत्वपूर्ण विषय सीखते हैं —
🧠 Word Embeddings, जो deep learning-based NLP की नींव रखते हैं।


🔶 1. Word Embeddings क्या हैं?

Word Embeddings वो तकनीक है जिससे शब्दों को संख्याओं (vectors) में represent किया जाता है — इस तरह कि उनके semantic (meaningful) रिश्ते भी capture हों।

🎯 “Word Embeddings words को mathematical space में ऐसे map करते हैं कि उनके बीच के अर्थ संबंध भी साफ़ दिखें।”


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

Traditional NLP methods जैसे One-Hot Encoding सिर्फ पहचानते हैं कि कोई शब्द है या नहीं — लेकिन वो शब्दों के अर्थ या संबंध को नहीं समझते।

Techniqueसमस्या
One-HotHigh dimensional, sparse, no meaning
EmbeddingDense, low-dimensional, meaningful representation

📏 2. Embedding Vector कैसा होता है?

Word → Vector (जैसे 300 dimensions का dense vector):

WordVector (छोटा version)
king[0.25, 0.67, …, 0.12]
queen[0.23, 0.65, …, 0.14]
banana[0.10, 0.32, …, 0.91]
democracy[0.55, 0.40, …, 0.60]

👉 Words जो अर्थ में करीब होते हैं, उनके vectors भी पास होते हैं।


📊 3. Word2Vec

🧪 Developed By:

Google (2013) — Tomas Mikolov et al.

⚙️ Idea:

  • शब्दों के context के आधार पर embedding सीखना।
  • “You shall know a word by the company it keeps.”

🔁 Two Architectures:

Architectureकार्य
CBOW (Continuous Bag of Words)Nearby words से center word predict करता है
Skip-GramCenter word से आसपास के words predict करता है

🔍 Word2Vec Diagram:

[The] [king] [of] [Spain] → [rules]
↑ context → target

CBOW: Predict “rules”
Skip-Gram: Predict “The”, “king”, “Spain” ← “rules”


🧠 4. GloVe (Global Vectors)

🧪 Developed By:

Stanford (2014) — Jeffrey Pennington et al.

⚙️ Idea:

  • Word2Vec local context पर निर्भर करता है
  • GloVe पूरे corpus के co-occurrence matrix का उपयोग करता है

🧾 Objective:

Find word vectors so that: 

जहाँ Pij​ दो शब्दों के co-occurrence का ratio है।


🔍 Word2Vec vs GloVe

AspectWord2VecGloVe
ContextLocal windowGlobal corpus statistics
TypePredictiveCount-based
TrainingFasterSlower (matrix-based)
AccuracyHighSlightly better for analogies
Use CaseFast semantic learningFine-grained vector space

🧪 5. Real Example: Word Analogy

king−man+woman≈queen

Word Embeddings में ये relation mathematically मिल जाता है! 🔥


🧰 6. Python Example (Gensim – Word2Vec)

from gensim.models import Word2Vec

sentences = [["I", "love", "deep", "learning"],
["Word2Vec", "captures", "semantic", "meaning"]]

model = Word2Vec(sentences, vector_size=50, window=2, min_count=1, sg=1)
print(model.wv["deep"]) # Embedding vector
print(model.wv.most_similar("learning"))

📌 7. Pretrained Embedding Sources

EmbeddingSource
GloVehttps://nlp.stanford.edu/projects/glove/
Word2Vechttps://code.google.com/archive/p/word2vec/
FastTexthttps://fasttext.cc/
BERT EmbeddingsHuggingFace (transformers library)

📈 8. Applications

Use CaseHow Embeddings Help
🗣️ ChatbotsWords with similar meanings treated similarly
📝 Sentiment Analysis“bad” vs “awful” को पहचानना
🔁 TranslationSemantic similarity across languages
💬 Q&A SystemsUnderstanding user intent

📝 Practice Questions:

  1. Word Embeddings क्या होते हैं?
  2. Word2Vec के दो architecture कौन-कौन से हैं?
  3. GloVe और Word2Vec में मुख्य अंतर बताइए।
  4. एक embedding vector की structure को समझाइए।
  5. Word analogy कैसे काम करता है embedding space में?

🧠 Summary Table

TopicSummary
Word EmbeddingWords → meaningful vectors
Word2VecLearns from local context (CBOW, Skip-gram)
GloVeLearns from global co-occurrence
AdvantageSemantic similarity capture करना
ApplicationChatbots, translation, classification