Interview's MateData Science
Interview's Mate

Data Science

Python → ML → MLOps

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
Data Science topics
Lesson 132/ 160
07. Deep Learning & NLP

Sequence Models (RNNs, LSTMs, GRUs)

Model sequences with recurrent nets and gated memory for longer dependencies.

IntermediateRNN · LSTM3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

An RNN reads one item at a time and keeps a short memory of what it has seen. LSTMs and GRUs add little gates that decide what to remember and what to forget, so they can hold on to important things for longer.

Think of it like…

Reading a book with a notepad of limited size. A plain RNN rewrites the whole notepad every page, so early details fade quickly; an LSTM has a separate margin note it can leave untouched for many pages, with gates deciding what to erase, what to add and what to read out.

Where you’ve seen it

A utility predicts next-hour electricity demand from the last 48 hours of readings. In a scalar toy RNN with w_x = 1, w_h = 0.5 and an input spike (1, 0, 0), the hidden state is tanh(1) = 0.762, then tanh(0.5 × 0.762) = 0.363, then tanh(0.5 × 0.363) = 0.180: the memory of the spike roughly halves each step. Backward through time the gradient is multiplied by about w_h × tanh′ at every step, so across 20 steps it shrinks like 0.5²⁰ ≈ 9.5×10⁻⁷ (and would grow like 1.5²⁰ ≈ 3,325 with a factor of 1.5, hence gradient clipping). In an LSTM the cell state is c_t = f_t ⊙ c_{t−1} + i_t ⊙ g_t, so with a forget gate near 0.9 a stored value retains 0.9²⁰ ≈ 0.12 of its size after 20 steps, an additive path that decays slowly. For input size 128 and hidden size 256, a plain RNN layer has 256 × (128 + 256) + 256 = 98,560 parameters, a GRU 3 × that = 295,680 and an LSTM 4 × that = 394,240 (PyTorch keeps two bias vectors per gate, so it reports 395,264 for the LSTM). The team compares the LSTM with a gradient-boosted model on lag features (demand 1, 24 and 168 hours ago, hour of day, temperature) using a rolling-origin split; the boosted model is within 1% of the LSTM and 20 times faster to train, so the LSTM is kept as an ensemble member and for multi-step probabilistic forecasts. Sequences are padded to equal length, packed so the padding doesn't affect the state, and validated only on later periods than the training data.

Words you’ll hear

Hidden state
The vector summarising what the network has seen so far in the sequence.
Gate
A learned 0–1 multiplier that controls how much information passes.
Cell state
The LSTM's additive memory line, updated by forget and input gates.
BPTT
Backpropagation through time: unrolling the recurrence and applying backprop across steps.

Visual diagram

Loading interactive diagram

Theory & deep dive

RNN recurrence and the vanishing gradient

At each step the hidden state mixes the new input with the previous state. With scalar weights w_x = 1, w_h = 0.5 and input (1, 0, 0), h₁ = tanh(1) = 0.762, h₂ = tanh(0.5 × 0.762) = tanh(0.381) = 0.363 and h₃ = tanh(0.181) = 0.180. The influence of the first input decays geometrically. Training by backpropagation through time multiplies the gradient by w_h × tanh′(·) at every step; if that factor averages 0.5 the gradient over 20 steps is 0.5²⁰ ≈ 9.5×10⁻⁷, so early inputs get almost no learning signal, and a factor of 1.5 gives 1.5²⁰ ≈ 3,325 (exploding). Clipping the gradient norm handles explosions; vanishing needs architectural change.

Practical consequences: plain RNNs rarely learn dependencies beyond 10 to 20 steps, they are sequential (each step needs the previous one, so they parallelise poorly across time) and they are sensitive to initialisation and learning rate. Truncated BPTT limits how many steps gradients flow through (commonly 50 to 200) to save memory; bidirectional RNNs read the sequence both ways when the whole sequence is available (not for forecasting).

Memory decay

Plain RNN with factor 0.5: after 20 steps 0.5²⁰ ≈ 9.5×10⁻⁷ of the signal remains. LSTM cell with forget gate 0.9: 0.9²⁰ = 0.1216 remains. With forget gate 0.99 it is 0.99²⁰ = 0.818, so the model can learn to keep information almost indefinitely.

Key takeaway: Repeated multiplication shrinks or inflates gradients; gated, additive memory paths keep them usable.

LSTM, GRU and when to use them

An LSTM keeps a cell state c_t and computes forget f_t, input i_t and output o_t gates (each a sigmoid of the input and previous hidden state) plus a candidate g_t = tanh(·). The update c_t = f_t ⊙ c_{t−1} + i_t ⊙ g_t is additive, so gradients can flow along the cell state without being squashed each step, and h_t = o_t ⊙ tanh(c_t). A GRU merges the cell and hidden state and uses update and reset gates, with three weight blocks rather than four, which makes it about 25% smaller and often as accurate. For d = 128 inputs and h = 256 hidden units, the weight blocks have 256 × (128 + 256) + 256 = 98,560 parameters each: 98,560 for a plain RNN, 3 × 98,560 = 295,680 for a GRU and 4 × 98,560 = 394,240 for an LSTM.

Use recurrent models for streaming or online prediction with small state, moderate-length time series and small text datasets, especially on constrained hardware. Prefer transformers for long-range text, large datasets and pretrained language models; try 1D CNNs or gradient boosting on lag and calendar features first for forecasting, since they are fast and often competitive. Engineering details: pad and pack variable-length sequences, split by time (never shuffle across the time boundary), scale inputs using training statistics, clip gradients, add dropout between layers and evaluate multi-step forecasts honestly, since errors compound when predictions feed back as inputs.

Parameter counts

d = 128, h = 256: per gate block 256 × (128 + 256) + 256 = 98,560. RNN 98,560 · GRU 295,680 · LSTM 394,240. PyTorch stores two bias vectors per gate, so it counts 4 × 256 × 384 + 8 × 256 = 395,264 for the LSTM.

Key takeaway: LSTMs and GRUs fix gradient decay with gating; benchmark them against simple lag-feature models and transformers before committing.

How it works, step by step

Step 1 of 4
Data scientist

1. Frame and split by time

Create input windows and targets, then split chronologically with a rolling origin to avoid leakage.

48 hours in → next hour out
Key numbers at this step
Split
by time, not random

When to use it & trade-offs

What it is

A recurrent neural network (RNN) processes a sequence one step at a time while carrying a hidden state: h_t = tanh(W_x x_t + W_h h_{t−1} + b). The same weights are reused at every step, so the model handles variable-length inputs and shares what it learns across positions. Plain RNNs struggle with long dependencies because gradients are multiplied by the same factor at every step and vanish (or explode). LSTMs add a cell state with additive updates controlled by forget, input and output gates, and GRUs simplify this to two gates (update and reset). They are trained with backpropagation through time and are still used for time series, sensor streams and small-data text problems, although transformers dominate large-scale language tasks.

Why it matters: Many data-science problems are sequences: sessions of clicks, sensor readings, transaction histories, text and demand series. Knowing how recurrent models carry memory, why they forget and what they cost lets you choose between them, convolutional models, gradient boosting on lag features and transformers. The vanishing-gradient arithmetic behind LSTMs is also a favourite interview topic, and understanding it clarifies why gating and residual paths appear throughout deep learning.

When to reach for it

  • Short-horizon forecasting with learned temporal patterns
  • Sensor and event streams with small per-step state
  • Small-data text classification where pretrained models are unavailable

When to avoid or be careful

  • Random shuffling across the time axis when validating
  • Plain RNNs for dependencies beyond a few dozen steps
  • Reporting one-step accuracy for a multi-step forecasting task

Sequence model choices

LSTM / GRU
Best for: Streaming data, moderate sequences, small datasets

Strengths: Compact state; handles variable length.

Watch out: Sequential training; limited long-range memory.

Transformer
Best for: Large text corpora and long-range dependencies

Strengths: Parallel training; pretrained models.

Watch out: Quadratic attention cost; data hungry.

Gradient boosting on lag features
Best for: Tabular-style time series with calendar effects

Strengths: Fast, strong baseline, interpretable.

Watch out: Manual feature engineering; no learned long memory.

1D CNN
Best for: Local patterns in signals

Strengths: Parallel and fast.

Watch out: Fixed receptive field.

Interview signals & numbers to know

When this topic comes up

  • “Why do RNNs have vanishing gradients?”
  • What an LSTM's cell state does
  • LSTM versus GRU parameter counts
  • Why transformers replaced RNNs for text
  • Time-series validation without leakage

Benchmarks & rules of thumb

0.5²⁰ ≈ 9.5e-7 -
gradient factor over 20 steps at 0.5 per step
3× and 4× -
GRU and LSTM parameters relative to a plain RNN layer
394,240 -
LSTM parameters for d = 128, h = 256 (one bias per gate)

Common mistakes & follow-ups

Common interview mistakes

  • Validating on randomly shuffled windows that leak the future.
  • Skipping gradient clipping and getting NaN losses.
  • Not trying a gradient-boosted baseline first.

Likely interviewer follow-ups

  • Why does an LSTM avoid vanishing gradients?
  • How would you handle sequences of different lengths?
  • When would you choose a GRU over an LSTM?
Interview tip: Count LSTM parameters and quote 0.5²⁰; the arithmetic shows you understand both the cost and the failure mode.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Sequence Models (RNNs, LSTMs, GRUs) with data science interview Q&A and hands-on practice.

Open Data Science Q&A →Machine Learning Q&A
Previous topic
Object Detection & Image Segmentation Basics
Next topic
Text Preprocessing (Tokenization, Lemmatization)