📚 সমস্ত অধ্যায় দেখুন
অধ্যায়/ফেজ 4 · Phase 4 · Deep Learning
4.4৩০ মিনিট পড়া29 / 68

RNN, LSTM, GRU — Sequence এর জন্য

Recurrent Networks

Memory cell, gate, sequence modeling।

Hook — Sequence এর গল্প

ভাষা, music, time series — সব sequence। আগের শব্দ পরের শব্দের অর্থ ঠিক করে। RNN এমন network যার ‘স্মৃতি’ আছে — আগের timestep এর hidden state পরের timestep এ যায়।

Vanilla RNN

h_t = tanh(W_x · x_t + W_h · h_{t-1} + b)

প্রতি timestep এ একই weight ব্যবহৃত হয় — weight sharing across time।

সমস্যা

Long sequence এ vanishing gradient — পুরোনো information হারিয়ে যায়।

LSTM — Long Short-Term Memory

Hochreiter & Schmidhuber (1997) — তিনটি gate দিয়ে কোন information রাখবে, কোনটা ফেলবে, কোনটা বের করবে — সবই learn করে।

  • Forget Gate — পুরোনো cell state এর কতটুকু রাখবে।
  • Input Gate — নতুন information কতটুকু যোগ করবে।
  • Output Gate — hidden state এ কী বেরোবে।
  • Cell State — long-term memory highway।

GRU — Gated Recurrent Unit

LSTM এর simpler version — দুটো gate (reset + update), কোনো আলাদা cell state নেই। কম parameter, প্রায় সমান performance — ছোট dataset এ ভালো।

Variants

  • Bidirectional RNN — সামনে এবং পিছনে দুদিক থেকে context।
  • Stacked RNN — একাধিক layer।
  • Encoder-Decoder — seq2seq (translation)।

Code — PyTorch LSTM

lstm_text.py
import torch.nn as nn

class TextClassifier(nn.Module):
    def __init__(self, vocab_size, embed=128, hidden=256, classes=2):
        super().__init__()
        self.emb  = nn.Embedding(vocab_size, embed)
        self.lstm = nn.LSTM(embed, hidden, batch_first=True, bidirectional=True)
        self.fc   = nn.Linear(hidden * 2, classes)

    def forward(self, x):                # x: (batch, seq)
        e = self.emb(x)                  # (batch, seq, embed)
        out, (h, c) = self.lstm(e)
        last = out[:, -1, :]             # শেষ timestep
        return self.fc(last)

Applications

  • Sentiment analysis, text classification।
  • Machine translation (pre-Transformer era)।
  • Speech recognition।
  • Time series prediction।
  • Music generation।

Limitations → Transformer এর প্রয়োজন

  • Sequential computation — parallelize করা কঠিন।
  • Long-range dependency এখনো কঠিন।
  • Transformer এসে এই দুটোই সমাধান করেছে।

Summary

এক নজরে

RNN = sequence memory; LSTM/GRU = gate দিয়ে long-term memory; Bidirectional = উভয় দিকের context।