Part VIII — Deep Learning

Chapter 28 · Recurrent Neural Networks

Chapter 26's network reads a row of features. Chapter 27's reads a picture. Neither can read a sequence — text that only means something in order, a price that only means something in context, a sound that only means something as it unfolds. This chapter builds the network that reads step by step and carries a memory: the recurrent neural network. The hidden state is computed by hand, the training is backpropagation run along the unrolled timeline, and the famous disease — the vanishing gradient — is not asserted but measured, with exact numbers: how much influence does the first state still hold at step 40? The honest surprise: toy tasks survive the disease. The honest conclusion: the disease is real anyway, and the next chapter's gates are the cure. Every section opens with a plain-words box that follows Priya, a junior equity analyst, so the idea lands before the mathematics does.

📖 Chapter 28 of 35 ⏱ ~95 min read Mostly Core Stable Volatile 📝 Quiz · 30 MCQs

🎯 Learning Objectives

1. Why Order Matters

📝
How to read this chapter: every section starts with an In plain words box that tells the idea as a story, with no mathematics. The technical explanation follows it. If you are new to the subject, read the boxes first; if you are technical, the boxes are a quick check that the idea is clear before the formulas.
📖
In plain words · Priya’s notebook

Meet Priya, a junior equity analyst in Mumbai. She follows one company, Sunrise Foods (a made-up name), and every morning she reads one headline about it.

One day her manager hands her two news summaries built from the same two sentences. The first says: “Profits fell. Then the company won a large contract.” The second says: “The company won a large contract. Then profits fell.” Same sentences, opposite stories: the first company is recovering, the second is getting worse. The difference is only the order.

Prices work the same way. A share at ₹500 after climbing from ₹450 means something different from a share at ₹500 after falling from ₹550. Same number, different story.

A spreadsheet that only counts words, or only looks at today’s price, cannot tell these apart. To understand them you have to read in order and remember what came before. That is what this chapter builds.

Take the sentence "the food was not good". Now shuffle the words: "good was food the not". Same words. Same counts. To Chapter 25's bag of words, the two sentences are identical. To a reader, one is a mild complaint and the other is nonsense. Meaning lives in order.

Prices are the same. Today's close means one thing after a ten-day slide and another after a ten-day rally. The value is the same number; the sequence around it is the meaning. Sound, video, sensor logs, clicks, heartbeats — a large part of the world arrives as a sequence: items whose meaning depends on the items before them.

Now check what we have built so far. Chapter 26's Dense network reads one fixed-length vector. Order of features is not something it understands: each position has its own weights, so position 7 and position 8 are unrelated slots to it. It has no way to share what it learns about "not" at position 3 with "not" at position 30, and it demands a fixed input length. Chapter 27's convolution sees local order, but only within one small window; stacking grows its reach, yet slowly — it has no efficient way to connect a word at the start of a paragraph to one at the end. Neither machine has a memory that persists across the input.

📝
Note: Chapter 25 got far with order-blind bags — 78% on restaurant reviews. That is the honest baseline this chapter must beat or explain: for many tasks a bag is enough. Recurrence earns its keep when order carries the payload: "not good" vs "good", "debt rose then fell" vs "fell then rose".

2. The Recurrent Idea

📖
In plain words · Priya’s notebook

Priya cannot remember every headline from the last six months. So she keeps one number on a sticky note: her current view of the stock, from −1 (very negative) to +1 (very positive).

Every morning she does the same three things: she reads today’s headline, she looks at yesterday’s number, and she writes a new number that takes both into account. Then she throws the old note away.

How she does this depends on three personal habits: how strongly today’s news moves her, how firmly she holds on to yesterday’s view, and her natural lean (some analysts are a little optimistic every day, some a little cautious). She uses the same habits every day.

A recurrent network works exactly like Priya. The sticky note is called the state; her morning routine is the cell; her three habits are the weights W (how strongly new input moves her), U (how firmly she holds the old view) and b (her lean). A real network keeps a small card of numbers instead of one, for example 16 (one for sales, one for debt worries, one for the sector mood, and so on), but the card never gets bigger, however many days she reads.

2.1 Reading one word at a time

A Dense network takes all its inputs at once, as one fixed row of numbers. That works for a table. A sentence is different: the words arrive one after another, and the meaning of a word depends on the words before it. “Good” means one thing on its own and the opposite after “not”.

So we need a network that can read one word at a time and remember what it has already read.

A recurrent network does this by giving the network one extra input. At every step it receives two things:

  1. the current word, and
  2. its own result from the previous step.

That second input is the network’s memory. It is called the state, written h. Each step takes the current word and the previous state and produces a new state, which is passed on to the next step. The small piece of network that does this one step is called the cell.

Here is the cell reading “the food was not good”:

StepThe cell receivesIt produces
1“the” + empty memory (h0 = 0)h1
2“food” + h1h2
3“was” + h2h3
4“not” + h3h4
5“good” + h4h5 → prediction

At step 5 the cell sees “good”, but it also receives h4, which was built from “the food was not”. That is how it can tell “not good” from “good”.

One important detail: the state has a fixed size. It is always the same short list of numbers (for example 16), however long the sentence is. It cannot store every word separately, so it has to keep only what is useful. That is why the state is often called a summary of what has been read so far.

2.2 One step, as a formula

Each step is one formula. Read it in words first:

new state = tanh( U · previous state + W · current input + b )
In symbols: ht = tanh( U · ht−1 + W · xt + b ). t is the step number: xt is the input at step t, ht−1 is the state from the previous step, and ht is the new state. At step 1 there is no previous state, so h0 starts as all zeros. (A network cannot read letters, so each word is first turned into a list of numbers; Chapter 29 shows how.)

The three letters W, U and b are the cell’s weights. They are what training learns, and each has one job:

SymbolWhat it isIts job
x the input at this step (a word turned into numbers, or one day’s return) what the network reads now
h (state) a fixed-size list of numbers carrying what has been read so far the memory
W (input weights) multiply the current input decide how the current input changes the state
U (recurrent weights) multiply the previous state decide how much of the previous state is carried into the new one
b (bias) a fixed number added at every step a constant shift, like the intercept in a regression
tanh squashes the result into (−1, 1) keeps the state from growing without limit

W decides what the network notices; U decides what it remembers. If U were zero, the old state would be ignored and the cell would be an ordinary Dense layer with no memory. U is the whole difference. Section 3 works one step by hand with real numbers.

2.3 The same cell, drawn two ways

A · The idea: one cell that feeds its own state back the cell W, U, b new state h (the memory) W new input x (one word) U its ownprevious state,fed back in At every step the cell gets two things: ① the new input (read with W) ② its own previous state (carried with U) and produces one new state. b is a constant shift. B · The same cell, unrolled: one copy per word of “the food was not good” memory after each word: the same cell W, U, b W “the” step 1 the food same cell W, U, b W “food” step 2 the food was same cell W, U, b W “was” step 3 … was not same cell W, U, b W “not” step 4 the whole sentence same cell W, U, b W “good” step 5 h₀ = 0no memory U h₁ U h₂ U h₃ U h₄ U h₅ prediction Five boxes, but only ONE cell: the same W, U and b are reused at every step. new input, read with W memory (state), carried with U b = constant shift inside each cell
Figure 28.1 — The recurrence. A: one cell takes two things at every step: the new input (blue, read with W) and its own previous state (green, carried with U), and produces a new state. B: the same loop unrolled over “the food was not good”: one copy per word, all five with the same W, U and b. The italic words above the boxes show, loosely, what the memory holds after each step; the real state is a vector of numbers. h5 summarises the whole sentence and feeds the prediction.

How to read Figure 28.1, panel B, from left to right:

  1. Start. The memory starts empty: h0 = 0.
  2. Blue arrows go up into each box. That is the new word, read with W.
  3. Green arrows go sideways. That is the state from the previous step, carried with U, passing from each box to the next. By the time “good” arrives, h4 already carries “the food was not”. That is how the network can tell “not good” from “good”.
  4. End. The last state, h5, carries the whole sentence. A small output layer turns it into the prediction.
❓
Common question — does the cell keep only the last few words? No. Keeping the last few words (“was not”, then “not good”) would be a sliding window, and once a word slid out it would leave no trace. The state is not a list of words at all: it is a fixed set of numbers, and every new word changes those numbers rather than taking a slot. After “the food was not” the numbers have been nudged by all four words. The italic labels in panel B mean “influenced by these words”, not “these words are stored”. The catch, measured in Section 5: the influence of older words fades with every step.
💡
Pro Tip — you already know a one-unit RNN: the exponential moving average of a price, EMAt = 0.3 · pricet + 0.7 · EMAt−1, is a recurrent cell with W = 0.3, U = 0.7, b = 0 and no tanh. It is one number, yet every past price has influenced it. A price 10 days back counts about 3% as much as today’s (0.710 ≈ 0.028), and one 20 days back less than 0.1% (0.720 ≈ 0.0008). Fixed-size memory, long reach, fading weight: the RNN in miniature.

2.4 Why the same W, U and b at every step

Panel B shows five boxes, but they are one cell used five times, like applying the same stamp to five pages. This is the “recurrent” in the name, and it has three consequences:

You have met this trick before. A convolution (Chapter 27) shares one kernel across space; a recurrent cell shares one set of weights across time.

⚠
Common confusion: the five boxes in panel B are not five different networks. Nothing is copied or trained five times. There is one W, one U and one b; training changes those three and every box changes with them.

3. The RNN Cell, by Hand

📖
In plain words · Priya’s notebook

Give Priya simple habits: today’s news counts fully (W = 1), she keeps half of yesterday’s view (U = 0.5), and she has no lean (b = 0). Her note starts blank, at 0.

Day 1, strong good news (+1). Her raw total is 1. But her scale only runs from −1 to +1, and the closer she gets to an end the harder it is to move further, so she writes 0.76, not 1. (That “harder near the ends” rule is what tanh does.)

Day 2, bad news (−1). Her raw total is the bad news plus half of yesterday’s view: −1 + 0.38 = −0.62, and she writes −0.55.

Without a memory she would have written −0.76 on day 2, exactly the reverse of day 1. Yesterday’s good news softened today’s reaction. That softening is memory at work, and the table below shows the same two days with every decimal.

The cell is Chapter 26's neuron with one extra input — its own past. In math:

ht = tanh( U · ht−1 + W · xt + b )
xt = the input at step t (a word turned into numbers, or one day's scaled return); ht−1 = the state from the previous step; W = input weights; U = recurrent weights (the memory path); b = bias; tanh keeps the state bounded in (−1, 1). At t = 1 there is no past: h0 starts as all zeros.

Now compute it, by hand, with the smallest possible network: one input, one hidden unit. Weights: W = 1, U = 0.5, b = 0. Inputs: x1 = 1 (a strong up-day: a return scaled so that 1 means one standard deviation), then x2 = −1 (an equally strong down-day). Watch the memory work:

StepRaw sum (inside tanh)State h = tanh(raw sum)Reading
t = 1 0.5·(0) + 1·(1) + 0 = 1.000 0.7616 the up-day registered — tanh squashes the raw sum 1 into 0.7616
t = 2 0.5·(0.7616) + 1·(−1) + 0 = −0.6192 −0.5506 the down-day dominates — but the memory of yesterday’s up-day pulls the state up: −1 alone would give −0.7616

That pull is the memory doing its job. The state at t = 2 is a blend of the new input and the old state. Notice which number travels on: only the state h is passed to the next step; the raw sum is a working value, thrown away once tanh has been applied. Chapter 26 gave us every tool here: tanh (the activation menu), the weighted sum, the bias. The only new term is U · ht−1 — the loop back.

One more count before we scale up. With n hidden units and m input features, W is an n×m matrix, U is n×n (every state number can influence every other), and b has n entries. A layer of 16 units reading 5 features owns 16·5 + 16² + 16 = 352 parameters — and they are the same 352 at every time step.

💡
Pro Tip — verify one value: tanh(1) = 0.7616 and tanh(−0.6192) = −0.5506. Two calculator presses. Every number in this table is exactly reproducible to four decimals — the house rule for hand examples.

4. Backpropagation Through Time

📖
In plain words · Priya’s notebook

At the end of the month, Priya’s manager compares her final view with what the stock actually did. Suppose she was too optimistic. To improve, she must find out which mornings led her astray.

So she walks backwards through her notes. Today’s number came from yesterday’s number and today’s headline; yesterday’s came from the day before, and so on. At each step back she asks: “how much did that day shape the next one?” Only by walking the whole chain can she see how much a headline from day 1 affected her final call.

Then she adjusts her habits, not one particular day: perhaps she should react less strongly to good news, or hold on to old views less firmly. The lessons from every day are added together into one change of habits, because she has only one set of habits. The network learns in exactly this way, and the name for it is backpropagation through time.

How does this thing learn? Look back at panel B of Figure 28.1: that picture is already unrolled — it is a deep feedforward network, one layer per time step. So training is exactly Chapter 26's algorithm, applied along the timeline. The name is the only new part: backpropagation through time (BPTT).

Suppose the sentence ends and the output layer is wrong — it said "positive" for "the food was not good". The error travels backwards: into h₅, then h₄, h₃, h₂, h₁. To learn how the first word influenced the final answer, the gradient must cross every intermediate step — and each crossing multiplies by the recurrence's Jacobian, the derivative of ht with respect to ht−1. We can write that factor exactly:

∂ht / ∂ht−1 = diag(1 − ht²) · U
The same U appears at every step; only the diagonal changes, because it depends on the current state. This one formula is exactly the code line in Section 5.

And there, in one sentence, is the whole chapter's tension: to assign credit to the distant past, gradients must survive a long chain of multiplications. Chapter 26 already met chains — that was the chain rule. The recurrent twist is that the chain grows with the sequence, and a factor built from the same U is multiplied over and over.

Sharing has one more consequence. Because W, U, b are the same objects at every step, each of their gradients is the sum of the contributions from every time step — credit from the whole sequence lands on one set of weights. And for very long sequences the backward pass is often cut short: backpropagate only through the last k steps. That habit is called truncated BPTT.

5. The Vanishing Gradient, Measured

📖
In plain words · Priya’s notebook

Priya never keeps all of yesterday’s view, so old news fades. If each day only 81% of the old influence survives, then after 40 days the day-1 headline counts for about 0.02% of what it once did. It is like losing 19% of your money every day for 40 days: almost nothing is left.

Worse, the same fading hits the manager’s feedback when Priya walks backwards through her notes. By the time the lesson reaches day 1, it is too faint to change anything, so she can never learn that an early headline mattered. That is the vanishing gradient.

The opposite analyst overreacts: each day he blows up yesterday’s view by a third (1.33 times). After 40 days a small early worry has grown about 90,000-fold into panic, and his feedback explodes the same way. That is the exploding gradient.

Think of the children’s game of whispers passed along 40 children: either the message fades to silence or it grows into a roar. A plain RNN struggles to sit exactly in between. The code below measures both failures.

Textbooks assert the vanishing gradient. We will measure it — no training, no accuracy scores, just the exact question: how much influence does the first state (h₀) still carry at step T? The answer is the Frobenius norm of the product of the recurrence Jacobians, and we can multiply them out precisely, cell by cell, with numpy. Here is the entire script:

# the memory carry: || dh_T / dh_0 ||, exact, no training
import numpy as np

def memory_carry(u_std, n=16, T=40, seed=0):
    rng = np.random.default_rng(seed)
    U = rng.normal(0, u_std, (n, n))       # recurrent weights
    W = rng.normal(0, 1.0, n)              # input weights (1 input feature)
    b = np.zeros(n)
    h = np.zeros(n); P = np.eye(n)         # P = running Jacobian product
    for t in range(T):
        x = rng.uniform(-1, 1)
        h = np.tanh(U @ h + W * x + b)
        P = (np.diag(1 - h**2) @ U) @ P    # one more step of the chain rule
    return np.linalg.norm(P)               # Frobenius norm of dh_T/dh_0

for std in (0.25, 1.0):
    c = np.array([memory_carry(std, seed=s) for s in range(10)])
    print(std, f"geometric mean {np.exp(np.log(c).mean()):.1e}",
              f"range {c.min():.0e} ... {c.max():.0e}")

The script, line by line

Not a programmer? Read only the right-hand column: it tells the story of the listing in order, one line (or a few closely linked lines) at a time.

CodeWhat it does, in plain English
import numpy as npLoad numpy, the toolbox for working with lists and tables of numbers.
def memory_carry(u_std, n=16, T=40, seed=0):Define one experiment. u_std is how big the memory weights U are (the one thing we compare); the network has 16 units (n) and runs for 40 steps (T); seed fixes the random numbers so the run can be repeated.
rng = np.random.default_rng(seed)Create a random-number generator with that fixed seed.
U = rng.normal(0, u_std, (n, n)) # recurrent weightsMake a random 16×16 table of memory weights U. Their typical size is u_std: 0.25 (small) or 1.0 (large).
W = rng.normal(0, 1.0, n) # input weights (1 input feature)Make random input weights W: how each of the 16 units reacts to the day’s single input number.
b = np.zeros(n)Set every bias b to zero, to keep the experiment simple.
h = np.zeros(n); P = np.eye(n) # P = running Jacobian productStart with an empty memory (h = 0). P will record “how much does the memory today depend on the starting memory”; it starts as “fully, unchanged” (the identity table).
for t in range(T):Repeat the following for each of the 40 steps:
x = rng.uniform(-1, 1)… draw a random input between −1 and +1, like a day’s scaled return;
h = np.tanh(U @ h + W * x + b)… run one ordinary RNN step: the formula of Section 2, h = tanh(U·h + W·x + b), for all 16 units at once (@ means matrix multiplication);
P = (np.diag(1 - h**2) @ U) @ P # one more step of the chain rule… multiply in this step’s sensitivity, (1 − h²) × U: the slope of tanh times the memory weights. Chaining it onto P gives “how much a nudge to the starting memory still moves today’s memory”.
return np.linalg.norm(P) # Frobenius norm of dh_T/dh_0Shrink the final 16×16 table to one number (the square root of the sum of its squares). This is the memory carry: big means the start still matters a lot, tiny means it has faded.
for std in (0.25, 1.0):Run the comparison for the two sizes of memory weights.
c = np.array([memory_carry(std, seed=s) for s in range(10)])Repeat the experiment ten times with different random starts (seeds 0–9), because one run can be unusually high or low.
print(std, f"geometric mean {np.exp(np.log(c).mean()):.1e}", f"range {c.min():.0e} ... {c.max():.0e}")Print the typical result and the range. The geometric mean (the average of the logarithms, turned back) is used because the ten results differ by thousands of times; an ordinary average would just follow the biggest one. Expected: about 0.00024 for 0.25 (fading) and about 83,000 for 1.0 (exploding).

Nothing is hidden: 16 units, 40 steps, Gaussian recurrent weights at two scales, ten seeds, one norm. Running it exactly as printed gives (our machine, numpy):

NetworkPer-step rateCarry at T = 40 (geometric mean)Spread across the 10 seeds
SimpleRNN, U std = 0.25≈ 0.812.4 × 10⁻⁴1 × 10⁻⁷ … 2 × 10⁻²
SimpleRNN, U std = 1.0≈ 1.338.3 × 10⁴1 × 10³ … 3 × 10⁷

Both rows are the same disease. The per-step rate is the carry taken to the power 1/40 — rate = carry1/T — so the 0.81 row is 0.81⁴⁰ ≈ 0.0002 and the 1.33 row is 1.33⁴⁰ ≈ 9 × 10⁴. Multiply a number less than one by itself forty times and it dies. Multiply a number greater than one and it detonates. We report the geometric mean because single seeds land all over the spread column: when a quantity varies by orders of magnitude, the average of the logs is the honest centre. The tanh is the culprit — its derivative tops out at 1 and averages well below it, so the recurrent path contracts; scale the weights up to compensate and it overshoots into explosion. The network sits on a knife edge between forgetting everything and amplifying everything, and the edge gets narrower as sequences get longer.

Why is 0.25 the dividing line? For a 16×16 Gaussian weight matrix, the typical size of U is std × √n — so std = 1/√16 = 0.25 is exactly the neutral point, where U neither shrinks nor expands a random vector. tanh's slope is below 1, and that tips the neutral point into fading (the 0.81). At std = 1.0 the weights are four times the neutral scale: the state saturates and still explodes.

memory carry (log scale): influence of the first state at step T 10⁵ 10³ 10¹ 10⁻¹ 10⁻³ 10⁻⁴ 01020 3040 time steps T U std 1.0 — explodes (≈ 1.33 per step) U std 0.25 — vanishes (≈ 0.81 per step) forget gate f = 0.982 — the dial (next chapter)
Figure 28.2 — The three fates of a memory, measured. Logarithmic scale, one even decade per gridline: the carry of the first state's information out to step 40. A plain RNN either fades to nothing or blows up — which one depends on weight scale. The green dashed line is the idealised carry of a forget gate held at 0.982 per step, not a measurement of the same simulation: it is the dial the next chapter installs.
⚠
Warning — the exploding twin: vanishing gets the fame, but the same multiplication running hot (U std = 1.0 above) amplifies the past by 1.33 per step — after forty steps, a hundred-thousand-fold. One huge update can throw the weights far away; the loss turns to NaN and training collapses. The standard band-aid is gradient clipping: if the gradient's norm exceeds a ceiling, rescale it down. Keras does not clip for you; you switch it on in the optimizer, e.g. tf.keras.optimizers.Adam(clipnorm=1.0) (or global_clipnorm=1.0). Clipping treats the symptom; the cure needs a new cell.

6. The Honest Calibration: Toys Survive

📖
In plain words · Priya’s notebook

If old news fades so fast, why does Priya still do well on simple tests? Ask her “was the very first headline good or bad?” after 10, 20 or 40 days, and she is usually right. Holding one yes-or-no fact is easy even with a fading memory.

The trouble shows up on harder, longer jobs: combining a debt warning from three months ago with this week’s results, where many details from far apart must be put together. Easy exams do not prove that her method is sound. So we judge the method by measuring how her memory works (Section 5), not only by her exam scores.

Here is what we did next, because you should do it too: we tried to break a plain RNN with training experiments. Two tasks, each needing genuine memory, at three sequence lengths, SimpleRNN(16) versus LSTM(16) — model seed 0, fixed data seeds, real accuracies (our run, TF 2.21):

TaskLengthSimpleRNNLSTM
was the first value positive? (chance 0.500)100.9900.976
200.9780.938
400.8340.952
is the running sum positive? (integration, chance 0.500)200.9640.980
400.9280.966
800.9260.982

Each cell is one run scored on 500 test sequences, so differences of a couple of points are noise — roughly ±1 point of standard error. Read the shape, not the third digit: the plain RNN stayed far above chance everywhere, and it even beat the LSTM on the short sign tasks. The LSTM's edge appears exactly where the mechanism of Section 5 predicts it: the longer sequences, 40 and 80 steps, where fading starts to bite.

Read honestly: the plain RNN survived the toys. Sixteen units, Adam — it held 0.83–0.99, never close to chance, with the fade showing only at the longest lengths. If we had stopped here and printed only this table, we would have "proven" the vanishing gradient irrelevant. The measurement of Section 5 says otherwise, and the reconciliation matters: the disease is about how gradients flow, not about whether a small net can memorise a small trick. Symptoms appear when dependencies get long, information dense, and the state small — language modelling at scale, long documents, long histories — or when you need to learn from scratch, not just hold one bit.

The lesson generalises past RNNs, and it is worth stating as a course rule: mechanism first, shoot-outs second. A benchmark can hide a disease; a derivative cannot.

7. The Dial: a Preview of the Cure

📖
In plain words · Priya’s notebook

Now give Priya a dial she controls: each morning she decides how much of yesterday’s view to keep, from 0 (forget everything) to 1 (keep everything).

For a long-running story, such as a court case that will take months, she sets the dial near 0.98: after 60 days about a third of that view is still with her. For daily noise she turns it down and forgets quickly.

A plain RNN has no such dial: how fast it forgets is fixed by its habits and cannot be chosen. The next chapter’s LSTM adds the dial, and the network learns where to set it, even changing it from day to day.

Look at the green dashed line in Figure 28.2 — the one that refuses to die. That is not a better-scaled tanh. It is a forget gate held at f = 0.982, and it is the entire idea of the next chapter arriving one section early:

Per-step memory rateCarry at T = 60Meaning
0.5 (a gate that outputs σ(0))8.7 × 10⁻¹⁹even a gate at its zero-input value forgets
0.7311 (= σ(1), Keras's init — bias only)6.9 × 10⁻⁹the default starting point — about ten orders of magnitude better than 0.5
0.9820 (= σ(4), trained open)0.34memory that survives 60 steps

The numbers are pure arithmetic — 0.5⁶⁰, 0.7311⁶⁰, 0.9820⁶⁰ — and you can check them on any calculator. The point they make is the hinge of this whole part of the book: the plain RNN's decay rate is stuck, a side effect of weight scale and tanh saturation. The gated cell's decay rate is a learnable parameter. That single change — forgetting as a decision instead of an accident — is the LSTM.

📋 Stable content — Reviewed: October 2026 · Code tested with TensorFlow 2.21 / Keras 3.15

8. Implementation in Python (Keras)

📖
In plain words · Priya’s notebook

Building Priya in code takes four instructions. First, tell the computer the shape of what she reads: how many days, and how many numbers per day.

Second, windowing: hand her the last 10 days of returns and ask for tomorrow, again and again, sliding forward one day at a time. Third, a time-ordered test: she studies the older days and is tested only on later ones, because in real life nobody gets to read tomorrow’s paper.

Fourth, an honest comparison: put her against a lazy analyst who always says “no change”. If Priya cannot beat him, her method has found no edge, and on daily returns that is the usual, honest result. One more switch, return_sequences, decides whether she reports her view every day or only at the end.

The whole zoo in one listing — the sign-memory task from Section 6 at all three lengths, the parameter count opened up, and the habits every sequence project needs: windowing a series, splitting it in time order, and stacking recurrent layers:

# ---- Listing 28.1: sequences in Keras, end to end ----
import numpy as np, tensorflow as tf
tf.keras.utils.set_random_seed(0)
tf.config.experimental.enable_op_determinism()   # same machine + version = same numbers

# task: was the first value of the sequence positive?
def make_data(n, length, seed):
    rng = np.random.default_rng(seed)
    X = rng.uniform(-1, 1, size=(n, length, 1)).astype('float32')
    y = (X[:, 0, 0] > 0).astype('int32')
    return X, y

def run(length):
    X_tr, y_tr = make_data(2000, length, 1)
    X_te, y_te = make_data(500,  length, 2)
    model = tf.keras.Sequential([
        tf.keras.Input(shape=(length, 1)),       # (timesteps, features) — 3D!
        tf.keras.layers.SimpleRNN(16),           # one state vector out
        tf.keras.layers.Dense(1, activation='sigmoid')])
    model.compile('adam', 'binary_crossentropy', metrics=['accuracy'])
    model.fit(X_tr, y_tr, epochs=30, batch_size=64, verbose=0)
    return model.evaluate(X_te, y_te, verbose=0)[1]

for length in (10, 20, 40):                      # Section 6's sign task, three lengths
    print(length, run(length))                   # 0.990 / 0.978 / 0.834 (our run)

model = tf.keras.Sequential([                    # the length-20 model, opened up
    tf.keras.Input(shape=(20, 1)),
    tf.keras.layers.SimpleRNN(16),               # 16*1 + 16*16 + 16 = 288 weights
    tf.keras.layers.Dense(1, activation='sigmoid')])   # 16 + 1 = 17
model.summary()                                  # 305 trainable parameters in total

# windowing a series: (last 10 returns) -> next return
close = np.cumprod(1 + np.random.default_rng(0).normal(0, 0.01, 1000))  # synthetic prices
r = np.diff(np.log(close))                       # log returns
window = 10
X_w = np.array([r[t-window:t] for t in range(window, len(r))])
y_w = r[window:]
X_w = X_w.reshape(len(X_w), window, 1)           # Keras wants 3D: (samples, steps, features)

split = int(0.8 * len(X_w))                      # chronological split — never shuffle time
Xw_tr, Xw_te = X_w[:split], X_w[split:]
yw_tr, yw_te = y_w[:split], y_w[split:]

rnn = tf.keras.Sequential([                      # stacking: first layer returns the FULL sequence
    tf.keras.Input(shape=(window, 1)),
    tf.keras.layers.SimpleRNN(16, return_sequences=True),  # (samples, window, 16)
    tf.keras.layers.SimpleRNN(8),                           # (samples, 8)
    tf.keras.layers.Dense(1)])
rnn.compile('adam', 'mean_squared_error')
rnn.fit(Xw_tr, yw_tr, epochs=20, batch_size=32, verbose=0)

mae   = np.mean(np.abs(rnn.predict(Xw_te, verbose=0).ravel() - yw_te))
naive = np.mean(np.abs(0 - yw_te))               # the trivial baseline: predict zero
print(mae, naive)                                # 0.0067 vs 0.0068 — no edge found

Listing 28.1 — SimpleRNN in Keras, end to end: 3D inputs, three sequence lengths, the 305-parameter count, stacking with return_sequences, and an honest windowed regression with a naive baseline. Every printed number is real (seed 0, our run, TF 2.21).

Listing 28.1, line by line

Not a programmer? Read only the right-hand column: it tells the story of the listing in order, one line (or a few closely linked lines) at a time.

CodeWhat it does, in plain English
import numpy as np, tensorflow as tfLoad numpy (numbers) and TensorFlow (the network-building toolbox).
tf.keras.utils.set_random_seed(0)Fix the computer’s “dice”, so every run starts from the same random numbers.
tf.config.experimental.enable_op_determinism()Ask TensorFlow to do its sums in a fixed order, so the results repeat exactly on the same machine and version.
def make_data(n, length, seed):Define a small factory that makes practice questions: n sequences, each length steps long.
rng = np.random.default_rng(seed)… using its own fixed random-number generator, so the same questions come out every time.
X = rng.uniform(-1, 1, size=(n, length, 1)).astype('float32')… fill each sequence with random numbers between −1 and +1 (think of them as daily scaled returns). The shape (n, length, 1) means: n sequences, length steps each, 1 number per step.
y = (X[:, 0, 0] > 0).astype('int32')… the correct answer for each sequence: 1 if its first number was positive, otherwise 0. To answer, the network must remember step 1 all the way to the end.
return X, y… hand back the questions and the answers.
def run(length):Define one complete experiment for a given sequence length:
X_tr, y_tr = make_data(2000, length, 1) X_te, y_te = make_data(500, length, 2)… make 2,000 study sequences and 500 different test sequences (different seeds, so no overlap);
model = tf.keras.Sequential([… build a network as a stack of layers:
tf.keras.Input(shape=(length, 1)), # (timesteps, features) — 3D!… the input is length steps with 1 number per step. With the batch of sequences in front, Keras sees three dimensions: (sequences, steps, numbers per step);
tf.keras.layers.SimpleRNN(16), # one state vector out… a plain recurrent layer with a 16-number memory. It reads the steps one by one and passes on only its final memory;
tf.keras.layers.Dense(1, activation='sigmoid')])… one last unit that turns that memory into a probability between 0 and 1 that the first number was positive;
model.compile('adam', 'binary_crossentropy', metrics=['accuracy'])… choose how it learns: adam adjusts the weights, binary cross-entropy measures how wrong a yes/no guess is, and accuracy is tracked;
model.fit(X_tr, y_tr, epochs=30, batch_size=64, verbose=0)… train: go through the 2,000 study sequences 30 times, adjusting after every 64, quietly;
return model.evaluate(X_te, y_te, verbose=0)[1]… score it on the 500 unseen test sequences and return the accuracy.
for length in (10, 20, 40): print(length, run(length))Run the experiment for sequences of 10, 20 and 40 steps and print each accuracy. Our run: 0.990, 0.978 and 0.834. Remembering step 1 gets harder as the sequence gets longer, which is the fading memory of Section 5.
model = tf.keras.Sequential([ tf.keras.Input(shape=(20, 1)),Build the length-20 model once more, only to look inside it:
tf.keras.layers.SimpleRNN(16), # 16*1 + 16*16 + 16 = 288 weights… the recurrent layer owns 288 weights: 16 input weights W (one input number × 16 units), 256 memory weights U (16 × 16) and 16 biases b;
tf.keras.layers.Dense(1, activation='sigmoid')]) # 16 + 1 = 17… the output unit owns 17: one weight for each of the 16 memory numbers, plus one bias.
model.summary()Print a table of the layers and their weight counts: 305 in total. The same 305 are used at every step, however long the sequence.
close = np.cumprod(1 + np.random.default_rng(0).normal(0, 0.01, 1000))Make up a price path for practice: 1,000 days, each day moving by a random amount of about ±1%, multiplied together like real compounding. These are not real prices.
r = np.diff(np.log(close))Turn the prices into daily returns (very close to the percentage change from one day to the next).
window = 10Each question will look at the last 10 days.
X_w = np.array([r[t-window:t] for t in range(window, len(r))])Build the questions: for each day t, the 10 returns just before it. This is called windowing.
y_w = r[window:]Build the answers: the return on day t itself, the “next” day after each window.
X_w = X_w.reshape(len(X_w), window, 1)Reshape the questions into the three dimensions Keras wants: (questions, 10 steps, 1 number per step).
split = int(0.8 * len(X_w))Find the point where the first 80% of the days end.
Xw_tr, Xw_te = X_w[:split], X_w[split:] yw_tr, yw_te = y_w[:split], y_w[split:]Study on the earlier 80%, test on the later 20%. Never shuffle time: in real life you cannot study tomorrow before predicting it.
rnn = tf.keras.Sequential([Build a stacked network, two recurrent layers deep:
tf.keras.Input(shape=(window, 1)),… the input is 10 days with 1 number each;
tf.keras.layers.SimpleRNN(16, return_sequences=True),… the first recurrent layer reports its memory at every one of the 10 steps (return_sequences=True), because the next layer needs a sequence to read;
tf.keras.layers.SimpleRNN(8),… the second recurrent layer reads that sequence of memories and passes on only its final 8-number memory;
tf.keras.layers.Dense(1)])… one output unit gives the forecast. There is no sigmoid, because a return can be any number.
rnn.compile('adam', 'mean_squared_error')Learn with adam, measuring error as the average squared miss.
rnn.fit(Xw_tr, yw_tr, epochs=20, batch_size=32, verbose=0)Train on the study period: 20 passes, adjusting after every 32 questions.
mae = np.mean(np.abs(rnn.predict(Xw_te, verbose=0).ravel() - yw_te))Forecast the test days and measure the average size of the miss (MAE).
naive = np.mean(np.abs(0 - yw_te))Measure the miss of a lazy forecaster who always says “no change” (a return of 0).
print(mae, naive)Print both. Our run: 0.0067 against 0.0068, a difference of one ten-thousandth. Because the prices were random by construction, there is nothing to find, and the network rightly finds nothing.

A word about that last line. The synthetic series is a random walk, and real next-day returns are close to noise too. A test MAE one ten-thousandth below the naive baseline and an R² below zero are the expected, honest results — R² near zero means "no edge found", not "code broken". We met the same honesty rule in Chapter 26's price regression, and we will meet it again with real prices in Chapter 29.

💡
Pro Tip — the three shapes: in this book we feed a Dense layer a 2D matrix (samples, features); a recurrent layer eats 3D (samples, timesteps, features); and with return_sequences=True it outputs 3D — which is exactly why only the last recurrent layer in a stack may drop it, when what follows needs a single vector per sample. Most first-Keras-RNN bugs are shape bugs from this rule.

One more map, so return_sequences does not look like a stacking trick only. Everything in this chapter is many-to-one: a whole sequence in, one number out — sentiment, next return. Set return_sequences=True and the layer emits one state per step — many-to-many, the shape behind tagging every word in a sentence or predicting every step of a trajectory. And one-to-many — one seed in, a sequence out — is the decoder half of the sequence-to-sequence machines Chapter 29 builds.

⚠ Volatile content — Reviewed: October 2026 · Next review: January 2027

9. The Road Ahead

📖
In plain words · Priya’s notebook

Priya’s one-note method was the standard approach for a while. The next generation of analysts got a better notebook: one with the dial from Section 7, which decides what to keep and what to cross out (the LSTM, Chapter 29). Today the strongest analysts work differently again: instead of trusting a single running note, they can reread the whole archive at once and pick out the headlines that matter (the transformer, met at the end of Chapter 29).

A short history, because the architecture's fate explains the next chapter's design. Recurrence was formalised in the 1980s; the vanishing-gradient analysis made the disease precise in the early 1990s; and in 1997 Hochreiter and Schmidhuber published the cure — long short-term memory — which Chapter 29 builds gate by gate. Plain RNNs are now a teaching chapter, not a production choice: almost nobody ships a plain SimpleRNN for real sequence work.

And Chapter 25's map finally gets paid. Its innermost ring — sequence-to-sequence, the models that read one sequence and write another — is built from exactly the gated cells of Chapter 29: an encoder state passed to a decoder. When you reach the end of Chapter 29, you will have every component that translation engines and chatbots were made of for several years — and you will also meet the rival that replaced them at scale.

Where the field stands right now: attention-based transformers — the rival you meet at the end of Chapter 29 — dominate sequence work at scale, and a newer family of linear-recurrence models (state-space models such as Mamba, and RWKV) has brought recurrence itself back into fashion as a research direction. This paragraph is the reason the section carries a quarterly review cycle: these sentences age.

🛠 Hands-On: Unroll, Measure, and Break ItIntermediate

Build the chapter's central claim yourself. You will compute hidden states by hand, then measure memory carry with exact Jacobians, then try — honestly — to break a SimpleRNN with training.

Steps

  1. Hand-compute Section 3's two steps (tanh(1), tanh(−0.6192)). Then add a third step x₃ = 0.5 and compute h₃ with the same W = 1, U = 0.5.
  2. Run Listing 28.1's sign-memory task at lengths 10, 20, 40 (the run() loop does all three). Reproduce 0.990 / 0.978 / 0.834 on the same machine and TF version; elsewhere expect a point or two of drift, and a bigger wobble on the length-40 dip.
  3. Implement the carry measurement of Section 5 in numpy (the short loop — or start from ch28_starter.py). Reproduce the geometric means: ≈ 2.4 × 10⁻⁴ at T = 40 with U std = 0.25, and ≈ 8.3 × 10⁴ with U std = 1.0.
  4. Design your own breaking task — longer sequences, more information, smaller state (4 units). Can you push SimpleRNN to chance while an LSTM holds? Report your best attempt honestly, including failures.
  5. Verify the dial arithmetic: 0.5⁶⁰, 0.7311⁶⁰, 0.9820⁶⁰ — three calculator presses, one table row each.
  6. No code, pencil only. Priya holds a view of +1 and then no news arrives for many days. If she keeps half of yesterday’s view each day (U = 0.5, ignoring the squashing), how much of the +1 is left after 1, 2, 3 and 10 days? Now repeat with a keep-rate of 0.98. Explain in two sentences, to someone who has never seen a formula, why the second analyst can follow a long story and the first cannot.
View Solution / Walkthrough

Step 1. h₃ = tanh(1·0.5 + 0.5·(−0.5506)) = tanh(0.2247) = 0.2210. The memory fades: 0.7616 → −0.5506 → 0.2210 — each state is a diluted echo of the last.

Step 2. 0.990, 0.978, 0.834 on our machine (TF 2.21, CPU, seed 0). The length-40 dip is the fade beginning to bite — but its depth moves by several points between setups: an earlier protocol of ours printed 0.954 in that same cell. Judge against chance (0.5), not against our third digit.

Step 3. Individual seeds vary by orders of magnitude — that is what the spread column says. Do not expect your first seed to match the mean; run all ten and average the logs. The geometric collapse is the point, not the third digit.

Step 4. There is no single right answer — treat this as a hypothesis to test, not a fact to confirm. In our tries, one bit of memory for 40 steps was survivable, and the gap seemed to widen beyond roughly 100 steps, where early details must combine with late ones. We did not measure that carefully enough to print numbers, and you may find otherwise. If your task didn't break either model, report that too: mechanism (Section 5) is the reliable evidence, shoot-outs are not.

Step 5. 0.5⁶⁰ = 8.7 × 10⁻¹⁹, 0.7311⁶⁰ = 6.9 × 10⁻⁹, 0.9820⁶⁰ = 0.34 — the Section 7 table, three calculator presses.

Step 6. Keep-rate 0.5: 0.5, 0.25, 0.125 after 1, 2, 3 days, and about 0.001 after 10 days, which is effectively gone. Keep-rate 0.98: 0.98, 0.96, 0.94, and still about 0.82 after 10 days. A possible answer: “The first analyst halves her memory every day, so within a week or two old news has vanished. The second keeps almost everything each day, so news from weeks ago still shapes her view.”

🎯 Key Takeaways

1

A recurrent network reads a sequence step by step and carries a state — the same weights at every step, weight sharing through time.

2

The cell is Chapter 26's neuron plus one loop: ht = tanh(U·ht−1 + W·xt + b). By hand: 1 → 0.7616 → −0.5506.

3

Measured, not asserted: the plain RNN's memory carry at T = 40 is 2.4 × 10⁻⁴ (vanishing) or 8.3 × 10⁴ (exploding) — geometric means over ten seeds; same disease, two directions.

4

Toy tasks survive the disease (0.83–0.99, far above chance, fading only at length). Mechanism first, shoot-outs second: a benchmark can hide a disease; a derivative cannot.

5

The cure is a dial: a learnable forget rate. 0.5⁶⁰ dies, 0.982⁶⁰ = 0.34 survives. That dial is Chapter 29.

📖
The whole chapter in plain words

Priya reads one headline a day and keeps one number for her view. Each morning she mixes today’s news with yesterday’s view, always with the same habits. That is a recurrent network. Because she keeps only part of yesterday each day, old news fades, and her lessons about old news fade too, so she cannot learn from the distant past. Easy tests do not reveal this. The fix, in the next chapter, is a dial that lets her decide what to keep.

Test Your Understanding

30 questions from the whole chapter: order, the recurrent idea, the hand-worked cell, BPTT and its Jacobian, the measured vanishing gradient, the honest calibration, the dial, and the Keras habits. Choose one answer per question, then check your answers.

Q1.The networks in this chapter are built to:

Q2.The pair “not good” vs “good” — same words, different order — shows:

Q3.The hidden state ht is best described as:

Q4.“Weight sharing through time” means:

Q5.Because the same weights serve every time step, a trained RNN can:

Q6.“Unrolling” a recurrence means:

Q7.(Hand) With W = 1, U = 0.5, b = 0 and x₁ = 1 (h₀ = 0), the first state h₁ is:

Q8.(Calculator) Same cell, next step: x₂ = −1, with h₁ = 0.7616 from the previous question. The state h₂ is:

Q9.(Hand) A SimpleRNN layer with 16 units reading 5 input features owns:

Q10.Backpropagation through time (BPTT) is:

Q11.Because W, U and b are shared across all steps, each parameter's gradient is:

Q12.“Truncated BPTT” means:

Q13.The recurrence Jacobian ∂ht/∂ht−1 equals:

Q14.Within one sequence, how does the Jacobian factor change from step to step?

Q15.The vanishing gradient in a plain RNN is caused by:

Q16.(Real) The measured memory carry at T = 40 for the 16-unit SimpleRNN with U std = 0.25 was:

Q17.With U std = 1.0 the same measurement explodes to 8.3 × 10⁴. The standard first aid is:

Q18.The carry measurement of Section 5 works by:

Q19.Why measure Jacobians instead of trusting task accuracy?

Q20.(Real) In the honest calibration of Section 6, the plain RNN:

Q21.Why is std = 0.25 the neutral weight scale for a 16-unit layer?

Q22.tanh is chosen for the state because:

Q23.(Calculator) 0.982⁶⁰ is approximately:

Q24.The key improvement the gated cell of Chapter 29 offers is:

Q25.Keras' SimpleRNN layer expects input shaped:

Q26.With return_sequences=True, a recurrent layer outputs:

Q27.Tagging every word in a sentence with its part of speech is:

Q28.“Windowing” a price series for a recurrent model means:

Q29.For time-series forecasting, the train/test split must be:

Q30.In production sequence work today, plain SimpleRNN layers are: