Chapter 29 · Long Short-Term Memory
Chapter 28 ended with a measurement and a promise: the plain RNN's memory decays at a rate it cannot choose, and the cure is a dial. This chapter installs it. The LSTM cell keeps a separate conveyor belt — the cell state — that later steps can change in only two ways, controlled by learned gates: a forget gate that scales the old content and an input gate that adds new content; a third, the output gate, decides how much of the belt to reveal. One full cell step is computed by hand, every number exact. The parameter law is verified against Keras itself (LSTM costs exactly 4× the plain RNN). Then two real applications: the memory for order goes back to Chapter 25's restaurant reviews (0.775–0.800 over five seeds, scored against the famous beat-73% board), and to next week's AAPL return (racing a Dense network and two do-nothing baselines). It closes the loop Chapter 25 opened: encoder, decoder, sequence-to-sequence, and the rival that replaced them at scale. As in Chapter 28, every section opens with a plain-words box that follows Priya, the analyst, and her new two-part notebook.
🎯 Learning Objectives
- Explain in plain words, through Priya’s two-part notebook, how an LSTM decides what to keep, what to add and what to reveal
- Explain the cell state as a conveyor belt that later steps touch only through gates — and why that repairs Chapter 28's measured gradient collapse
- Compute one full LSTM cell step by hand: forget, input, output gates, candidate, cell state, hidden state — every value exact
- State and verify the parameter law: SimpleRNN nm+n²+n, GRU 3(nm+n²+2n), LSTM 4(nm+n²+n), checked against Keras’s own counts
- Build an LSTM text classifier in Keras (embedding, masking, the Keras-3 tokenizer note) and read its result against Chapter 25's scoreboard
- Run the finance race honestly: LSTM vs Dense vs naive on next week's return, and state the recurring lesson about public-price edges
- Describe seq2seq as an encoder state handed to a decoder — Chapter 25's map finally paid — and name the architecture that replaced recurrence at scale
1. The Conveyor Belt
In Chapter 28, Priya kept one number on a sticky note and rewrote it every morning. Each rewrite kept only part of yesterday, so old news faded whether it mattered or not: after 40 days, a headline from day 1 was almost gone.
Her manager gives her a better notebook with two parts. The first is a ledger: a running record she never rewrites from scratch. Each morning she may only do two things to it: cross out some of what is there, and add a new line. The second part is a short daily note for her manager, written from the ledger.
Because nothing in the ledger is rewritten automatically, an important old entry stays exactly as it is until Priya decides to cross it out. That one change is the whole idea of this chapter.
Chapter 28's cell had one register, the hidden state h, doing two jobs at once: remembering the past and exposing it to the output. Every step rewrote it completely: ht = tanh(…). Each rewrite multiplies the past by a factor, and Chapter 28 measured where that ends: a geometric-mean carry of about 2.4 × 10−4 after forty steps.
The long short-term memory cell, or LSTM, splits the two jobs. The idea and the constant-error path are due to Hochreiter and Schmidhuber (1997); the forget gate, which makes that path adjustable, was added by Gers, Schmidhuber and Cummins (2000) and is part of every modern LSTM. The cell adds a second register, the cell state c, that flows through time untouched by any weight matrix. No tanh squashes it on the way. It is a conveyor belt running the length of the sequence, and a step can change it in only two ways, each controlled by a learned valve: scale down what is already there, or add something new.
The hidden state h survives too, but with a smaller job: it is the readable face of the belt, ht = ot ⊙ tanh(ct), filtered by an output gate o. The output gate reads from the belt without changing it. Memory lives on the belt; the network speaks through h.
2. The Three Gates
Every morning, after reading the headline and her last daily note, Priya answers four questions:
1. How much of the ledger should I keep? A
number from 0 (cross out everything) to 1 (keep everything). This is
the forget gate, the dial from Chapter 28.
2. What does today’s news say? A draft line
from −1 (bad) to +1 (good). This is the candidate.
3. How much of that draft should I write into the
ledger? From 0 (ignore it) to 1 (write it in full). This is
the input gate.
4. How much of the ledger should I tell my manager
today? From 0 (say nothing) to 1 (say it all). This is the
output gate; it does not change the ledger.
She does not answer by mood. Each answer follows a learned habit that depends on today’s headline and yesterday’s note, and the same habits are used every day.
A gate is Chapter 11’s sigmoid doing the one job it is shaped for: producing a number between 0 and 1 that scales something. Each gate looks at the current input xt and the previous hidden state ht−1, with its own weights:
| Part | Formula | Range | Job |
|---|---|---|---|
| Forget gate f | σ(Wf·xt + Uf·ht−1 + bf) | 0 = drop the past · 1 = keep all of it | the dial from Chapter 28 §7: the learnable memory rate |
| Input gate i | σ(Wi·xt + Ui·ht−1 + bi) | 0 = write nothing · 1 = write fully | how much new information enters the belt |
| Candidate g | tanh(Wg·xt + Ug·ht−1 + bg) | −1 … 1 | the content proposed for the belt: not a gate, the ink |
| Output gate o | σ(Wo·xt + Uo·ht−1 + bo) | 0 = stay silent · 1 = speak fully | how much of the belt this step reveals as ht |
Each row has its own W, U and b: four separate sets of weights. Read the four together as a sentence the cell says at every step: keep f of what I had, write i of this new thing g, and show o of the result.
A forget gate near 1 for many steps is exactly the 0.982-rate carry of Chapter 28’s green dashed line: memory that survives. Unlike the plain RNN’s stuck rate, this one is trained to be whatever the task needs, and it can change from step to step.
unit_forget_bias=True). With the weights’
contribution at zero, a fresh LSTM therefore starts with
f = σ(1) = 0.731: already leaning towards remembering. Training
then pushes the bias wherever the sequences demand. The trick was
popularised by Jozefowicz, Zaremba and Sutskever (2015).
3. One Cell Step, by Hand
Priya’s ledger stands at 0.5 (mildly positive). This morning she decides to keep 73% of it, so 0.37 stays. Today’s headline is strongly good: her draft line is 0.76, and she writes 73% of it in, adding 0.56. The ledger now reads 0.92.
But she is cautious with her manager: she reveals only about half of what the ledger says, and her daily note reads 0.40. She knows more than she says. The ledger keeps the full picture for later days; the note is only today’s summary.
The smallest honest cell: one input, one hidden unit. Coming in: xt = 1.0, ht−1 = 0.2, ct−1 = 0.5. We choose the weights so that each pre-activation is easy to read:
| Part | W (input) | U (recurrent) | b (bias) |
|---|---|---|---|
| forget f | 0 | 0 | 1 |
| input i | 1 | 0 | 0 |
| candidate g | 1 | 0 | 0 |
| output o | 0 | 1 | 0 |
| Quantity | Raw sum (W·x + U·h + b) | Value |
|---|---|---|
| forget gate | 0·1 + 0·0.2 + 1 = 1 | f = σ(1) = 0.7311 |
| input gate | 1·1 + 0·0.2 + 0 = 1 | i = σ(1) = 0.7311 |
| candidate | 1·1 + 0·0.2 + 0 = 1 | g = tanh(1) = 0.7616 |
| output gate | 0·1 + 1·0.2 + 0 = 0.2 | o = σ(0.2) = 0.5498 |
| cell state | 0.7311·0.5 + 0.7311·0.7616 = 0.3655 + 0.5568 | ct = 0.9223 |
| hidden state | 0.5498 · tanh(0.9223) = 0.5498 · 0.7270 | ht = 0.3997 |
Read the story in the numbers. The belt held 0.5; the forget gate kept 73% of it (0.3655) and the input gate wrote 73% of a strong new candidate (0.5568); the belt now reads 0.9223. The output gate, seeing only a modest h, opens 55%, so the cell remembers more than it says: c = 0.92 underneath, h = 0.40 on the surface. That gap is the LSTM’s signature. Note that c is not squashed: it can grow beyond 1 over several steps, and only the copy shown as h passes through tanh.
4. Why the Gates Cure the Disease
With the sticky note, every rewrite shrank old news a little, automatically, every day. With the ledger, an old entry shrinks only by Priya’s own keep-decision. For an important, long-running story she keeps nearly everything (say 98% a day), so the entry is still there weeks later.
The same is true when her manager’s feedback walks backwards through the notebook: it travels along the ledger and is reduced only by those keep-decisions, so lessons can reach early days. And she can learn where to set the keep-dial, because the feedback reaching it is not lost on the way.
There is a price: four sets of habits instead of one, so four times as many settings to learn.
Back to Chapter 28’s measurement, now with the belt in view. The gradient of the loss with respect to an earlier cell state cs flows along ct = ft ⊙ ct−1 + it ⊙ gt. Differentiate the belt and the leading term is just ft, so along the belt alone the carry from step s to step T is fs+1 · fs+2 ⋯ fT: a product of learned numbers, each free to sit near 1. The plain RNN’s product was of Jacobians, ∏ diag(1 − h²)·U, squeezed by a tanh it could not negotiate with. The LSTM replaced the squeeze with a decision.
That product is one path, not the whole story: the gates also depend on ht−1, so influence leaks along other paths too. So we measure the whole thing, exactly as in Chapter 28: a 16-unit LSTM with Keras-style initial weights (Glorot input weights, orthogonal recurrent weights), random inputs, T = 40, the full Jacobian of the state (hT, cT) with respect to (h0, c0), Frobenius norm, geometric mean over ten seeds:
| Forget-gate bias | Average f | Belt-only product f40 | Measured carry at T = 40 |
|---|---|---|---|
| 0 | 0.50 | 9 × 10−13 | ≈ 5 × 10−6 |
| 1 (Keras default) | 0.73 | 4 × 10−6 | ≈ 0.16 |
| 4 | 0.98 | 0.48 | ≈ 50 |
Two lessons. First, the measured carry at the default bias (≈ 0.16) is several hundred times the plain RNN’s 2.4 × 10−4 in Chapter 28 (the set-ups differ, so read the order of magnitude, not the digits), and far above the belt-only f40: the other paths carry influence too. Second, a gate held near 1 does not guarantee a stable gradient: at bias 4 the carry grows to about 50, the exploding twin again. The LSTM does not remove the knife edge; it hands the network a dial and lets training find the right setting. (The script is in the Hands-On solution.)
The honest footnote. At bias 0 a gate sits at 0.5 and the belt decays like 0.560 = 8.7 × 10−19. Keras’s bias of 1 only buys 0.7360 ≈ 7 × 10−9 along the belt. Neither remembers sixty steps at initialisation. The cure is that gradient descent can open the gate: the forget-gate bias receives a clean gradient along the belt and moves toward what the task needs. In practice LSTMs learn dependencies of tens to low hundreds of steps.
The cure has a price tag, and it is exact. Each of the four parts has a full set of input weights, recurrent weights and biases, so the cell owns four blocks where the plain RNN owned one:
5. GRU — the Streamlined Cousin
Priya’s colleague Arjun uses a simpler notebook: one page instead of a ledger plus a note, and two valves instead of three. One dial decides the blend each morning (“keep 70% of my old view, take 30% from today”), and a second valve decides how much of his old page he looks at while drafting today’s line. His method has fewer habits to learn, and on most jobs he does about as well as Priya.
In 2014 Cho and colleagues asked which parts of the LSTM carry the load, and removed the rest. The GRU (gated recurrent unit) drops the separate cell state and the output gate and keeps two gates: a reset gate r (how much of the past the candidate may see) and an update gate z (the forget-and-write blend, used in both roles):
| Cell | Registers | Gates | Params (n = 16, m = 5) | Character |
|---|---|---|---|---|
| SimpleRNN | 1 (h) | none | nm+n²+n = 352 | forgets, cannot choose to |
| GRU | 1 (h) | 2 (reset, update) | 3(nm+n²+2n) = 1,104 | lighter, merges forget and write |
| LSTM | 2 (c and h) | 3 + candidate | 4(nm+n²+n) = 1,408 | the full belt; most control |
All three counts are the ones Keras reports. GRU’s formula has
2n per block where the others have n: the extra n per block (3n in
total, 48 parameters here) comes from Keras’s default
reset_after=True, which stores the input and recurrent
biases separately. On benchmarks GRU and LSTM trade wins; the practical
rule is simple: same family, same recipes, try both when it matters,
and expect small differences.
6. Bidirectional and Stacked
Stacked: a senior analyst reads Priya’s daily notes instead of the raw news, and keeps her own notebook on top. Each layer works from a more digested view.
Two directions: when Priya reviews a finished report, reading it once forwards and once backwards helps: a “not” near the end can change how the first line should be read. That is fair, because the whole report is on her desk. But when she is forecasting, reading backwards means reading tomorrow’s newspaper. Any forecast built that way looks brilliant on old data and is useless in real life.
Two standard assemblies, one warning each:
- Stacked recurrent layers: the first layer returns
its state at every step (
return_sequences=True) so the second layer can read the whole sequence of states, Chapter 28’s rule unchanged. Each layer builds features over the last one’s output. - Bidirectional: one LSTM reads left to right,
another right to left, and their final states are concatenated.
Bidirectional(LSTM(16))therefore outputs 32 numbers and owns twice the parameters (2 × 1,408 at the chapter’s n = 16, m = 5). Legitimate and powerful for offline text, where a sentence’s end often disambiguates its start. Illegitimate for forecasting: the backward pass reads tomorrow to predict today. Bidirectional leakage is the sequence version of Chapter 3’s leakage rule, and it produces beautiful backtests that trade on nothing.
One more switch you will need in Section 10: by default a Keras
LSTM returns only the last hidden state h. Pass
return_state=True and it also returns the final h and c
separately, which is how an encoder hands its memory to a decoder.
7. Implementation in Python (Keras)
A network cannot read letters, so we first make a dictionary: every common word gets a number (“good” might be 7, “not” 12). Words that are not in the dictionary all get one shared number meaning “unknown”. The dictionary is built from the training reviews only, so the test reviews stay truly unseen.
Reviews have different lengths, so short ones are filled up with blank days, and a mask tells the network to skip those blanks instead of reading them as words. For the price experiment, we cut the history into windows, test only on later weeks, and leave a short gap between the two, so that no answer from the study period leaks into the test.
Two listings, both run for real. First the text pipeline, with a
transparent hand-rolled tokenizer. Keras 3 removed the old
keras.preprocessing.text module; its official replacement
is the TextVectorization layer, which does the counting,
ranking, indexing and padding inside the model. The fifteen lines below
do the same job in plain Python, so every step is visible:
# ---- Listing 29.1: LSTM sentiment on the restaurant reviews ----
import numpy as np, pandas as pd, re, collections, tensorflow as tf
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
tf.keras.utils.set_random_seed(0)
tf.config.experimental.enable_op_determinism() # same machine + version = same numbers
ds = pd.read_csv('Restaurant_Reviews.tsv', delimiter='\t', quoting=3)
tokens = [re.sub('[^a-z ]', ' ', t.lower()).split() for t in ds['Review']]
y = ds.iloc[:, -1].values
# split FIRST (same 800/200 split as Chapter 25), then build the vocabulary from training rows only
train_idx, test_idx = train_test_split(np.arange(len(ds)), test_size=0.2, random_state=0)
freq = collections.Counter(w for i in train_idx for w in tokens[i])
vocab = {w: k + 2 for k, (w, _) in enumerate(freq.most_common(1498))} # 0 = pad, 1 = unknown
MAXLEN = 20 # 106 of 1,000 reviews are longer and get cut
X = np.zeros((len(tokens), MAXLEN), dtype='int32')
for r, toks in enumerate(tokens):
idx = [vocab.get(w, 1) for w in toks[:MAXLEN]] # unknown words -> 1, never 0
X[r, :len(idx)] = idx # pad the rest with 0
X_train, X_test, y_train, y_test = X[train_idx], X[test_idx], y[train_idx], y[test_idx]
model = tf.keras.Sequential([
tf.keras.layers.Embedding(1500, 16, mask_zero=True), # word index -> 16 numbers; skip pads
tf.keras.layers.LSTM(16), # the belt
tf.keras.layers.Dense(1, activation='sigmoid')])
model.compile('adam', 'binary_crossentropy', metrics=['accuracy'])
model.fit(X_train, y_train, epochs=15, batch_size=32, verbose=0) # epochs fixed in advance
y_pred = (model.predict(X_test, verbose=0) > 0.5).astype(int).ravel()
print((y_pred == y_test).mean()) # 0.775 (our run)
print(confusion_matrix(y_test, y_pred)) # [[84 13]
# [32 71]]
# ---- look at some predictions ----
probs = model.predict(X_test, verbose=0).ravel()
right = np.where(y_pred == y_test)[0][:3] # three it got right ...
wrong = np.where(y_pred != y_test)[0][:3] # ... and three it got wrong
for i in np.concatenate([right, wrong]):
r = test_idx[i]
print(f"{probs[i]:.2f} said {y_pred[i]} truth {y_test[i]} | {ds['Review'][r][:60]}")
def encode(text): # a new sentence, same dictionary, same padding
idx = [vocab.get(w, 1) for w in re.sub('[^a-z ]', ' ', text.lower()).split()[:MAXLEN]]
return np.array([idx + [0] * (MAXLEN - len(idx))], dtype='int32')
for text in ['the food was good', 'the food was not good', 'not bad at all']:
print(f"{model.predict(encode(text), verbose=0)[0, 0]:.2f} {text}")
Listing 29.1 — Order-sensitive sentiment: words → integer indices (0 = pad, 1 = unknown) → padded sequences → embedding → LSTM → sigmoid. Our run (seed 0, TF 2.21, CPU): accuracy 0.775. On another machine or version expect a point or two of drift. The last part prints six test reviews with the network’s verdict, and its verdict on three new sentences.
What Listing 29.1 prints (our run, seed 0, TF 2.21):
0.775
[[84 13]
[32 71]]
0.06 said 0 truth 0 | the presentation of the food was awful.
0.01 said 0 truth 0 | Worst food/service I've had in a while.
0.04 said 0 truth 0 | Never again will I be dining at this place!
0.73 said 1 truth 0 | The ambiance isn't much better.
0.17 said 0 truth 1 | This place is a jewel in Las Vegas, and exactly what I've be
0.08 said 0 truth 1 | The only thing I did like was the prime rib and dessert sect
0.58 the food was good
0.13 the food was not good
0.01 not bad at all
Reading the result of Listing 29.1
| What is printed | What it tells us |
|---|---|
0.775 |
The network classified 155 of the 200 test reviews correctly (77.5%). These are reviews it never saw while learning. |
[[84 13] |
The confusion matrix. Rows are the truth, columns the network’s answer. Of the 97 negative reviews, 84 were correctly called negative and 13 were wrongly called positive. Of the 103 positive reviews, 71 were found and 32 were missed. So the network is quicker to say “negative”: it catches 87% of the complaints but only 69% of the compliments. When it does say “positive”, it is right 71 times out of 84 (85%). |
0.06 said 0 truth 0 | the presentation of the food was awful.(and the next two lines) |
Three correct calls. The first number is the network’s probability that the review is positive; below 0.5 means “negative”. Clear complaint words (“awful”, “worst”, “never again”) push the probability close to 0. |
0.73 said 1 truth 0 | The ambiance isn't much better. |
A wrong call, and an instructive one. The cleaning step cuts “isn’t” into “isn” and “t”, and “isn” never appeared in the training reviews, so it becomes “unknown”. The negation is invisible, and “better”, a praise word, wins. |
0.17 said 0 truth 1 | This place is a jewel in Las Vegas, ... |
Missed praise. “Jewel” never appeared in the training reviews, so the strongest positive word is “unknown”, and the review is 23 words long, so its last three words were cut off. |
0.08 said 0 truth 1 | The only thing I did like was the prime rib ... |
Missed again, but a human might hesitate too: “the only thing I did like” sounds like a complaint, yet the review is labelled positive. |
0.58 the food was good0.13 the food was not good |
The point of the chapter in two lines. The same words, with “not” added, move the verdict from positive (0.58) to clearly negative (0.13). The network reads the words in order and lets “not” change what follows. |
0.01 not bad at all |
An honest limit. “Not bad at all” is praise, but the network calls it strongly negative: it has learned that “not” and “bad” each point to a complaint, and 800 short reviews contain too few double negatives to learn that two negatives can make a positive. |
Bottom line. The LSTM works: it reads word by word, it uses “not”, and it is right about three times in four. Its mistakes come from words it has never seen and from phrasing it had too few examples to learn. Section 8 compares the 0.775 with Chapter 25’s scoreboard and asks whether the difference is real.
Listing 29.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.
| Code | What it does, in plain English |
|---|---|
import numpy as np, pandas as pd, re, collections, tensorflow as tf | Load the toolboxes we need: numpy for numbers, pandas for tables, re for cleaning text, collections for counting, and tensorflow for building the network. |
from sklearn.model_selection import train_test_split | Borrow a ready-made tool that splits the data into a study part and a test part. |
from sklearn.metrics import confusion_matrix | Borrow a tool that counts the right and wrong answers by type (see the last line). |
tf.keras.utils.set_random_seed(0) | Fix the computer’s “dice”. Networks start from random numbers; fixing the seed means every run starts the same way. |
tf.config.experimental.enable_op_determinism() | Ask TensorFlow to do its sums in a fixed order, so the result repeats exactly on the same machine and version. |
ds = pd.read_csv('Restaurant_Reviews.tsv', delimiter='\t', quoting=3) | Open the file of 1,000 restaurant reviews as a table. The columns are separated by tabs; quoting=3 says “treat quote marks inside a review as ordinary text”. |
tokens = [re.sub('[^a-z ]', ' ', t.lower()).split() for t in ds['Review']] | For every review: make it lower case, replace anything that is not a letter or a space with a space, and cut it into a list of words. “Wow... Loved this place.” becomes [‘wow’, ‘loved’, ‘this’, ‘place’]. |
y = ds.iloc[:, -1].values | Take the last column: the correct answer for each review (1 = the customer liked it, 0 = did not). |
train_idx, test_idx = train_test_split(np.arange(len(ds)), test_size=0.2, random_state=0) | Shuffle the review numbers 0–999 and put 800 in a study pile and 200 in a test pile. random_state=0 gives exactly the same split as Chapter 25, so the scores can be compared. |
freq = collections.Counter(w for i in train_idx for w in tokens[i]) | Count how often each word appears, using the study reviews only, so the test reviews stay unseen. |
vocab = {w: k + 2 for k, (w, _) in enumerate(freq.most_common(1498))} | Build the dictionary: the most common word gets number 2, the next gets 3, and so on, for 1,498 words. Number 0 is kept for “blank” and number 1 for “unknown word”. |
MAXLEN = 20 | Every review will be made exactly 20 words long. The 106 longer reviews lose their extra words; shorter ones are filled with blanks. |
X = np.zeros((len(tokens), MAXLEN), dtype='int32') | Make an empty grid: one row per review, 20 columns, every cell 0 (blank). |
for r, toks in enumerate(tokens): | Go through the reviews one at a time (r is the review’s row number, toks its list of words). |
idx = [vocab.get(w, 1) for w in toks[:MAXLEN]] | Take the first 20 words and swap each for its dictionary number. A word that is not in the dictionary becomes 1 (“unknown”), never 0. |
X[r, :len(idx)] = idx | Write those numbers into the review’s row, starting from the left. The cells left over stay 0: that is the padding. |
X_train, X_test, y_train, y_test = X[train_idx], X[test_idx], y[train_idx], y[test_idx] | Pull out the 800 study rows and the 200 test rows, each with its correct answers. |
model = tf.keras.Sequential([ | Start building the network as a stack of layers that the data passes through from top to bottom. |
tf.keras.layers.Embedding(1500, 16, mask_zero=True), | Layer 1 turns each word number into a list of 16 numbers that the network learns; words used in similar ways end up with similar lists. mask_zero=True tells the next layer to skip the blanks. |
tf.keras.layers.LSTM(16), | Layer 2 is Priya’s notebook: it reads the words one by one, keeps a ledger of 16 numbers, and passes on its final daily note. |
tf.keras.layers.Dense(1, activation='sigmoid')]) | Layer 3 turns that note into one number between 0 and 1: the network’s probability that the review is positive. |
model.compile('adam', 'binary_crossentropy', metrics=['accuracy']) | Choose how it learns: adam is the method that adjusts the weights, binary cross-entropy measures how wrong a yes/no guess is, and we also keep track of accuracy. |
model.fit(X_train, y_train, epochs=15, batch_size=32, verbose=0) | Train: go through the 800 study reviews 15 times, adjusting the weights after every 32 reviews, quietly (verbose=0). The number 15 was fixed in advance, not chosen by peeking at the test scores. |
y_pred = (model.predict(X_test, verbose=0) > 0.5).astype(int).ravel() | Ask for a probability for each test review. Above 0.5 counts as “liked” (1), otherwise “not liked” (0). ravel turns the result into a simple list. |
print((y_pred == y_test).mean()) | Print the share of test reviews it got right. 0.775 means 155 of the 200. |
print(confusion_matrix(y_test, y_pred)) | Print a 2×2 count. Top row, the real negative reviews: 84 correctly called negative, 13 wrongly called positive. Bottom row, the real positive reviews: 32 missed, 71 correctly called positive. |
probs = model.predict(X_test, verbose=0).ravel() | Get the network’s probability of “positive” for every test review. |
right = np.where(y_pred == y_test)[0][:3] | Find the first three test reviews it got right… |
wrong = np.where(y_pred != y_test)[0][:3] | … and the first three it got wrong. |
for i in np.concatenate([right, wrong]): | Go through those six reviews: |
r = test_idx[i] | … find the review’s row in the original file; |
print(f"{probs[i]:.2f} said {y_pred[i]} truth {y_test[i]} | {ds['Review'][r][:60]}") | … print its probability, the network’s answer, the true answer, and the first 60 characters of the review. |
def encode(text): | Define a helper that prepares any new sentence exactly as the training reviews were prepared: |
idx = [vocab.get(w, 1) for w in re.sub('[^a-z ]', ' ', text.lower()).split()[:MAXLEN]] | … clean it, split it into words, and look each word up in the same dictionary (unknown words become 1); |
return np.array([idx + [0] * (MAXLEN - len(idx))], dtype='int32') | … fill it up to 20 positions with blanks (0) and shape it as one review. |
for text in ['the food was good', 'the food was not good', 'not bad at all']: | Try three sentences the network has never seen… |
print(f"{model.predict(encode(text), verbose=0)[0, 0]:.2f} {text}") | … and print its probability that each one is positive. |
Second, the finance race: Chapter 26 §8’s setup, upgraded to sequences and to a one-week target:
# ---- Listing 29.2: next-WEEK return, LSTM vs Dense vs two naive baselines ----
import numpy as np, pandas as pd, tensorflow as tf
tf.keras.utils.set_random_seed(0)
tf.config.experimental.enable_op_determinism()
px = pd.read_csv('data/equity_research_prices_8tickers.csv', parse_dates=['Date'])
aapl = px[px.Ticker == 'AAPL'].sort_values('Date')
close = aapl['Close'].values # 1,695 daily closes, Jan 2020 - Sep 2026
dates = aapl['Date'].dt.date.values
r = np.diff(np.log(close)) # daily log returns
window, FWD = 10, 5 # last 10 days in, next 5 days' total out
X = np.array([r[t-window:t] for t in range(window, len(r)-FWD)])
y = np.array([r[t:t+FWD].sum() for t in range(window, len(r)-FWD)])
t_of = np.arange(window, len(r)-FWD) # the day each question is asked on
cut = int(0.8 * len(y)) # TIME split - never shuffle
X_train, y_train = X[:cut], y[:cut]
X_test, y_test = X[cut+FWD:], y[cut+FWD:] # 5-day gap: no target overlaps the test inputs
mu, sd = X_train.mean(), X_train.std() # scale inputs on TRAIN statistics only
X_train, X_test = (X_train - mu) / sd, (X_test - mu) / sd
ym, ys = y_train.mean(), y_train.std() # scale the target the same way
lstm = tf.keras.Sequential([tf.keras.Input(shape=(window, 1)),
tf.keras.layers.LSTM(16), tf.keras.layers.Dense(1)])
lstm.compile('adam', 'mean_squared_error')
lstm.fit(X_train[..., None], (y_train - ym) / ys, epochs=60, batch_size=32, verbose=0)
p_lstm = lstm.predict(X_test[..., None], verbose=0).ravel() * ys + ym
tf.keras.utils.set_random_seed(0)
dense = tf.keras.Sequential([tf.keras.Input(shape=(window,)),
tf.keras.layers.Dense(16, activation='relu'),
tf.keras.layers.Dense(8, activation='relu'), tf.keras.layers.Dense(1)])
dense.compile('adam', 'mean_squared_error')
dense.fit(X_train, (y_train - ym) / ys, epochs=60, batch_size=32, verbose=0)
p_dense = dense.predict(X_test, verbose=0).ravel() * ys + ym
def report(name, p):
mae = np.abs(p - y_test).mean()
direction = ((p > 0) == (y_test > 0)).mean()
r2 = 1 - ((y_test - p)**2).sum() / ((y_test - y_test.mean())**2).sum()
print(f'{name:12s} MAE {mae:.5f} direction {direction:.3f} R2 {r2:+.3f}')
report('LSTM', p_lstm)
report('Dense 16-8', p_dense)
report('naive: 0', np.zeros_like(y_test)) # "no change" (direction = share of up weeks)
report('naive: mean', np.full_like(y_test, ym)) # "an average week", from training data
print('corr LSTM', np.corrcoef(p_lstm, y_test)[0, 1].round(3), '| train/test', len(y_train), len(y_test))
# ---- look at the predictions themselves ----
t_test = t_of[cut+FWD:] # the day each test forecast was made
made_on, ends_on = dates[t_test], dates[t_test + FWD]
show = pd.DataFrame({
'forecast made': made_on, 'for close on': ends_on,
'price then': close[t_test].round(2),
'predicted %': (100 * p_lstm).round(2),
'actual %': (100 * y_test).round(2),
'predicted price': (close[t_test] * np.exp(p_lstm)).round(2),
'actual price': close[t_test + FWD].round(2)})
show['direction right?'] = np.where((p_lstm > 0) == (y_test > 0), 'yes', 'no')
print(show.tail(5).to_string(index=False))
print(pd.crosstab(np.where(y_test > 0, 'actual up', 'actual down'),
np.where(p_lstm > 0, 'LSTM said up', 'LSTM said down'),
rownames=[''], colnames=['']))
print(f'forecasts move about +/-{100*p_lstm.std():.2f}% ; real weeks move about +/-{100*y_test.std():.2f}%')
# ---- one live forecast from the latest 10 days in the file ----
x_now = ((r[-window:] - mu) / sd).reshape(1, window, 1)
p_now = lstm.predict(x_now, verbose=0).ravel()[0] * ys + ym
print(f'Forecast made on {dates[-1]}: next 5 trading days {100*p_now:+.2f}% '
f'-> price {close[-1]:.2f} to about {close[-1]*np.exp(p_now):.2f}')
Listing 29.2 — Sequence regression: the last ten daily returns predict next week’s total return. Time split with a 5-day gap, inputs and target scaled on training data only, two models and two naive baselines scored the same way, then the predictions themselves: the last five test weeks, an up/down scorecard, and one live forecast from the latest data. Results discussed in Section 9.
What Listing 29.2 prints (our run, seed 0, TF 2.21):
LSTM MAE 0.02864 direction 0.538 R2 -0.082
Dense 16-8 MAE 0.02907 direction 0.492 R2 -0.062
naive: 0 MAE 0.02855 direction 0.414 R2 -0.047
naive: mean MAE 0.02810 direction 0.586 R2 -0.014
corr LSTM -0.059 | train/test 1343 331
forecast made for close on price then predicted % actual % predicted price actual price direction right?
2026-09-16 2026-09-23 332.41 0.92 1.38 335.50 337.02 yes
2026-09-17 2026-09-24 337.00 0.99 -0.32 340.34 335.92 no
2026-09-18 2026-09-25 336.13 0.95 1.46 339.36 341.07 yes
2026-09-21 2026-09-28 338.98 0.56 -0.17 340.87 338.40 no
2026-09-22 2026-09-29 339.75 0.26 -3.09 340.63 329.40 no
LSTM said down LSTM said up
actual down 48 89
actual up 64 130
forecasts move about +/-0.70% ; real weeks move about +/-3.58%
Forecast made on 2026-09-30: next 5 trading days -0.33% -> price 333.02 to about 331.92
Reading the result of Listing 29.2
| What is printed | What it tells us |
|---|---|
LSTM MAE 0.02864 direction 0.538 R2 -0.082 |
On average, the LSTM’s forecast of next week’s return missed by 2.86 percentage points. It called the direction (up or down) right in 53.8% of the 331 test weeks. R² below zero means its forecasts were further from the truth than simply using the test period’s average. |
Dense 16-8 MAE 0.02907 direction 0.492 R2 -0.062 |
The plain network, which ignores order, missed slightly more (2.91 points) and called the direction right only 49.2% of the time: worse than tossing a coin. |
naive: 0 MAE 0.02855 ... |
Saying “no change” every week missed by 2.86 points: no worse than the LSTM. (Its “direction” of 0.414 is not a real score; a forecast of zero is counted as “down”, so it is just the share of weeks that fell.) |
naive: mean MAE 0.02810 direction 0.586 R2 -0.014 |
The best line on the page. Forecasting an average week (a small rise) every time beats both networks on all three measures: the smallest miss, the best direction score, the best R². |
corr LSTM -0.059 | train/test 1343 331 |
The LSTM’s forecasts are essentially unrelated to what happened (a correlation of −0.06, where 0 means no relation). It learned from 1,343 weeks and was tested on 331. |
| The five-row table | The predictions themselves. Take the last row: on 22 September 2026 the share stood at $339.75; the LSTM forecast +0.26%, a price of $340.63 a week later; the share actually fell 3.09% to $329.40. Every forecast in the table is a small rise (+0.26% to +0.99%), while the real moves are bigger and go both ways. Direction: 2 right, 3 wrong. |
| The up/down scorecard | The “accuracy” table. Correct calls are on the diagonal: 48 + 130 = 178 of 331 weeks, the 53.8% above. The LSTM said “up” 219 times and “down” 112 times. AAPL actually rose in 194 weeks (58.6%), so someone who always says “up” scores better than the LSTM. |
forecasts move about +/-0.70% ; real weeks move about +/-3.58% |
The forecasts are timid: they move only a fifth as much as the real weeks. With so little information in the past ten days, the safest thing a squared-error model can do is stay close to the average. |
Forecast made on 2026-09-30: next 5 trading days -0.33% -> price 333.02 to about 331.92 |
A live forecast from the latest data in the file: a small fall of 0.33%, from $333.02 to about $331.92. After the scores above, this is a demonstration of how to produce a forecast, not a view worth trading on. |
Bottom line. The code works and produces real forecasts, prices and an accuracy score, but the forecasts carry no usable edge: the laziest forecaster on the page wins. Section 9 shows all 331 forecasts against reality in one chart and explains why this is the expected result for public price data.
Listing 29.2, 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.
| Code | What it does, in plain English |
|---|---|
import numpy as np, pandas as pd, tensorflow as tf | Load the toolboxes for numbers, tables and the network. |
tf.keras.utils.set_random_seed(0)
tf.config.experimental.enable_op_determinism() | Fix the “dice” and the order of the sums, so the results repeat on the same machine (as in Listing 29.1). |
px = pd.read_csv('data/equity_research_prices_8tickers.csv', parse_dates=['Date']) | Open the course’s price file (daily prices for eight companies) and read the Date column as real dates. |
aapl = px[px.Ticker == 'AAPL'].sort_values('Date') | Keep only Apple’s rows and put them in date order. |
close = aapl['Close'].values | Take the closing price of each day: 1,695 days from January 2020 to September 2026. |
dates = aapl['Date'].dt.date.values | Keep the matching calendar dates, so every forecast can be labelled with the day it was made. |
r = np.diff(np.log(close)) | Turn prices into daily returns: the change from one day to the next, measured in a way (log returns) that is very close to the percentage change. |
window, FWD = 10, 5 | Look back 10 trading days; predict the total move over the next 5 trading days (one week). |
X = np.array([r[t-window:t] for t in range(window, len(r)-FWD)]) | Build the questions. For each day t, take the 10 returns just before it. Each row is one question: “given these 10 days…”. |
y = np.array([r[t:t+FWD].sum() for t in range(window, len(r)-FWD)]) | Build the answers: for the same day t, add up the next 5 daily returns, which gives next week’s return. |
t_of = np.arange(window, len(r)-FWD) | Remember, for each question, which day it was asked on. We need this later to print dates and prices next to the forecasts. |
cut = int(0.8 * len(y)) | Find the point where the first 80% of the time period ends. |
X_train, y_train = X[:cut], y[:cut] | Everything before that point is the study period. |
X_test, y_test = X[cut+FWD:], y[cut+FWD:] | The test period starts 5 days later, leaving a gap, so no answer from the study period overlaps a test question. Testing only on later dates mirrors real life: you never get tomorrow’s newspaper. |
mu, sd = X_train.mean(), X_train.std() | Measure the average return and the typical size of a return, using the study period only. |
X_train, X_test = (X_train - mu) / sd, (X_test - mu) / sd | Rescale the returns so a typical one is about ±1; networks learn better with numbers of that size. The test data is rescaled with the study-period numbers, so nothing from the test period is used. |
ym, ys = y_train.mean(), y_train.std() | Do the same measurement for the answers (next week’s returns). |
lstm = tf.keras.Sequential([tf.keras.Input(shape=(window, 1)),
tf.keras.layers.LSTM(16), tf.keras.layers.Dense(1)]) | Build the LSTM model. Each question is 10 days with 1 number per day; the LSTM notebook keeps a 16-number ledger; one final unit gives one number. There is no sigmoid at the end, because a return can be any number, not just 0–1. |
lstm.compile('adam', 'mean_squared_error') | Learn with adam, and measure error as the average of the squared misses. |
lstm.fit(X_train[..., None], (y_train - ym) / ys, epochs=60, batch_size=32, verbose=0) | Train for 60 passes on the study weeks, with the answers rescaled too. [..., None] adds the “1 number per day” dimension that an LSTM expects. |
p_lstm = lstm.predict(X_test[..., None], verbose=0).ravel() * ys + ym | Forecast every test week, then undo the rescaling so the forecasts are real returns again. |
tf.keras.utils.set_random_seed(0) | Reset the dice, so the second model starts on equal terms. |
dense = tf.keras.Sequential([tf.keras.Input(shape=(window,)),
tf.keras.layers.Dense(16, activation='relu'),
tf.keras.layers.Dense(8, activation='relu'), tf.keras.layers.Dense(1)]) | Build the comparison model: a plain network from Chapter 26. It sees the 10 days as 10 separate columns, with no sense of which came first. |
dense.compile(...); dense.fit(...); p_dense = dense.predict(...) | Train and forecast with the plain network in exactly the same way as the LSTM. |
def report(name, p): | Define a small routine that scores any set of forecasts in the same three ways, so the comparison is fair. |
mae = np.abs(p - y_test).mean() | MAE: the average size of the miss, ignoring whether it was too high or too low. Smaller is better. |
direction = ((p > 0) == (y_test > 0)).mean() | Direction: the share of weeks where the forecast called “up” or “down” correctly. |
r2 = 1 - ((y_test - p)**2).sum() / ((y_test - y_test.mean())**2).sum() | R²: how much better the forecast is than simply guessing the test period’s own average. 0 means no better; below 0 means worse. |
print(f'{name:12s} MAE {mae:.5f} direction {direction:.3f} R2 {r2:+.3f}') | Print one tidy line with the three scores. |
report('LSTM', p_lstm)
report('Dense 16-8', p_dense) | Score the two networks. |
report('naive: 0', np.zeros_like(y_test)) | Score the lazy forecaster who always says “no change” (a return of 0). |
report('naive: mean', np.full_like(y_test, ym)) | Score the lazy forecaster who always says “an average week” (the study-period average, which happens to be slightly positive, so it always says “up”). |
print('corr LSTM', np.corrcoef(p_lstm, y_test)[0, 1].round(3), '| train/test', len(y_train), len(y_test)) | Print the correlation between the LSTM’s forecasts and what really happened (from −1 to +1; 0 means no relation), and how many study and test weeks were used. |
t_test = t_of[cut+FWD:] | The days on which the test forecasts were made. |
made_on, ends_on = dates[t_test], dates[t_test + FWD] | For each test forecast: the date it was made, and the date five trading days later that it is about. |
show = pd.DataFrame({...}) | Build a readable table, one row per test week: the price on the day of the forecast, the predicted and actual return in %, and the predicted and actual price a week later. A predicted price is today’s price grown by the predicted return (close × exp(prediction)). |
show['direction right?'] = np.where((p_lstm > 0) == (y_test > 0), 'yes', 'no') | Add a column that says whether the forecast got the direction (up or down) right. |
print(show.tail(5).to_string(index=False)) | Print the last five test weeks of that table. |
print(pd.crosstab(..., rownames=[''], colnames=[''])) | Print a 2×2 up/down scorecard: how often the LSTM said “up” or “down”, against what really happened. The two diagonal cells are the correct calls. |
print(f'forecasts move about +/-...% ; real weeks move about +/-...%') | Compare how much the forecasts move with how much real weeks move (the standard deviation of each, in %). |
x_now = ((r[-window:] - mu) / sd).reshape(1, window, 1) | Take the latest 10 daily returns in the file (up to 30 September 2026), rescale them with the study-period numbers, and shape them as one question. |
p_now = lstm.predict(x_now, verbose=0).ravel()[0] * ys + ym | Ask the trained LSTM for its forecast of the next five trading days, and undo the rescaling. |
print(f'Forecast made on {dates[-1]}: next 5 trading days ... -> price ... to about ...') | Print that live forecast as a return and as a price: the last close, and where the forecast says it will be a week later. |
mask_zero=True on the Embedding tells the LSTM to skip
them. That is also why unknown words get their own index (1): if they
were mapped to 0, the mask would silently delete them from the
review, and rare words are often the opinion words.
8. Application: Reviews, with Order
Put Priya’s clever notebook up against a clerk who simply counts words, on 1,000 short restaurant reviews. They score about the same. With so few examples, the notebook does not have enough practice to beat a simple count, and the clerk can be taught a cheap trick of his own: count two-word phrases such as “not good” as one item. The lesson: a clever method needs plenty of examples before it pulls ahead.
Chapter 25’s bag of words scored 73% on these 1,000 reviews and its best linear rival 78%. The open question was whether order (“not good” versus “good”) is worth the machinery. Same 800/200 split, all numbers from our runs:
| Model | Accuracy | Confusion matrix |
|---|---|---|
| Naive Bayes on the bag (Ch 25) | 0.730 | [[55, 42], [12, 91]] |
| Logistic on the bag (Ch 25) | 0.775 | [[80, 17], [28, 75]] |
| LinearSVC on the bag (Ch 25) | 0.780 | [[80, 17], [27, 76]] |
| LSTM on the sequence (Listing 29.1, seed 0) | 0.775 | [[84, 13], [32, 71]] |
| LSTM, five seeds (0–4) | 0.775–0.800, mean 0.791 | — |
| Logistic on a bag with bigrams | 0.790 | [[81, 16], [26, 77]] |
| LinearSVC on a bag with bigrams | 0.760 | [[80, 17], [31, 72]] |
Read it honestly, both directions. The LSTM lands in the same band as the linear models (0.775–0.80 against 0.775–0.79), and clearly above Naive Bayes, without any hand-built counting: pure order and a learned embedding. It does not dethrone the bag. On a 200-review test set one review is half a point and the standard error is about 3 points, so everything from 0.76 to 0.80 is one tie; the five LSTM seeds alone span 2.5 points. Even the bigram trick is not a sure win: it lifts logistic regression to 0.790 but drops LinearSVC to 0.760. With 800 training reviews and a 1,500-word vocabulary, a 16-unit cell is data-starved; recurrence’s appetite for data is its known cost.
9. Application: Next Week’s Return
Priya uses her notebook to forecast next week’s move in a real share price. Her lazy colleague simply says “next week will be an average week” every time. Over the test period the lazy colleague wins.
Look at what Priya actually writes down: almost every week she says “a little up, under 1%”, while the real share moves 3–4% up or down. She gets the direction right a little more than half the time, but the lazy colleague, who always says “up”, gets it right more often. When the news is mostly noise, a careful forecaster learns to say very little.
This is not because the notebook is bad. Public price history is read by thousands of professionals, so most of what it can tell you is already in the price. There is a second lesson: an earlier version of this experiment, which fed in the raw returns without scaling them, seemed to show Priya had a small edge. After one ordinary preparation step (scaling the inputs, as Chapter 26 does), the edge disappeared. A result that vanishes when a routine step changes was never a real edge.
The finance desk’s question, posed to the belt: the last ten daily returns on AAPL (Jan 2020 – Sep 2026, 1,679 windows), predict next week’s total return. Time split with a 5-day gap: 1,343 training windows, 331 test windows. One deterministic run of Listing 29.2:
| Model | MAE | Direction | R² |
|---|---|---|---|
| LSTM(16) on the window | 0.02864 | 0.538 | −0.082 |
| Dense(16-8) on the flattened window | 0.02907 | 0.492 | −0.062 |
| Naive: predict 0 (“no change”) | 0.02855 | (0.414) | −0.047 |
| Naive: predict the training mean | 0.02810 | 0.586 (always “up”) | −0.014 |
9.1 The predictions themselves
Scores hide what a model actually says, so Listing 29.2 also prints its forecasts. Here are the last five test weeks, exactly as printed (returns in %, prices in US dollars):
| Forecast made | For the close on | Price then | Predicted | Actual | Predicted price | Actual price | Direction right? |
|---|---|---|---|---|---|---|---|
| 16 Sep 2026 | 23 Sep | 332.41 | +0.92% | +1.38% | 335.50 | 337.02 | yes |
| 17 Sep 2026 | 24 Sep | 337.00 | +0.99% | −0.32% | 340.34 | 335.92 | no |
| 18 Sep 2026 | 25 Sep | 336.13 | +0.95% | +1.46% | 339.36 | 341.07 | yes |
| 21 Sep 2026 | 28 Sep | 338.98 | +0.56% | −0.17% | 340.87 | 338.40 | no |
| 22 Sep 2026 | 29 Sep | 339.75 | +0.26% | −3.09% | 340.63 | 329.40 | no |
Read one row slowly. On 22 September the share closed at $339.75. The LSTM, looking at the previous ten days, forecast a small rise of 0.26% for the following week, which means a price of about $340.63 on 29 September. The share actually fell 3.09% to $329.40. Wrong direction, and a miss of about $11. Every row has the same feature: the forecasts are small, mostly “a little up”, while the real moves are larger and go either way.
The figure shows the whole test period at once. The forecast line is almost flat. That is not a bug; it is what a careful model does when the inputs carry very little information about the target: minimising squared error, its safest bet is to stay close to the average week and move only a little. A forecast that moves ±0.7% cannot follow a market that moves ±3.6%.
9.2 Accuracy: the up/down scorecard
For a price forecast, “accuracy” usually means calling the direction right. The scorecard counts all 331 test weeks:
| LSTM said down | LSTM said up | Total | |
|---|---|---|---|
| Actual down | 48 (right) | 89 (wrong) | 137 |
| Actual up | 64 (wrong) | 130 (right) | 194 |
| Total | 112 | 219 | 331 |
The LSTM called the direction right in 48 + 130 = 178 of 331 weeks: 53.8%. That sounds better than a coin toss, but the right comparison is not a coin. AAPL rose in 194 of the 331 weeks (58.6%), so a forecaster who simply says “up” every week scores 58.6%, higher than the LSTM. Look at the two columns separately: when the LSTM said “up” it was right 130 times out of 219 (59%), which is just the up-rate; when it said “down” it was right only 48 times out of 112 (43%), worse than ignoring it. Its “down” calls are where it loses.
9.3 One live forecast
Finally, the listing uses the latest ten days in the file to forecast the week after it ends:
9.4 What it all means
The by-now-familiar shape. The best row is the laziest: predicting an average training week beats both networks on every measure. Two notes on reading the table. R² here compares each forecast with the test mean, which no forecaster knows in advance, so even the naive rows score below zero; what matters is the ranking. And the “predict 0” row’s direction (0.414) is shown in brackets because it is not a real score: a forecast of exactly zero never says up or down, and the code simply counts it as “down”, so 0.414 is just the share of weeks that fell.
A cautionary tale about fragile results. An earlier version of this listing fed the raw (unscaled) returns, with no gap between training and test. That run showed a correlation of about +0.12 between the LSTM’s forecasts and the real weekly returns, and the same across five seeds (+0.12 to +0.14). It looked like a whisper of signal. We then changed one thing at a time. Adding the gap alone left it at +0.12; scaling the inputs alone removed it. With both in place, the correlation over five seeds is −0.06 to +0.06: nothing. Scaling is routine practice (Chapter 26 does it), so the “whisper” was an artefact of one preparation choice, not a property of the market. Even the earlier +0.12 would not have been convincing. The 5-day targets overlap (each week shares four days with the next), so the 336 test points behave like about 67 independent ones, and a correlation of 0.12 is well within what chance produces at that size. Memory for order does not exempt sequences from market efficiency: the same wall met in Mini-Project 1, Applied Project 1 and Chapter 26 §8, now from the belt’s direction.
10. The Seq2Seq Payoff
Priya’s firm needs English research reports in Hindi. One analyst reads the whole English report and fills in a single summary card. A second analyst, who never sees the report, writes the Hindi version word by word from that card alone, looking at each word she has just written to choose the next.
This works for short reports. For long ones, one card is not enough room, and details get lost. The fix was to let the writer look back at the original pages while writing (that is attention). Later, teams dropped the card-passing altogether and let everyone look at every page at once (the transformer).
Chapter 25’s map put sequence-to-sequence at the innermost ring and
deferred it. Every component now exists. An encoder LSTM
reads the input sequence and ends with its final state (c, h), obtained
with return_state=True: a thought compressed into vectors. A
decoder LSTM starts from that state and generates the
output sequence one token at a time. At inference time it feeds each of
its own predictions back in as the next input. During training it is
usually fed the correct previous token instead, a habit called
teacher forcing, which makes training
faster and more stable. Read a sentence, write a sentence:
The design’s strength and its flaw are the same arrow. The whole input sentence must fit in the fixed-size (c, h): a bottleneck that bends on long inputs. The fix, letting the decoder look back at every encoder state and weight them by relevance, is attention (Bahdanau, Cho and Bengio, 2014). The 2017 paper “Attention Is All You Need” went further and removed recurrence entirely. The transformer, today’s default, is that step, and it is deliberately the door this course leaves ajar rather than opens, having shown you everything it replaced.
11. The Road Ahead
Today the strongest language tools work like an analyst who can reread the whole archive at once (transformers). But the notebook method is still the right tool when data arrives one tick at a time and must be handled immediately with little computing power: a sensor on a machine, a live trading feed, a small device with no room for a giant model.
Where gated recurrence stands now, honestly:
- Transformers dominate at scale. Most of the headline language models read whole sequences at once with self-attention: no belt, no steps, far more parallel, scaling where LSTMs could not.
- LSTMs did not die; they specialised. Streaming and low-latency settings (a device that must react to each sensor tick as it arrives), modest-data time series, embedded and edge deployment: any workload where data arrives one step at a time and cannot be re-read.
- Recurrence is back in research. State-space models (such as Mamba) and RWKV revive the idea of a fixed-size running state with transformer-like training speed. This is the sentence most likely to need changing at the next quarterly review.
- The concepts transfer wholesale. Gates, states, embeddings, masking, windowing, teacher forcing, the leakage rules of Sections 6 and 9: all of it reappears inside modern stacks. Learning it here was not a detour; it was the vocabulary.
And with that, Part VIII is complete: dense networks that read tables, convolutions that read pictures, recurrences that read time. Part IX turns to the opposite question: not what more a network can see, but which directions of a dataset can be dropped without losing what matters.
🛠 Hands-On: Gates, Laws, and One Honest RaceIntermediate
Work the belt with your own hands: verify the cell, prove the parameter law against Keras, then rerun the reviews experiment and push it one honest step further.
Steps
- Verify Section 3’s hand cell with three lines of numpy (
sigmoid,tanh). Then change bf from 1 to 4 and recompute: how much more of the 0.5 on the belt survives? - Prove the parameter law: build SimpleRNN(16), GRU(16), LSTM(16) over m = 5 inputs and confirm 352 / 1,104 / 1,408 with
count_params(). Then predict GRU’s count for n = 32, m = 8 and check it. - Rerun Listing 29.1 and reproduce 0.775 and [[84, 13], [32, 71]] (same machine and version). Then run seeds 1–4 and report the spread.
- Swap
LSTM(16)forGRU(16)and forBidirectional(LSTM(16)). Two more real numbers, and one sentence on why the bidirectional model is legitimate here (offline text) while the same swap in Listing 29.2 would be cheating. - Chapter 25’s cheapest order trick was bigrams. Add
ngram_range=(1, 2)to the bag (keepmax_features=1500) and score logistic regression and LinearSVC. Put the results beside the LSTM’s. Which bought more accuracy per line of code, and is any difference bigger than the noise? - Measure the carry of an LSTM yourself (Section 4’s table) with the script in the solution, at forget-gate biases 0, 1 and 4.
- No code. Explain to a friend who has never seen a formula, using Priya’s ledger, why the LSTM can remember a headline from six weeks ago when the Chapter 28 network could not. Three sentences.
View Solution / Walkthrough
Step 1. With bf = 4: f = σ(4) = 0.9820, so the belt keeps 0.9820·0.5 = 0.4910 of its past (versus 0.3655), and ct rises to 0.4910 + 0.5568 = 1.0478. The belt now keeps 98% of its past instead of 73%: the dial turned by hand. Note that c has gone above 1; the belt is not squashed.
Step 2. GRU at n = 32, m = 8: 3(nm + n² + 2n) = 3(256 + 1024 + 64) = 4,032. Keras agrees.
Step 3. Our five seeds (0–4): 0.775, 0.790, 0.790, 0.800, 0.800, mean 0.791. One seed is not a result; the spread is part of the answer.
Step 4. Our runs (seed 0): GRU 0.800, Bidirectional LSTM 0.805. Both sit inside the LSTM’s own seed spread, so neither is a clear improvement. The bidirectional model reads the review’s end before classifying its start; offline, the whole review is on the desk, so that is simply more information, not leakage. In Listing 29.2 the “end of the sequence” is next week; reading it to predict this week is the future-peek this course has refused since Chapter 3.
Step 5. Our runs: logistic with bigrams 0.790 (up from 0.775), LinearSVC with bigrams 0.760 (down from 0.780). Bigrams help one model and hurt the other, and every number from 0.76 to 0.80 is within the 3-point noise of a 200-review test. The honest answer: on 800 reviews, neither engineered order (bigrams) nor learned order (the LSTM) clearly beats the plain bag.
Step 6. The script (16 units, 5 inputs, Keras-style initial weights, numerical Jacobian of the full state):
import numpy as np
sg = lambda z: 1 / (1 + np.exp(-z))
def lstm_carry(fb, n=16, m=5, T=40, seed=0):
rng = np.random.default_rng(seed)
lim = np.sqrt(6 / (m + 4*n)); W = rng.uniform(-lim, lim, (m, 4*n)) # Glorot input weights
U = np.concatenate([np.linalg.qr(rng.normal(size=(n, n)))[0] for _ in range(4)], axis=1) # orthogonal
b = np.zeros(4*n); b[n:2*n] = fb # forget-gate bias
xs = rng.uniform(-1, 1, (T, m))
def step(s, x):
h, c = s[:n], s[n:]
z = x @ W + h @ U + b
i, f, g, o = sg(z[:n]), sg(z[n:2*n]), np.tanh(z[2*n:3*n]), sg(z[3*n:])
c2 = f*c + i*g
return np.concatenate([o*np.tanh(c2), c2])
s = np.zeros(2*n); P = np.eye(2*n); eps = 1e-6
for t in range(T):
base = step(s, xs[t])
J = np.column_stack([(step(s + eps*np.eye(2*n)[k], xs[t]) - base) / eps for k in range(2*n)])
P, s = J @ P, base
return np.linalg.norm(P)
for fb in (0, 1, 4):
c = np.array([lstm_carry(fb, seed=s) for s in range(10)])
print(fb, f"geometric mean {np.exp(np.log(c).mean()):.1e}") # about 5e-6, 0.16, 50
The Step 6 script, line by line
| Code | What it does, in plain English |
|---|---|
import numpy as np
sg = lambda z: 1 / (1 + np.exp(-z)) | Load numpy and write the sigmoid, the function that squeezes any number into the range 0 to 1 (the shape of every gate). |
def lstm_carry(fb, n=16, m=5, T=40, seed=0): | Define one experiment: an LSTM with forget-gate bias fb, 16 units, 5 inputs, run for 40 steps. |
rng = np.random.default_rng(seed) | Create a random-number generator with a fixed seed, so the experiment can be repeated. |
lim = np.sqrt(6 / (m + 4*n)); W = rng.uniform(-lim, lim, (m, 4*n)) | Random input weights for all four parts (forget, input, candidate, output) at once, sized the way Keras starts them (“Glorot”). |
U = np.concatenate([np.linalg.qr(rng.normal(size=(n, n)))[0] for _ in range(4)], axis=1) | Random recurrent weights, one 16×16 block per part. Each block is “orthogonal”: on its own it neither stretches nor shrinks the state, again like Keras. |
b = np.zeros(4*n); b[n:2*n] = fb | All biases start at 0, except the forget gate’s, which is set to fb (0, 1 or 4). |
xs = rng.uniform(-1, 1, (T, m)) | Make 40 days of random inputs, 5 numbers per day. |
def step(s, x): ... | One morning of Priya’s notebook: split the state into the note h and the ledger c; compute the four parts; update the ledger (c = f·c + i·g); write the new note (h = o·tanh(c)). |
s = np.zeros(2*n); P = np.eye(2*n); eps = 1e-6 | Start with a blank note and ledger. P records “how much does today depend on day 0”, starting as “unchanged”. eps is a tiny nudge used to measure slopes. |
for t in range(T): | Repeat for each of the 40 days: |
base = step(s, xs[t]) | … run the normal step; |
J = np.column_stack([(step(s + eps*np.eye(2*n)[k], xs[t]) - base) / eps for k in range(2*n)]) | … nudge each of the 32 state numbers in turn by a tiny amount and see how the next state moves. That gives today’s table of sensitivities; |
P, s = J @ P, base | … chain today’s sensitivities onto all the earlier days, and move the state forward. |
return np.linalg.norm(P) | Shrink the final table of sensitivities to one number: how strongly day 40 still reacts to day 0. |
for fb in (0, 1, 4):
c = np.array([lstm_carry(fb, seed=s) for s in range(10)])
print(fb, ...) | Run the experiment for each forget bias, ten times with different random starts, and print the typical (geometric-mean) result: about 0.000005, 0.16 and 50. |
Step 7. A possible answer: “The old network rewrote its single note every day and kept only part of yesterday, so a six-week-old headline had faded to almost nothing. The LSTM keeps a ledger that is never rewritten automatically; an entry shrinks only when the network decides to cross some of it out. For an important story it learns to keep almost everything each day, so the headline is still there six weeks later.”
🎯 Key Takeaways
The cell state is a conveyor belt: ct = f⊙ct−1 + i⊙g. No matrix touches the past; the gradient rides the belt instead of dying in tanh chains, and the forget gate is a learnable dial.
By hand: f = i = σ(1) = 0.7311, g = tanh(1) = 0.7616, o = σ(0.2) = 0.5498 → c = 0.9223, h = 0.3997. The cell remembers more than it says.
The price is exact: LSTM = 4(nm + n² + n), 1,408 versus the plain RNN’s 352, verified against Keras. GRU’s 1,104 sits between.
On 800 reviews the LSTM scored 0.775–0.800 over five seeds: level with the linear bag models, above Naive Bayes. Order helps; data scale decides how much.
Next week’s AAPL: an average training week beats both networks, and an apparent +0.12 correlation vanished once the inputs were scaled. Seq2seq pays Chapter 25’s map; transformers replace the belt where scale matters.
Priya swapped her sticky note for a two-part notebook: a ledger she never rewrites automatically, and a short daily note. Each morning she decides how much of the ledger to keep, what today’s news says, how much of it to add, and how much to tell her manager. Because old ledger entries fade only when she chooses, important news can survive for weeks, and the lessons from her mistakes can reach back that far too. That notebook is the LSTM. It is a better tool, but on small datasets it only ties simple methods, and on public share prices it cannot beat a lazy “average week” forecast.
Test Your Understanding
30 questions from the whole chapter: Priya’s notebook, the belt and the gates, the hand-worked cell, the measured carry, the parameter law, Keras habits, both applications, and the road to transformers. Choose one answer per question, then check your answers.
Q1.In Priya’s two-part notebook, the ledger corresponds to:
Q2.At each step, the cell state can be changed only by:
Q3.The belt’s update rule is:
Q4.Which part reads the belt without changing it?
Q5.A gate’s output lies in:
Q6.The candidate g is best described as:
Q7.The forget gate was added to the LSTM by:
Q8.(Hand) Forget-gate weights zero, bias 1. Then f equals:
Q9.(Hand) ct−1 = 0.5, f = i = 0.7311, g = 0.7616. Then ct is:
Q10.(Hand) ht = 0.5498 · tanh(0.9223) equals:
Q11.(Hand) Raising the forget bias from 1 to 4, the belt keeps of its 0.5:
Q12.Along the belt alone, the carry from step s to step T is:
Q13.(Real) Measured LSTM carry at T = 40 with Keras’s default bias:
Q14.At forget bias 4 the measured carry grew to about 50. This shows:
Q15.The LSTM parameter count for n units and m inputs is:
Q16.(Real) Keras counts at n = 16, m = 5 for SimpleRNN / GRU / LSTM:
Q17.In Keras, the GRU’s extra n parameters per block come from:
Q18.The GRU simplifies the LSTM by:
Q19.A bidirectional LSTM suits reviews but not forecasting because:
Q20.Bidirectional(LSTM(16)) outputs:
Q21.In Listing 29.1, unknown words get index 1 rather than 0 because:
Q22.Listing 29.1 builds its vocabulary from training reviews only to:
Q23.(Real) Over five seeds, the LSTM on the reviews scored:
Q24.(Real) Adding bigrams to the bag of words:
Q25.(Real) The best row of the AAPL next-week race was:
Q26.The earlier +0.12 correlation disappeared when:
Q27.Even +0.12 was weak evidence, because overlapping weeks:
Q28.Teacher forcing means:
Q29.The seq2seq bottleneck that attention removed was:
Q30.Where gated recurrence still fits best today: