(लंबी याददाश्त वाले नेटवर्क – RNN का विकास)
अब हम Recurrent Neural Networks (RNN) के दो शक्तिशाली upgrades को समझते हैं —
👉 LSTM (Long Short-Term Memory) और GRU (Gated Recurrent Unit) जिन्होंने RNN की Vanishing Gradient जैसी समस्याओं का समाधान किया।
🔶 1. Why LSTM and GRU?
RNN बहुत लंबी sequence data को ठीक से process नहीं कर पाते क्योंकि gradients vanish हो जाते हैं।
इस समस्या को दूर करने के लिए Gated Mechanisms वाली architectures विकसित की गईं:
Problem | Solution |
---|---|
Memory fades | Memory Cells (LSTM) |
Gradient vanishes | Gates control flow (LSTM/GRU) |
🧠 2. LSTM (Long Short-Term Memory)
📌 Introduced by: Hochreiter & Schmidhuber (1997)
LSTM एक special RNN architecture है जो Memory Cell का उपयोग करता है।
इसमें तीन मुख्य गेट्स (gates) होते हैं जो यह नियंत्रित करते हैं कि information कितनी रखनी है, कितनी भूलनी है, और कितनी बाहर भेजनी है।
🔹 LSTM Cell Diagram:
┌────────────┐
│ Forget │ → decides what to forget
x_t ──►──┤ Gate ├──┐
└────────────┘ │
▼
┌────────────┐
│ Input │ → decides what new info to store
│ Gate ├──┐
└────────────┘ │
▼
┌────────────┐
│ Cell State │ ← updated memory
└────────────┘
▲
┌────────────┐ │
│ Output │ └──→ h_t (output/hidden)
│ Gate ├──────►
└────────────┘
🔹 LSTM Equations:
Let’s denote:

🧠 3. GRU (Gated Recurrent Unit)
📌 Introduced by: Cho et al. (2014)
GRU को LSTM से सरल और तेज़ बनाया गया है। इसमें सिर्फ
दो gates होते हैं:
- Update Gate (z)
- Reset Gate (r)
GRU में अलग-अलग memory cell नहीं होता — hidden state को ही memory की तरह प्रयोग किया जाता है।
🔹 GRU Equations:

🔄 4. LSTM vs GRU – Comparison Table
Feature | LSTM | GRU |
---|---|---|
Gates | 3 (Forget, Input, Output) | 2 (Reset, Update) |
Cell State | Yes (separate from h) | No (merged with h) |
Complexity | Higher | Lower |
Speed | Slower (more parameters) | Faster |
Performance | Good for longer sequences | Comparable on many tasks |
Use Case | Text, speech, time-series | Similar, but with simpler models |
🔧 5. PyTorch Example: LSTM and GRU
LSTM:
import torch.nn as nn
lstm = nn.LSTM(input_size=10, hidden_size=20, num_layers=1, batch_first=True)
input = torch.randn(5, 8, 10)
h0 = torch.zeros(1, 5, 20)
c0 = torch.zeros(1, 5, 20)
output, (hn, cn) = lstm(input, (h0, c0))
GRU:
gru = nn.GRU(input_size=10, hidden_size=20, num_layers=1, batch_first=True)
output, hn = gru(input, h0)
📈 6. When to Use Which?
Scenario | Use |
---|---|
Complex dependencies | LSTM |
Faster training needed | GRU |
Simpler datasets | GRU |
Large vocabulary/text | LSTM |
Low memory environment | GRU |
📝 Practice Questions:
- LSTM और GRU में क्या अंतर है?
- LSTM में Forget gate क्या करता है?
- GRU में Cell State क्यों नहीं होता?
- LSTM का output कैसे निकाला जाता है?
- LSTM और GRU के फायदे और नुकसान क्या हैं?
🎯 Summary
Model | Memory | Gates | Use Case |
---|---|---|---|
RNN | Short | None | Simple sequences |
LSTM | Long | 3 | Complex dependencies |
GRU | Medium | 2 | Fast + good performance |