LSTM and GRU Networks

(लंबी याददाश्त वाले नेटवर्क – 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 विकसित की गईं:

ProblemSolution
Memory fadesMemory Cells (LSTM)
Gradient vanishesGates 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

FeatureLSTMGRU
Gates3 (Forget, Input, Output)2 (Reset, Update)
Cell StateYes (separate from h)No (merged with h)
ComplexityHigherLower
SpeedSlower (more parameters)Faster
PerformanceGood for longer sequencesComparable on many tasks
Use CaseText, speech, time-seriesSimilar, 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?

ScenarioUse
Complex dependenciesLSTM
Faster training neededGRU
Simpler datasetsGRU
Large vocabulary/textLSTM
Low memory environmentGRU

📝 Practice Questions:

  1. LSTM और GRU में क्या अंतर है?
  2. LSTM में Forget gate क्या करता है?
  3. GRU में Cell State क्यों नहीं होता?
  4. LSTM का output कैसे निकाला जाता है?
  5. LSTM और GRU के फायदे और नुकसान क्या हैं?

🎯 Summary

ModelMemoryGatesUse Case
RNNShortNoneSimple sequences
LSTMLong3Complex dependencies
GRUMedium2Fast + good performance