Backpropagation and Neural Networks

A network decides whether Paris is a place by reading five words at once. Backpropagation turns each mistake into a gradient for all 48 weights and for the word vectors themselves. After 300 steps, Paris in “museums in Paris” scores 0.99 and Paris in “Paris Hilton” scores 0.01.

Press Train. Watch the bars over the two Paris chips split apart, and the purple word vectors drift on the map. Then turn off word-vector updates and train again. After that we build the tagger piece by piece: the window, the layer, the loss, the Jacobians and the backward pass.

You need a little Python, what a derivative is and the word vectors of Lecture 2. We build the rest from zero.

Lecture 3, “Backpropagation and Neural Network Basics”, of Stanford CS224N, Natural Language Processing with Deep Learning (Winter 2026, Diyi Yang and Yejin Choi; this lecture’s slides are Diyi Yang’s). Before: Lecture 2, Word Vectors. Next: Lecture 4, Language Models and RNNs. The general backward pass, gate by gate: Backpropagation.

Train a window tagger

Illustrative toy, trained live in your browser. Our 6 labelled sentences give 35 windows. The 2-number word vectors stand in for Lecture 2’s. Window of 2 words each side, 4 tanh hidden units, full-batch gradient descent, learning rate 0.5. Chapter 9 opens up the same tagger.

Chapter 0

Is Paris a Place?

Tag the same word in two sentences and see why the word alone cannot decide

Lecture 3 opens with two sentences. “Last night, Paris Hilton wowed in a sequin gown.” “Samuel Quinn was arrested in the Hilton Hotel in Paris in April 1989.” In the first, Paris is a person. In the second, Paris is a place, and Hilton is part of a hotel’s name.

Finding such names and their types is named entity recognition (NER): label each word as a person, a location, an organization, a date or none. Question answering needs it, because answers are often names. So does tracking what a news story says about one company.

A classifier that sees only the word has one vector for “Paris”. One vector gives one answer, so it must be wrong in one of the two sentences. CS224N’s first fix is simple: classify each word together with its neighbours. To keep it small, the lecture asks one yes-or-no question: is the centre word a location? We ask the same question all through this lesson.

Give the tagger some context

The bracket shows what the tagger reads. Each Paris gets a probability of being a place. Widen the window and watch the two answers separate.

Illustrative toy: three copies of the hero’s tagger, each trained for 300 steps on our 6 sentences, one per window size. Both sentences are in the training set.

Here is the worked number. With the word alone, both Paris windows hold the same input, so the tagger gives both the same probability, 0.67. It calls both a place, and the Paris Hilton one is wrong. On pairs like these, a word-only tagger can be right at most half the time. With one neighbour each side, the answers split to 0.99 and 0.02.

Symptom: the tagger labels every “Paris” the same way, whatever the sentence says.

Measure: collect words that take two tags in your data. A tagger that reads only the word is right on at most one tag of each such word.

Fix: give the classifier the neighbours. Here a window of 2 words each side reads “Paris Hilton wowed” and “museums in Paris are”.

The road

  1. Window: five word vectors stacked into one input.
  2. Layer: a hidden layer and a nonlinearity score the window.
  3. Loss: cross-entropy, and its slope p − y.
  4. Jacobians: every output against every input.
  5. Chain: multiply Jacobians, and keep the error signal δ.
  6. Shapes: the gradient of W has the shape of W.
  7. Word vectors: the gradient reaches the words, and when to stop it.
  8. Graph: backpropagation as bookkeeping on a graph.
  9. Showcase: train the tagger, break it, check its gradients.
  10. Field guide: the shapes, the code, the readings.
Why can a tagger that reads only the word itself be right on at most one of “museums in Paris” and “Paris Hilton wowed”?

Chapter 1

Five Words Become One Vector

Look up each word’s vector, stack them in order, and count the weights the stack needs

Take the lecture’s sentence: “the museums in Paris are amazing to see.” To classify Paris with a window of 2 words each side, the classifier reads five words: museums, in, Paris, are, amazing.

Each word becomes its vector from Lecture 2. The lecture calls this the embedding layer, x = Le. Here e is a one-hot vector: all zeros except a 1 at the word’s index. It picks one column of the embedding matrix L. In code it is a table lookup.

Then we stack the five vectors end to end. This is concatenation: the first d numbers belong to “museums”, the next d to “in”, and so on. Slot order is position order, so the network can tell “in Paris” from “Paris in”.

Build the window input

Tap a word to make it the centre. Each block below is one word’s vector, in order. Change the sizes and watch the counts.

2
100

Counting tool. The 300-number size matches the published word2vec vectors; 50 is the smallest GloVe size. Words past the sentence edge use a padding vector.

Name the pieces before we write them down. Call the vector of the word “museums” xmuseums, and so on for each word. Each has d numbers. Call the stacked input x.

Say it aloud

x equals the stack of x-museums, x-in, x-Paris, x-are and x-amazing, and it lives in R to the five d.

x
x the window input: one long column of numbers that the network reads.
xmuseums ; …
x-museums, x-in, … each word’s vector from the embedding table, d numbers each. The semicolons mean “stack below”.
∈ ℝ5d
in R to the five d x is a list of 5 × d real numbers.
In plain words

Look up the vector of each word in the window. Write them one after another, left word first. The result x has 5 × d numbers.

With numbers

With d = 300, x has 5 × 300 = 1,500 numbers. A hidden layer of 100 units then needs a weight matrix W of 100 × 1,500 = 150,000 weights. Our toy uses d = 2, so x has 10 numbers.

Symptom: the first word of a sentence has no left neighbours, so the window is short and x has the wrong length.

Measure: the code crashes on a shape mismatch, or silently reads the end of the previous sentence.

Fix: pad. Put a special padding token past each edge, with its own vector. Tap “the” in the device to see two padding blocks.

A window of 2 words each side, word vectors of size 300, and a hidden layer of 100 units. How many weights are in W?

Chapter 2

A Hidden Layer Scores the Window

Push one window through a weight matrix, a nonlinearity and a final dot product, and read off a probability

A plain softmax classifier draws a straight boundary through the input space. The lecture lists what a neural classifier adds. It learns the weights and the word vectors together, and it stacks layers, so it can draw a curved boundary.

Our network has one hidden layer. It mixes the window’s numbers with a weight matrix, bends the result, and collapses it to one score. Then a squashing function turns the score into a probability.

Push one window forward

Three words go in at the top; a probability comes out at the bottom. Pick a nonlinearity and watch h, s and p change.

Worked example of ours, small enough to read: a window of 1 word each side (“in Paris are”), 2-number word vectors, 2 hidden units. We made up the weights.

Name each step. The weight matrix W and the bias b give the pre-activation z = Wx + b, one number per hidden unit. The nonlinearity f bends each number on its own: h = f(z). The weight vector u collapses h to one score s. The logistic function σ(s) = 1 / (1 + e−s) turns s into p, the probability that the centre word is a place.

Say it aloud

s equals u-transpose times f of, W x plus b.

s
s the score: one number, high when the network thinks the centre word is a place.
uT
u-transpose the output weights, laid flat as a row so that u-transpose times h is a dot product. Learned.
f
f the nonlinearity, applied to each number on its own: ReLU, tanh, logistic or GELU.
W
W the hidden weights: one row per hidden unit, one column per input number. Learned.
x
x the window input from Chapter 1.
b
b the bias: one learned offset per hidden unit.
In plain words

Multiply W by x and add b: that is z. Bend each number of z with f: that is h. Take the dot product of u with h: that is s. Then p = σ(s).

With numbers

From the device, with ReLU: z = (1.26, −1.10). ReLU keeps 1.26 and turns −1.10 into 0, so h = (1.26, 0). With u = (1.5, −0.8), s = 1.5 × 1.26 + (−0.8) × 0 = 1.89, and p = σ(1.89) = 0.87.

Why bend at all? Without f, two layers multiply out to one: W2(W1x) = (W2W1)x, a single matrix. Any number of linear layers is still one straight boundary. The lecture’s list of choices: logistic, tanh (which is 2 × logistic(2z) − 1), ReLU, Leaky ReLU, and GELU, the usual choice in Transformers. SwiGLU, a gated version, is in Llama 3 and Qwen3. Activation Functions draws each one.

Symptom: with ReLU, a hidden unit outputs 0 for this window, and nothing you do to its weights changes the score.

Measure: its z is −1.10, below zero, where ReLU is flat. Its slope is 0, so it passes back no gradient.

Fix: fine for one window. If a unit is negative for every window, it is dead for good: try tanh, Leaky ReLU or a smaller learning rate. Chapter 9 shows a whole tagger stuck this way.

Why does a network with two linear layers and no nonlinearity draw only a straight boundary?

Chapter 3

Cross-Entropy Turns a Guess into a Slope

Score the probability against the label, then find the one number that starts the backward pass

The network says p = 0.87 that Paris is a place, and a person labelled it a place. How wrong is that? Training needs one number that is large for a bad guess and small for a good one. That number is the loss.

The lecture states it as cross-entropy, from information theory. Let the true distribution put probability 1 on the right class and 0 on the rest. Then the cross-entropy keeps one term: minus the log of the probability the model gave the right class. For our yes-or-no question, call the hand label y: 1 for a place, 0 for not a place.

Say it aloud

J equals minus, y times log p, plus one minus y, times log of one minus p.

J
J the loss for this window. 0 is perfect; it grows without limit for a confident wrong guess.
y
y the hand label: 1 if the centre word is a place, 0 if not.
log
log the natural logarithm. log 1 = 0, and the log of a small number is far below 0.
p
p σ(s), the network’s probability that the word is a place.
In plain words

Find the probability the network gave the right answer: p if y is 1, or 1 − p if y is 0. Take its log and flip the sign. That is J.

With numbers

From Chapter 2: p = 0.869 and y = 1, so J = −log 0.869 = 0.141. If a person had labelled the window “not a place”, J = −log 0.131 = 2.03: fourteen times larger.

The backward pass starts with the slope of J against the score s. Use the logistic function’s slope, σ′(s) = p(1 − p). For y = 1, J = −log p, so the slope is −(1/p) × p(1 − p) = p − 1. For y = 0 the same steps give p. Both cases are one line:

∂J/∂s = p − y

Read “∂J/∂s” as “how much J moves per unit of s”. Here it is the prediction minus the label. In our example it is 0.869 − 1 = −0.131. The minus sign says: raise s and the loss goes down.

Drag the score, read the slope

The pink curve is J against s; the dashed line is its slope at your score. Drag s to −6 with the label “place”, then turn on squared error.

1.89

Exact curves. Squared error here is (y − p)², with p = σ(s), shown in grey because it is the alternative, not our loss.

Symptom: the loss prints nan or inf after a few steps.

Measure: p rounded to exactly 0 or 1, so the code took log 0.

Fix: compute the loss from the score s, not from p. PyTorch’s BCEWithLogitsLoss and CrossEntropyLoss take raw scores for this reason.

The network gives p = 0.2 for a word that is labelled a place (y = 1). What is ∂J/∂s, and what does training do with it?

Chapter 4

Jacobians: Every Output Against Every Input

Grow the derivative from one number to a vector to a matrix, and find the zeros in a layer’s matrix

The lecture’s motto: “multivariable calculus is just like single-variable calculus if you use matrices.” Start with one input and one output. For f(x) = x³ the derivative is 3x². At x = 1, nudge x to 1.01 and f goes to 1.0303: about 3 times the nudge.

With n inputs and one output, the derivative becomes a gradient: n slopes, one per input. With n inputs and m outputs, it becomes a Jacobian: an m × n table. Its entry in row i, column j is ∂fi/∂xj: how much output i moves per unit of input j. The chain rule stays the same idea. For one-variable functions you multiply derivatives. For vectors you multiply Jacobians.

Our network has three kinds of step, so it needs three kinds of Jacobian. The device shows each one. The first is the one the lecture works through: a nonlinearity applied to each number on its own.

Open a layer’s Jacobian

Rows are outputs, columns are inputs. Grey cells are zero. Pick a layer, then tap any cell.

Exact values. The f layer uses z = (0.5, −0.3, 1.2, −0.8); the other three use Chapter 2’s numbers. We checked every grid against finite differences.

Why is the first grid diagonal? Output hi = f(zi) uses input zi and nothing else. So ∂hi/∂zj is 0 whenever i and j differ. On the diagonal it is the slope of f at zi, written f′(zi).

Say it aloud

d-h by d-z equals diag of f-prime of z.

∂h/∂z
d-h by d-z the Jacobian of the nonlinearity layer: n rows (outputs h), n columns (inputs z).
diag( )
diag of a square matrix with the given numbers on its diagonal and zeros everywhere else.
f′(z)
f-prime of z the slope of f at each entry of z: a vector of n numbers.
In plain words

For each hidden unit, find the slope of f at its z. Put those slopes down the diagonal. Every other entry is zero, because no unit looks at another unit’s z.

With numbers

From the device: z = (0.5, −0.3, 1.2). ReLU’s slope is 1 above zero and 0 below, so ∂h/∂z = diag(1, 0, 1). The logistic slope σ(z)(1 − σ(z)) gives diag(0.235, 0.245, 0.178).

The other three come from the lecture’s matrix-calculus notes. For z = Wx + b, ∂z/∂x = W, because zi = Σk Wikxk + bi has slope Wij in xj. Also ∂z/∂b = I, the identity matrix. For s = uᵀh, ∂s/∂u = hᵀ, a row.

Symptom: code that builds the full Jacobian of a nonlinearity runs out of memory on a real layer.

Measure: for 4,096 hidden units the matrix has 4,096 × 4,096 = 16.8 million entries, and all but 4,096 are zero.

Fix: store only the diagonal f′(z), a vector, and multiply number by number. That product is the Hadamard product, written ∘.

h = tanh(z) for z with 3 entries. What does ∂h/∂z look like?

Chapter 5

Multiply the Jacobians, Keep the Error Signal

Chain three Jacobians into the gradient for the bias, and spot the part every other gradient shares

Now find how the score moves with the bias, ∂s/∂b. The lecture works on the score s, not the loss J. The loss only adds the factor p − y at the front (Chapter 3). The lecture works in three steps.

  1. Break the network into simple pieces and keep track of each piece’s size: x → z = Wx + b → h = f(z) → s = uᵀh.
  2. Apply the chain rule: ∂s/∂b = (∂s/∂h)(∂h/∂z)(∂z/∂b).
  3. Write out each Jacobian from Chapter 4: uᵀ, then diag(f′(z)), then I.

The identity changes nothing, and multiplying a row by a diagonal matrix scales each entry. So the product is uᵀ ∘ f′(z). Now try the weights: ∂s/∂W = (∂s/∂h)(∂h/∂z)(∂z/∂W). The first two factors are the same as before. Compute them once and give them a name.

Say it aloud

delta equals d-s by d-z, which equals u-transpose times f-prime of z, entry by entry.

δ
delta the error signal at z, also called the upstream gradient: one number per hidden unit.
∂s/∂z
d-s by d-z how much the score moves per unit of each pre-activation zi.
uT
u-transpose the output weights as a row: ∂s/∂h.
∘
entry by entry the Hadamard product: multiply matching entries, keep the vector.
f′(z)
f-prime of z the slopes on the diagonal of ∂h/∂z.
In plain words

For each hidden unit i, multiply its output weight ui by the slope of f at its zi. The list of products is δ. Because ∂z/∂b = I, the gradient for the bias is δ itself.

With numbers

From Chapter 2, with ReLU: u = (1.5, −0.8) and f′(z) = (1, 0), so δ = (1.5, 0). With tanh, f′(z) = (0.276, 0.359) and δ = (0.41, −0.29). A finite-difference check on b gives the same numbers.

Multiply the chain

Press Multiply to fold the chain from the left, one Jacobian at a time. Below, three gradients light up the part they share.

Chapter 2’s worked network: 2 hidden units, so each Jacobian is small enough to read.

Symptom: a hand-written backward pass is many times slower than the forward pass.

Measure: it recomputes uᵀ ∘ f′(z) separately for W, for b and for x.

Fix: compute δ once per layer, from the top down, and reuse it. That reuse is what makes backpropagation fast.

With ReLU, a hidden unit has z = −0.4 for this window. What is its entry of δ?

Chapter 6

The Gradient Has the Parameter’s Shape

Turn δ and the input into a grid with one slope per weight, and lay it out the way the update needs

The score s is one number. W has n × m numbers. Pure maths says ∂s/∂W is a 1 × nm Jacobian: one long row. That row is awkward, because the update W ← W − α∇ needs something the shape of W.

So the lecture leaves pure maths and uses the shape convention: the gradient has the shape of the parameter. Then ∂s/∂W is an n × m grid. Each weight’s slope sits in the weight’s own place.

Look at one weight to fill the grid. W23 joins input x3 to hidden unit 2. It feeds z2 and nothing else, and ∂z2/∂W23 = x3. The rest of the path from z2 to s is δ2. So ∂s/∂W23 = δ2 x3: the error signal at the unit times the signal coming into it.

Say it aloud

d-s by d-W equals delta-transpose times x-transpose.

∂s/∂W
d-s by d-W the gradient of the score for every weight, laid out like W: n rows, m columns.
δT
delta-transpose the error signal stood up as a column: n numbers, one per hidden unit.
xT
x-transpose the window input laid flat as a row: m numbers.
In plain words

A column times a row is a grid. Cell (i, j) is δi times xj. Each input meets each hidden unit once, which is why the transposes are there.

With numbers

From Chapter 5: δ = (1.5, 0) and x = (0.5, −0.2, 0.9, 0.4, −0.3, 0.6). Row 1 is 1.5 × x = (0.75, −0.30, 1.35, 0.60, −0.45, 0.90). Row 2 is all zeros, because unit 2 is off. For the loss, multiply by p − y = −0.131: ∂J/∂W13 = −0.177.

Fill the grid, one weight at a time

δ runs down the left, x runs across the top. Tap a cell to see its two factors. Then lay the same numbers out as the pure-maths row.

Chapter 2’s worked numbers. We checked each of the 12 products against finite differences.

The lecture gives two ways to work. Compute in Jacobian form, where the chain rule is easy, and reshape at the end. Or follow the shape convention all the way, using the sizes to decide where a transpose goes. The CS224N assignments expect answers in the shape convention.

Symptom: the update line fails with a shape error, or runs and trains badly.

Measure: the code computed x δ, a 6 × 2 grid, where W is 2 × 6. NumPy may broadcast a wrong shape without an error.

Fix: assert that each gradient has its parameter’s shape: assert dW.shape == W.shape.

A layer has W of shape 100 × 1,500. What shape is ∂J/∂W under the shape convention, and what is its entry (i, j)?

Chapter 7

The Gradient Reaches the Words

Send the gradient past W into the window, split it among the five words, and see who gets left behind

The lecture’s update rule is θnew = θold − α∇θJ, where α is the learning rate. Then it adds: “In deep learning, θ includes the data representation (e.g., word vectors) too!” So the gradient must reach x.

The last Jacobian we need is ∂z/∂x = W, from Chapter 4. Chain it after δ and put the result in the shape of x:

Say it aloud

d-J by d-x equals p minus y, times W-transpose, times delta-transpose.

∂J/∂x
d-J by d-x the gradient of the loss for every number of the window input: 5d numbers.
p − y
p minus y the slope of the loss against the score, from Chapter 3.
WT
W-transpose W flipped, so it maps hidden units back to inputs.
δT
delta-transpose the error signal as a column, from Chapter 5.
In plain words

Each input number xj feeds every hidden unit through column j of W. Add up Wij δi over the units, then multiply by p − y. Cut the result into five pieces of d: one piece per word.

With numbers

From Chapter 6: Wᵀδᵀ = (0.60, 0.15, 0.90, 0.75, −0.30, 0.45). Times −0.131, the Paris piece is (−0.118, −0.098). With α = 0.5, xParis moves from (0.90, 0.40) to (0.96, 0.45), and p rises from 0.869 to 0.879 from that move alone.

Should the word vectors move at all? They came from Lecture 2, trained on far more text than any labelled NER set. Moving them fits them to the task, but only the words in the training windows move.

Leave a word behind

Purple dots are word vectors; the blue side of the line is “place”. Yellow rings are words labelled place. Marseille is never in training. Train, then reset and train with word updates off.

Illustrative toy of ours: 8 words with made-up 2-number vectors. The classifier reads only the centre word, σ(θ · x + θ₀), so its boundary is a line you can see. 200 steps of gradient descent; weights and vectors share the learning rate 0.2.

The worked number: frozen vectors leave Marseille beside Paris and Lyon, and the boundary sweeps past all three, so Marseille ends at 0.93. With updates on, Paris and Lyon walk across the line by themselves. The boundary moves less, and Marseille stays behind at 0.09.

Symptom: after fine-tuning, the tagger misses place names it never saw in training, though their pretrained vectors sit next to known cities.

Measure: score words that are in the pretrained table but not in the training windows. Here Marseille falls from 0.93 (frozen) to 0.09 (fine-tuned).

Fix: the usual advice: with a small training set, keep the pretrained vectors fixed. With a large one, fine-tuning them usually helps.

You fine-tune word vectors on a small NER set where “Paris” and “Lyon” appear but “Marseille” does not. What happens to Marseille’s vector?

Chapter 8

Backpropagation Is Bookkeeping on a Graph

Run values forward through a graph, send gradients back one node at a time, and add them where paths meet

We almost have backpropagation already. It is the chain rule from Chapters 5 to 7, plus one habit: reuse what the higher layers computed. Software makes the habit automatic: it stores the computation as a graph. Inputs are source nodes, operations are interior nodes, and edges carry each result to the next node.

The forward pass visits the nodes in order and saves every value. The backward pass starts with gradient 1 at the output and visits the nodes in reverse. Each node gets an upstream gradient from above and knows its own local gradient: the slope of its output against each input.

Say it aloud

The downstream gradient equals the upstream gradient times the local gradient.

downstream
downstream gradient ∂f/∂(this node’s input): what the node passes back to the node before it.
upstream
upstream gradient ∂f/∂(this node’s output): what arrives from the node after it.
local
local gradient ∂(output)/∂(input) of this one node, saved during the forward pass.
In plain words

Multiply what arrives from above by the node’s own slope for each input. Send each product down that input’s edge. Where an input feeds several nodes, add what comes back.

With numbers

The lecture’s graph: f = (x + y) × max(y, z) with x = 1, y = 2, z = 0. Forward: a = 3, m = 2, f = 6. At the × node the upstream is 1. The local slope for a is m = 2, so a gets 2, and x gets 2. y gets 2 through the + node and 3 through max, so ∂f/∂y = 5. z gets 0.

Send the gradient back by hand

Blue numbers are values; pink numbers are gradients. Press Backward to move one node at a time. Then drag z above y and watch max route the gradient the other way.

1
2
0

The lecture’s example graph, computed exactly. The numeric check uses central differences with h = 0.0001.

The lecture names three node habits. A + node distributes: each input gets the upstream gradient unchanged. A max node routes: the larger input gets it all, the other gets 0. A × node switches: each input gets the upstream times the other input. And gradients add where a value branches out.

Done this way, the backward pass has the same big-O cost as the forward pass. To test a hand-written node, compare it with a numeric gradient, using a small step h of about 10−4:

∂f/∂θ ≈ ( f(θ + h) − f(θ − h) ) / 2h

Here θ is any one input or weight. It costs two forward passes per number, so use it to check a layer, never to train. Backpropagation tells the gate-by-gate story.

Symptom: one input’s gradient is too small, and only for inputs that feed two nodes.

Measure: the numeric check says ∂f/∂y = 5; the code says 2 or 3. It overwrote the gradient at the branch instead of adding.

Fix: accumulate: grad[y] += …, never grad[y] = …. This is also why PyTorch adds into .grad until you zero it.

In f = (x + y) × max(y, z) with x = 1, y = 2, z = 0, why is ∂f/∂y = 5?

Chapter 9

Showcase: Train a Window Tagger

Set the window, the nonlinearity and the width, train on six sentences, and test on four it never saw

This is the hero’s tagger with its covers off. Every step runs the forward pass on 35 windows, the loss, δ, the outer products and the split into word vectors, exactly as in Chapters 2 to 7. The four test sentences are not in training. Two of their place names, Lyon and Marseille, appear in no training sentence at all.

Train, test, check

Pick the settings, press Train, and read the test sentences. Then press Check gradients to compare backpropagation with the numeric slope.

Illustrative toy, trained live: the hero’s 6 sentences and vectors, 300 steps of full-batch gradient descent, learning rate 0.5, one fixed random start per setting. The numeric check perturbs one number by 0.0001 each way.

Things to try. Choose “Word only”: the two Paris windows in training get the same probability, so one is wrong, as in Chapter 0. Choose ReLU with 4 units: training stalls at 30 of 35 windows. All five place windows end with every unit below zero, so p sits at exactly 0.50. Their δ is 0, so no gradient can pull them back. Switch to 8 units and the same ReLU network learns all 35.

Check yourself. Why does the word-only tagger still get Rome right in the first test sentence? Why does the check agree to about 10−8 and not to 0? The first is in the training labels; the second is the numeric step, which is an approximation.

Chapter 10

Field Guide

Keep the shapes, the gradients, the code, and where the course goes next

A window classifier stacks the vectors of five words, scores them with a hidden layer, and turns the score into a probability. Cross-entropy turns the probability into a loss whose slope is p − y. The chain rule, written as Jacobians, gives the error signal δ = uᵀ ∘ f′(z). One δ gives every gradient: δ for b, δᵀxᵀ for W, Wᵀδᵀ for the word vectors. Backpropagation is that reuse, run node by node over a graph.

QuantityFormulaShape (toy)Shape (d = 300, 100 units)
window input xstack of 5 word vectors101,500
pre-activation zWx + b4100
score s, probability puᵀf(z), σ(s)1, 11, 1
loss slope∂J/∂s = p − y11
error signal δuᵀ ∘ f′(z)4100
∂J/∂W(p − y) δᵀxᵀ4 × 10100 × 1,500
∂J/∂b(p − y) δᵀ4100
∂J/∂u(p − y) h4100
∂J/∂x, cut into 5 words(p − y) Wᵀδᵀ10 = 5 × 21,500 = 5 × 300

The whole lesson as code: Chapter 2’s window, forward and backward by hand, then a gradient check on every weight. We ran it; the comments are its output.

python
import numpy as np

x = np.array([0.5, -0.2, 0.9, 0.4, -0.3, 0.6])    # [x_in; x_Paris; x_are], d = 2
W = np.array([[0.4, 0.1, 0.6, 0.5, -0.2, 0.3],
              [-0.5, 0.2, -0.3, 0.1, 0.4, -0.6]])  # 2 hidden units
b = np.array([0.1, -0.1])
u = np.array([1.5, -0.8])
y = 1                                              # the centre word is a place

def forward(W, b, u, x):
    z = W @ x + b                  # pre-activation
    h = np.maximum(0, z)           # f = ReLU
    s = u @ h                      # score
    p = 1 / (1 + np.exp(-s))       # probability of "place"
    J = -(y * np.log(p) + (1 - y) * np.log(1 - p))
    return z, h, s, p, J

z, h, s, p, J = forward(W, b, u, x)
g = p - y                          # dJ/ds
delta = u * (z > 0)                # u ∘ f'(z), one number per hidden unit
dW = g * np.outer(delta, x)        # same shape as W: (2, 6)
db = g * delta
du = g * h
dx = g * (W.T @ delta)             # split into three word vectors of 2

print(round(s, 2), round(p, 3), round(J, 3))   # 1.89 0.869 0.141
print(np.round(dx[2:4], 3))                    # Paris: [-0.118 -0.098]

# gradient check on every entry of W
eps, num = 1e-4, np.zeros_like(W)
for i in range(W.shape[0]):
    for j in range(W.shape[1]):
        Wp, Wm = W.copy(), W.copy()
        Wp[i, j] += eps; Wm[i, j] -= eps
        num[i, j] = (forward(Wp, b, u, x)[4] - forward(Wm, b, u, x)[4]) / (2 * eps)
print(np.abs(num - dW).max() < 1e-8)           # True

Where it sits. The slides write J for the probability σ(s) and take the gradient of the score; we kept J for the loss and carried the factor p − y. Modern frameworks run the backward pass for you. Each node’s writer still works out its local gradient by hand. The lecture’s case for learning it is debugging: Lecture 4’s vanishing and exploding gradients are this lesson’s products, multiplied many times.

Keep going

Read next

The habit. Before you write a gradient, write each quantity’s shape. Then the gradient of anything has that thing’s shape, and the transposes fall out.
Which sentence best sums up how one window’s loss updates the whole tagger?

Now teach it: press Present or Teach. Derive δ for the window classifier, then the gradients of W and of the five word vectors, and say each one’s shape. Then go back to the tagger, turn off word-vector updates, and predict whether the two Paris bars still split before you press Train.

Backpropagation and Neural Networks · Stanford CS224N, Lecture 3
Before: Word Vectors · Next: Language Models and RNNs · Course site · Back to Gleams