Knowledge / Artificial Intelligence and Data Science / Recurrent networks and LSTMs

Recurrent networks and LSTMs

Artificial Intelligence and Data Science (B.E./B.Tech) · Deep learning · free study notes for exams, placements and interviews

In short

A recurrent neural network (RNN) processes a sequence one element at a time while carrying a hidden state that summarises everything seen so far, so the same weights are reused at every time step. This weight sharing lets one model handle variable-length input — text, speech, sensor streams, prices — but training by backpropagation through time (BPTT) makes gradients vanish or explode over long spans. The LSTM (Hochreiter and Schmidhuber, 1997) and the simpler GRU (2014) solve this with gated additive memory, and remain the standard answer for long-range dependence in sequences. Universities examine the recurrence equations, unrolling, BPTT derivation, the vanishing-gradient argument and LSTM gate arithmetic; GATE DA/CS asks parameter counts, output shapes and gradient-decay reasoning. Indian employers (Jio, Bhashini-linked labs, Zoho, Freshworks, Flipkart, Swiggy, HDFC/ICICI analytics, Tata Elxsi, Qualcomm, Honeywell, ISRO/IMD groups) still use RNNs and LSTMs in speech, forecasting, fraud and edge deployments where Transformers are too heavy.

Explained

Why recurrence, and the basic cell

Input–output patterns (classification of RNN architectures)

  1. One-to-one — ordinary net, no recurrence needed.
  2. One-to-many — image captioning, music generation: one input, a generated sequence.
  3. Many-to-one — sentiment classification, ECG arrhythmia detection: read the whole sequence, output once (usually from h_T or a mean/max pool over all h_t).
  4. Many-to-many, synchronised (T_in = T_out) — POS tagging, named-entity recognition, per-frame labelling.
  5. Many-to-many, asynchronous (encoder–decoder / seq2seq) — translation, summarisation, speech-to-text: an encoder compresses the input to a context vector, a decoder emits the output sequence.
  6. Bidirectional RNN (BiRNN/BiLSTM): one pass left-to-right, one right-to-left, states concatenated — doubles parameters, gives both past and future context. Valid only when the whole sequence is available (not for real-time/streaming or autoregressive generation).
  7. Stacked/deep RNN: layer 1's output sequence is layer 2's input; 2–4 layers typical. Depth in *features* is separate from depth in *time*.

BPTT — backpropagation through time

Vanishing and exploding gradients

LSTM — the gated cell

Training recurrent models in practice

Key points

Formulas and examples

Simple RNN: h_t = tanh(W_xh·x_t + W_hh·h_{t−1} + b_h); ŷ_t = softmax(W_hy·h_t + b_y)
x_t ∈ ℝm (input dim m), h_t ∈ ℝn (hidden size n), W_xh ∈ ℝ^{n×m}, W_hh ∈ ℝ^{n×n} (all dimensionless)
LSTM: f_t = σ(W_f[h_{t−1}, x_t] + b_f); i_t = σ(W_i[…] + b_i); o_t = σ(W_o[…] + b_o)
g_t = tanh(W_g[…] + b_g); c_t = f_t ⊙ c_{t−1} + i_t ⊙ g_t; h_t = o_t ⊙ tanh(c_t)
σ(z) = 1/(1+e^{−z}) ∈ (0,1); ⊙ = elementwise product
GRU: z_t = σ(W_z[h_{t−1}, x_t]); r_t = σ(W_r[h_{t−1}, x_t]);
h̃_t = tanh(W[r_t ⊙ h_{t−1}, x_t]); h_t = (1 − z_t) ⊙ h_{t−1} + z_t ⊙ h̃_t
Gradient path: ∂h_t/∂h_k = Π_{j=k+1}^{t} W_hhT · diag(tanh′(z_j)); LSTM: ∂c_t/∂c_k = Π_{j=k+1}^{t} f_j
Parameters — RNN: n(m + n + 1); LSTM: 4n(m + n + 1); GRU: 3n(m + n + 1); bidirectional: ×2
Gradient clipping: if ‖g‖₂ > τ then g ← g · τ/‖g‖₂ (τ = threshold, typically 1–5)
Language model: CE = −(1/N)Σ log p(y_i); Perplexity = e^{CE(nats)} = 2^{CE(bits)}

Example 1 — Parameter count (GATE style). Input m = 100, hidden n = 128, output classes 10.

Example 2 — Vanishing vs exploding, quantified. Suppose the per-step gradient factor ‖W_hh diag(tanh′)‖ is effectively a constant λ, over 30 steps.

Example 3 — One LSTM step by hand (scalar cell, x_t = 1.0, h_{t−1} = 0.5, c_{t−1} = 0.8).

Gatepre-activation zactivationvalue
Forget1.0(1.0) + 0.5(0.5) + 0 = 1.25σ0.7773
Input0.8(1.0) + (−0.4)(0.5) + 0.1 = 0.70σ0.6682
Candidate1.2(1.0) + 0.2(0.5) − 0.3 = 1.00tanh0.7616
Output0.5(1.0) + 0.5(0.5) + 0 = 0.75σ0.6792

Example 4 — Gradient clipping arithmetic. Global gradient norm ‖g‖₂ = 25, threshold τ = 5. Scale = 5/25 = 0.2, so every component is multiplied by 0.2 and the clipped norm is exactly 5. The *direction* is preserved; only the magnitude changes — which is why clipping does not bias the update.

Example 5 — Perplexity and memory. A Hindi–English code-mixed LSTM language model reaches validation cross-entropy 4.50 nats/token.

Simple RNNLSTMGRUTransformer
Params (m=100, n=128)29,312117,24887,936—
Long-range memorypoor (~10 steps)good (100s)goodexcellent
Gradient pathmultiplicativeadditive (cell)additive (interpolated)direct attention
Train-time parallelism over tnonenonenonefull
Inference memory per stepO(1)O(1)O(1)grows with context
Best fittoy/teachinglong streams, speechsmall data, fastlarge corpora, NLP
import torch, torch.nn as nn
class Tagger(nn.Module):
    def __init__(self, vocab, emb=128, hid=256, tags=12):
        super().__init__()
        self.emb  = nn.Embedding(vocab, emb, padding_idx=0)
        self.lstm = nn.LSTM(emb, hid, num_layers=2, batch_first=True,
                            bidirectional=True, dropout=0.3)
        self.out  = nn.Linear(2 * hid, tags)
    def forward(self, x, lengths):
        p = nn.utils.rnn.pack_padded_sequence(
                self.emb(x), lengths.cpu(), batch_first=True, enforce_sorted=False)
        o, _ = self.lstm(p)
        o, _ = nn.utils.rnn.pad_packed_sequence(o, batch_first=True)
        return self.out(o)                      # (B, T, tags)

# loss ignores padding; clip before every optimiser step
crit = nn.CrossEntropyLoss(ignore_index=0)
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=5.0)

Where it is used

Interview questions

Common mistakes

Related topics

Neural networks and backpropagation · Transformers and attention · Training deep networks: optimisers, normalisation and regularisation · Time-series forecasting and ARIMA · Natural language processing and word embeddings · Speech recognition and CTC

Open in the Knowledge reader →Find jobs →