Skip to main content
LearnMLAcademy
Advanced10 min read

RNNs, LSTMs and GRUs

Capture long-term temporal dependencies with LSTM and GRU gating mechanisms, with sequence diagrams, attention calculations, and model-code exercises.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

Deep Learning · Sequence Models

Some data has an order that changes its meaning: temperatures rise over time, words form a sentence, and machine vibrations develop before a fault. This lesson builds a sequence model from the first hidden-state update, shows why ordinary RNN memory can fail, calculates an LSTM memory update, and compares GRUs and bidirectional models.

A Sequence Is More Than a Bag of Values

Suppose a factory motor reports 20°C, 24°C, 31°C and 38°C. The final value matters, but the rising pattern also warns us that the motor is heating quickly. If we shuffle the same readings to 38°C, 20°C, 31°C and 24°C, their average is unchanged while the story is completely different.

A sequence model learns from both values and order. At time step t, it receives the current input xt and a compact summary of earlier inputs called the hidden state ht−1. It combines them to produce a new state ht. The state is learned—not a hand-written average—and its useful features emerge during training.

An RNN reads a sequence one step at a time

Each hidden state carries a learned summary of what has been read so far.

t = 1

x1 = 20°C

↓

h₁

first reading

memory moves forward

→

t = 2

x2 = 24°C

↓

h₂

uses h₁

memory moves forward

→

t = 3

x3 = 31°C

↓

h₃

uses h₂

memory moves forward

→

t = 4

x4 = 38°C

↓

h₄

alarm score

The same RNN cell and the same weights are reused at every time step. The four boxes are an unrolled view of one repeated computation—not four unrelated networks.

“Sequence model” describes several input–output shapes

Many → one

words → sentiment

I / loved / the / film→positive

Many → many (aligned)

readings → labels

normal / normal / spike→safe / safe / alert

One → many

image code → caption

photo representation→a / red / bus

Many → many (shifted)

past → future

sales days 1…30→forecast days 31…37
Choose the output shape from the task. Sentiment classification needs one prediction for the whole message; sequence labelling needs one prediction per meaningful step.

The Basic RNN Reuses One Update Rule

A recurrent cell uses the same parameters at every time step. Wxh controls how the current input affects memory; Whh controls how previous memory affects new memory; b is a bias. The tanh activation compresses each state component between −1 and 1.

Basic recurrent update

ht = tanh(Wxhxt + Whhht−1 + b)

ŷt = Whyht + by

xt is the current input, ht−1 is the previous hidden state, ht is the updated state, and ŷt is an optional prediction. In a real network these are usually vectors and the W terms are matrices. Multiplication lets each learned weight strengthen, weaken or reverse a feature; addition combines current and remembered evidence; tanh keeps the resulting state in a bounded range.

Two scalar updates, calculated by hand

Use Wxh=0.5, Whh=0.8, b=0 and initial state h₀=0. Let the normalized inputs be x₁=1 and x₂=0.5. These five values are deliberately chosen teaching numbers. In a real run, x comes from the data, the zero initial state is created by the framework unless you provide another state, and training learns W and b.

Time 1

h₁ = tanh(0.5×1 + 0.8×0)
= tanh(0.5)
≈ 0.462

No earlier reading exists, so h₀ contributes zero.

Time 2

h₂ = tanh(0.5×0.5 + 0.8×0.462)
= tanh(0.620)
≈ 0.551

The same two weights are reused; only the input and state changed.

Interpretation: h₂ depends on x₂ and on the summary created from x₁. Without the recurrent 0.8×h₁ term, the second state would ignore the first reading.

Training Unrolls the Network Backward Through Time

During the forward pass, states move from early to late time steps. After a loss is calculated, backpropagation through time (BPTT) treats the unrolled sequence like a deep network with shared weights and sends gradient information from later states toward earlier ones.

Each trip backward multiplies by another local derivative. Many factors below 1 can create a vanishing gradient, so early events receive almost no learning signal. Repeated large factors can create an exploding gradient, producing unstable updates or NaN values.

Repeated small derivatives can make an early learning signal disappear

Vanishing gradient across an unrolled recurrent networkA loss at time five sends a gradient backward. Multiplication by zero point five at each step reduces it from one to zero point zero six two five by time one.h1time 1h2time 2h3time 3h4time 4h5time 5gradient travelling backward through time10.50.250.1250.0625
This teaching example assumes a local derivative of 0.5 at each step: 1 × 0.5⁴ = 0.0625 by the earliest state. Values larger than 1 can instead make gradients grow rapidly. Real gradients are vectors and matrices, but repeated multiplication is the central difficulty.

What gradient clipping does

If the total gradient norm is too large, clipping scales it down before the optimizer step. This protects against explosions; it does not restore information already lost to vanishing gradients.

What truncated BPTT does

For very long streams, detach the hidden state after a chosen window. This limits memory and compute, but prevents gradients from directly crossing the truncation boundary.

An LSTM Adds a Controlled Memory Path

A Long Short-Term Memory network is still recurrent, but its cell keeps two states. The cell state c carries controlled long-term memory. The hidden state h is the visible working representation passed to prediction layers and the next cell. Learned gates use sigmoid values between 0 and 1 to regulate information—not probabilities of an event, but soft control values.

Inside one LSTM step: erase, write, then reveal

The gates are learned numbers between 0 and 1 for every memory feature.

LSTM cell state and three gatesPrevious hidden state and current input feed forget, input, candidate and output calculations. Old cell memory is filtered, new candidate memory is added, and the output gate reveals the new hidden state.previous cell memory cₜ₋₁×+new cell memory cₜforget gate fₜhow much old memory staysinput gate iₜhow much new memory enterscandidate gₜproposed new contentoutput gate oₜwhat becomes visible[hₜ₋₁, xₜ]past summary + inputhₜvisible state
The upper green path is the cell state—a controlled memory route. Multiplication by fₜ filters old memory; adding iₜ × gₜ writes selected new content. The output gate controls the hidden state exposed to the next step and prediction layers.

One standard LSTM formulation

ft = σ(Wf[ht−1, xt] + bf)   forget control

it = σ(Wi[ht−1, xt] + bi)   input control

gt = tanh(Wg[ht−1, xt] + bg)   candidate

ct = ft ⊙ ct−1 + it ⊙ gt   updated memory

ot = σ(Wo[ht−1, xt] + bo)   output control

ht = ot ⊙ tanh(ct)   visible state

[ht−1,xt] means concatenate the two vectors so every gate can inspect past and present together. Matrix multiplication forms learned mixtures, σ turns each mixture into a 0–1 control, ⊙ applies that control feature by feature, and addition combines retained old memory with accepted new memory.

One memory component, updated numerically

Suppose old memory ct−1=0.40. For this step the learned gates produce ft=0.80, it=0.30, candidate gt=0.50 and output gate ot=0.90. These are manually selected teaching outputs, not recommended settings. In a trained LSTM, the current input and previous hidden state pass through learned W and b values to calculate a different gate vector at every step.

Retained old memory
0.80 × 0.40
= 0.32

Accepted new memory
0.30 × 0.50
= 0.15

New cell state
ct = 0.32 + 0.15
= 0.47

ht = 0.90 × tanh(0.47) ≈ 0.90 × 0.438 = 0.394

Interpretation: most of the old feature was preserved, some candidate information was written, and 90% of the squashed memory became visible. During training the network learns the weights that produce these gate values.

A GRU Combines the Memory Controls

A Gated Recurrent Unit has a hidden state but no separate cell state. Its reset gate controls how much previous state influences the candidate. Its update gate blends old state with the new candidate. Fewer gate projections usually mean fewer parameters than a comparable LSTM.

The update gate performs a learned blend

ht = (1 − zt) ⊙ nt + zt ⊙ ht−1

In this convention, z near 1 preserves more old state and z near 0 selects more candidate state n. Some texts swap the two coefficients, so always read the implementation's equations.

z=0.75, old h=0.60, candidate n=0.20
ht=(0.25×0.20)+(0.75×0.60)=0.05+0.45=0.50

Do not choose LSTM because it is “always more powerful,” or GRU because it is “always faster.” Hidden size, implementation, hardware and task matter. Treat both as baselines and validate them on the same split and budget.

Bidirectional Models Use Past and Future Context

A bidirectional RNN runs one recurrent layer from left to right and another from right to left, then combines their representations. This is useful when the entire sequence is already available—for example, labelling every word in a stored document. The word “bank” can then use words on both sides.

Do not use future information when it would be unavailable

A live forecasting system at 10:00 cannot use readings from 10:05. A bidirectional encoder on such training windows leaks the future and creates unrealistic evaluation. Use a causal, forward-only model for real-time prediction.

Which Sequence Model Should You Try?

ModelHow it carries contextReasonable starting situationImportant limitation
Simple RNNOne hidden state; fewest gates/parametersShort dependencies, small teaching baselinesLong-memory training can be difficult
GRUReset and update gates; no separate cell stateA strong recurrent baseline when compute/data are limitedLess explicit memory control than LSTM
LSTMForget, input and output gates plus cell stateForecasting, speech or text when gated recurrence is appropriateMore parameters and sequential computation
TransformerAttention connects token pairs directlyParallel training and rich global contextStandard attention cost grows quadratically with length

For a small time-series or sequence-classification project, a one-layer GRU or LSTM is still an understandable, useful baseline. For large language modelling or parallel training, compare Transformer approaches. For extremely long streams, evaluate efficient attention or a supported SSM implementation—but measure quality, latency, memory and ecosystem maturity on your actual task.

A Small GRU Classifier in PyTorch

The model below receives a batch shaped [batch, time, features]. The GRU returns an output for every padded time position and a final hidden state. Packing tells the GRU which positions are real, so a short sequence does not treat padding as data.

gru_sequence_classifier.py
import torch
from torch import nn
from torch.nn.utils.rnn import pack_padded_sequence

class SequenceClassifier(nn.Module):
    def __init__(self, input_features, hidden_size, classes):
        super().__init__()
        self.gru = nn.GRU(
            input_size=input_features,
            hidden_size=hidden_size,
            batch_first=True,
        )
        self.classifier = nn.Linear(hidden_size, classes)

    def forward(self, padded_sequences, lengths):
        packed = pack_padded_sequence(
            padded_sequences,
            lengths.cpu(),
            batch_first=True,
            enforce_sorted=False,
        )
        _, final_hidden = self.gru(packed)
        last_layer_state = final_hidden[-1]   # [batch, hidden]
        return self.classifier(last_layer_state)

model = SequenceClassifier(input_features=6, hidden_size=32, classes=3)
logits = model(batch, lengths)  # raw class scores [batch, 3]
loss = nn.CrossEntropyLoss()(logits, labels)

Where the dimensions come from

input_features=6 must match the six measured or embedded features at each time step. hidden_size=32 is a developer-chosen capacity. classes=3 comes from the three target labels. With 10 examples and 20 time steps, the input shape is [10,20,6] and the logits shape is [10,3].

What the framework does

PyTorch initializes the GRU and linear weights, creates an all-zero initial hidden state when none is supplied, skips packed padding positions, and returns final states. CrossEntropyLoss internally applies log-softmax and selects the loss for each integer class label; pass raw logits, not pre-softmax probabilities.

For a bidirectional GRU, final_hidden contains a separate state for each direction; do not blindly take only [-1]. Reshape by layers and directions, then concatenate the last forward and backward states.

Diagnosing Recurrent Models

What you observeLikely problemCheck or correction
Model reacts to padding lengthPadding is entering pooling or final-state logicPack sequences or mask padded positions; test the same sample with extra padding
Loss becomes NaN; gradient norm jumpsExploding gradients or unstable inputs/rateInspect inputs, lower the rate and clip gradient norm before optimizer.step()
Long-range clue has no effectVanishing gradients, short training window or inadequate stateCompare LSTM/GRU, longer context and a Transformer/SSM baseline
Validation is suspiciously excellentFuture leakage from bidirectionality or random temporal splitUse causal features and a chronological split for forecasting
Only one batch size worksHidden state was created with a fixed batch dimensionInitialize from the current batch or let the framework create zero state
GPU memory grows every stream stepState retains the entire autograd graphDetach state at intentional truncated-BPTT boundaries
Shapes look transposedbatch_first setting disagrees with dataLog [batch,time,features] or [time,batch,features] before the recurrent layer

What to Remember

  • An RNN reuses one cell and carries a learned hidden state through ordered inputs.
  • BPTT sends gradients through the unrolled time steps; repeated derivatives can vanish or explode.
  • An LSTM regulates a separate cell memory with forget, input and output gates.
  • A GRU uses a simpler gated update with one hidden state; neither GRU nor LSTM wins every task.
  • Bidirectional context is useful only when future positions are available at prediction time.
  • Correct masking, causal evaluation, tensor shapes and gradient monitoring matter as much as the cell choice.

Continue Learning

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "RNNs, LSTMs and GRUs"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5conceptual
What does an RNN hidden state represent?
Question 2 of 5numerical/formula
With h_t=tanh(0.5x_t+0.8h_{t-1}), x=1, and h_0=0, which expression gives h_1?
Question 3 of 5interpretation
Why can a basic RNN forget distant evidence?
Question 4 of 5conceptual
What is the purpose of an LSTM forget gate?
Question 5 of 5practical selection
When is a bidirectional sequence model inappropriate?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1What does an RNN hidden state represent?▼

Correct Answer: A learned running summary of earlier sequence positions

The recurrent update combines the current input with the previous hidden state.

2With h_t=tanh(0.5x_t+0.8h_{t-1}), x=1, and h_0=0, which expression gives h_1?▼

Correct Answer: tanh(0.5)

Substitution gives tanh(0.5×1+0.8×0)=tanh(0.5).

3Why can a basic RNN forget distant evidence?▼

Correct Answer: Repeated derivatives can shrink through many time steps

Backpropagation through time multiplies many local derivatives, producing vanishing gradients.

4What is the purpose of an LSTM forget gate?▼

Correct Answer: Control how much old cell memory is retained

A sigmoid gate scales the previous cell state before new memory is added.

5When is a bidirectional sequence model inappropriate?▼

Correct Answer: When prediction must be causal and future inputs are unavailable

A bidirectional model depends on later positions, which cannot be used in real-time causal prediction.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Optional Learning Resources

These resources may complement the lesson. They are optional and are not required to use ML Academy.

As an Amazon Associate I earn from qualifying purchases. Other links are identified separately when they are not affiliate links.

Next