Deep Learning for Signals

A network that learns a pattern at one spot is blind when it moves. Slide one small filter along the signal, and it finds the pattern anywhere with 16 weights.

Pick where the pattern hides, then drag the shift and the noise. Watch the dense detector go blind while the sliding filter keeps finding it. Then we build everything underneath, piece by piece: layers, backpropagation, convolution, and spectrograms.

You need a sum of products (a weighted sum) and the idea of a slope. We build the rest from zero.

Based on Lecture 16 of Stanford EE269: Signal Processing for Machine Learning, taught by Mert Pilanci (November 18, 2020). Course slides. Every idea is re-taught here in our own words and devices. It follows Lecture 15, Neural Networks.

Find the pattern anywhere

20
0.25

Toy signal, 120 samples: a 16-sample pulse with ringing, hidden in random noise. Both detectors are one neuron. The dense one learned its 120 weights from windows where the pulse began at sample 20, so its weights are the pulse placed there. The convolutional one has 16 shared weights, the same pulse, and keeps its strongest response (max pooling). Scores are scaled so a clean pulse at the learned spot scores 1.00. Nothing here is trained on the page, the weights are written down, which is what training would find for this one example.

Chapter 0

Layers of Neurons

Follow real numbers through a small network and see why every layer needs a bend between its weighted sums

You carry a phone. Its accelerometer reports how hard the phone is pushed in three directions, twenty times every second. You want the phone to say “walking” or “sitting”. Nobody can write that rule by hand. The numbers are noisy, and every person walks a little differently.

So we do not write the rule. We show a program thousands of examples with the right answers, and it adjusts itself until it gets them right. That program is a neural network. Lecture 16 of Stanford EE269 starts with a recap of how one learns, then builds toward networks for images, sensor signals and speech.

The lecture is a single session by Mert Pilanci, given on November 18, 2020. It has 36 slides. The first six repeat and extend the last lecture. The rest are convolutional networks and two signal examples. This lesson follows the slides in order and explains each idea in our own words.

One neuron: a weighted sum with a bend

A neuron is the smallest part. It takes some numbers in. It multiplies each number by a weight, a dial that says how much that input matters. It adds the products. Then it passes the sum through a nonlinearity, a function that bends the result.

The bend we use most is the ReLU, short for rectified linear unit. It keeps positive numbers and turns negative ones into zero: ReLU(u) = max(0, u). Think of a one-way valve. Push forward and the flow passes. Push back and nothing comes through.

A layer: many neurons side by side

A layer is a row of neurons that all read the same inputs. Each neuron has its own weights, so each one looks for a different pattern in the same numbers. The layer’s output is the list of all their results.

A multilayer network stacks layers. The outputs of layer 1 become the inputs of layer 2, and so on. The slide draws this as a grid of circles joined by lines. Every line carries one weight.

The slide then writes the whole network in three lines. Read each symbol in the legend. Hover or tap a symbol to light its meaning.

z(0) = x
The input. The “layer 0” values are just the numbers you feed in, such as three acceleration readings.
aj(l)
The raw sum that neuron j in layer l collects, before any bend. We call it the pre-activation.
∑i
Add up over every neuron i in the layer below.
Wij(l)
The weight on the line from neuron i in layer l−1 to neuron j in layer l. These are the dials training turns.
zi(l−1)
The output of neuron i in the layer below. It is the number the weight multiplies.
zj(l)
The output of neuron j after the bend. We call it the activation. The next layer reads it.
σ
The nonlinearity. In the devices on this page it is the ReLU.

One honest note. The slide leaves out the bias, a constant added to every sum. Real networks keep it. You can hide it by giving every layer one extra input that is always 1, so the bias becomes an ordinary weight. We drop it here, as the slide does.

Follow the numbers

Here is a network small enough to hold in your head. It takes two numbers, x1 and x2. It has two hidden neurons and one output. Neuron 1 uses the weights (1, −1). Neuron 2 uses (0.5, 1). The output adds the two hidden values with weights (1, 2).

Feed it x = (1, 2). Neuron 1 sums 1×1 + (−1)×2 = −1. The ReLU turns that into 0. Neuron 2 sums 0.5×1 + 1×2 = 2.5, and the ReLU leaves it alone. The output is 1×0 + 2×2.5 = 5. Move the sliders below and watch each number change.

Run a forward pass

Blue circles are inputs. Purple circles are hidden neurons, with the raw sum a and the value z after the ReLU. The warm circle is the output. Drag the two inputs and find a spot where a hidden neuron goes silent.

1.0
2.0

Toy network with made-up weights, no bias, ReLU in the hidden layer and no bend at the output (the output is a plain weighted sum, the usual choice for a regression network). All numbers are computed live.

Notice what happened when neuron 1 went silent. Its ReLU output was 0, so it added nothing to the answer, whatever its outgoing weight. A neuron that outputs 0 passes no signal forward. Chapter 2 shows that it also receives no learning signal. Keep that in mind.

Why the bend matters

Suppose we removed every ReLU. Layer 1 would compute a weighted sum of the inputs. Layer 2 would compute a weighted sum of those sums. But a weighted sum of weighted sums is just another weighted sum, with new weights found by multiplying the matrices together. Ten layers would collapse into one.

The bend stops the collapse. With a ReLU between layers, the network can build curves, corners and decisions that no single weighted sum can. Depth only helps because of the bend.

Counting what training must find

The parameters of a network are all its weights, written together as Θ = (W(1), W(2), …, W(L)). Our toy network has 2×2 + 2×1 = 6 of them. A layer that reads dl−1 numbers and has dl neurons adds dl−1×dl weights.

For the phone, a window of 80 readings from 3 axes is 240 input numbers. A first layer of 100 neurons already has 24,000 weights. Training means finding good values for all of them. Chapter 1 shows how.

The road

  1. Training: a loss, a slope, and small steps downhill.
  2. Backpropagation: the chain rule, run backwards, gives every slope at once.
  3. Width and depth: what a layer can represent, and why deeper is cheaper.
  4. Too many weights: many perfect fits, and the optimizer picks one.
  5. Convolution: one small filter reused everywhere.
  6. ReLU, pooling and LeNet: keep the strong responses, shrink the map.
  7. ImageNet and the depth revolution: AlexNet, filters, and fooling a network.
  8. Signals and 1D convolutions: activity from a phone, 76% against 92%.
  9. Spectrograms: turn a sound into a picture with the short-time Fourier transform.
  10. Speech commands: the whole pipeline and a confusion matrix.
  11. Field guide: numbers, checklist, code.
A ten-layer network has no nonlinearity anywhere, only weighted sums. What can it compute?

Chapter 1

Training: Loss and Descent

Measure how wrong the network is with one number, then nudge every weight a little downhill

Imagine you are blindfolded on a hilly field. You want the lowest point. You cannot see, but you can feel the slope under your feet. So you take a small step in the direction that goes down, feel again, and repeat.

That is how a network learns. Your position on the field is the list of all its weights. Your height is a number called the loss, which says how wrong the network is on the training examples. Learning is walking downhill until the loss is small.

Two ways to measure wrong

The slide gives two losses. Both score one example n, and the total loss adds the scores over all N examples. The slide names the per-example score Rn(Θ). We use the same name.

For regression, where the answer is a number, the loss is the squared loss: Rn = (yn − f(xn))2. Here yn is the true value and f(xn) is what the network says. If the truth is 3 and the network says 5, the loss is (3 − 5)2 = 4.

For classification, where the answer is a label such as “walking”, the network ends with K outputs that are probabilities. A function called softmax turns raw scores into positive numbers that add up to 1. The label yn is written as a one-hot list: 1 for the true class and 0 for the others. The loss is the cross-entropy.

Rn(Θ)
The loss on example n. It depends on every weight in Θ.
∑k=1K
Add over the K classes.
ynk
1 if class k is the true class of example n, else 0. Only one term survives.
fk(xn)
The probability the network gives class k for input xn.

Only the true class counts, so the loss is simply −log of the probability the network gave the truth. Say there are three classes and the truth is class 2. A network that answers (0.2, 0.7, 0.1) has loss −log 0.7 = 0.357. A network that answers (0.8, 0.1, 0.1) has loss −log 0.1 = 2.303. The loss is gentle when you are nearly right and harsh when you are confidently wrong. We use the natural logarithm here.

Gradient descent: the step rule

The gradient is the slope of the loss with respect to every weight at once. It points uphill, so we step the other way. The step is scaled by the learning rate η, a small number you choose.

Θt+1
The weights after this step.
Θt
The weights before it. (The slide prints Θt+1 on the right side too. That is a typo. The old weights belong there.)
η
The learning rate: how long each step is.
∑ ∂Rn/∂Θ
The slope of the total loss: the slopes of all N examples added up.

Try one weight by hand. Let the loss be (w − 3)2 and start at w = 0 with η = 0.1. The slope is 2(w − 3) = −6. The step gives w = 0 − 0.1×(−6) = 0.6. At 0.6 the slope is −4.8, so w becomes 1.08. Each step is shorter than the last, and w creeps toward 3.

Stochastic gradient descent: one example at a time

The sum over N examples is the trouble. For a million images, one step needs a million passes through the network. That is too slow.

Stochastic gradient descent (SGD) draws one random example nt and steps along that example’s slope alone: Θt+1 = Θt − η ∂Rnt(Θ)/∂Θ. One example costs 1/N of the work. Its slope is noisy, but if you average it over all possible draws, you get exactly the full slope divided by N. So it points downhill on average. In practice people use a small random group, called a mini-batch, to smooth the noise.

The field has many valleys

The slide ends with three words: non-convex optimization problem. A convex loss has one valley, so every downhill walk reaches the same bottom. A network’s loss has many valleys. Even swapping two hidden neurons gives a different weight list that computes the same function, so valleys come in copies.

Where you end depends on where you start, and on how noisy your steps are. The device below has a toy field with two valleys, one deep and one shallow. Click the field to choose a start, pick the step rule, and run.

Walk downhill

Light areas are low loss. Click the field to move the start (the teal ring). Press Run to take 150 steps. Push the learning rate past 0.25, then past 0.5, and watch what breaks. Try SGD at a high rate and see if it hops valleys.

0.05

Toy loss L(x, y) = (x² − 1)² + 0.3x + 0.5y². Its valleys are at x near −1.04 (loss −0.30) and x near 0.96 (loss 0.29). The SGD noise is Gaussian noise of size 1.5 added to the slope, a stand-in for the luck of drawing one example. Real networks have millions of directions, not two.

Three things to see. First, the same start can end in different valleys, depending on the step rule. Second, SGD wanders but still arrives near a valley floor. Third, past a learning rate of about 0.25 the walker no longer settles. It jumps from wall to wall of the valley. Near 0.5 it overshoots so far that the loss explodes. The curvature at the right valley is about 7.1, so the largest step that still settles is about 2/7.1 = 0.28.

That is the whole failure story for the learning rate. Symptom: the loss goes up or jumps around. Measurement: print the loss after every step. Fix: halve η until the loss falls smoothly. Too small a rate is the quiet version: the loss falls, but so slowly that you stop long before the valley.

Why is SGD a sensible way to train when the data set has a million examples?

Chapter 2

Backpropagation

Run the chain rule backwards and get the blame for every weight in one sweep

A three-person assembly line bakes a cake, and the cake comes out bitter. Who is to blame? The last worker added too much salt. But the middle worker also passed along a doughy mix, and the first worker mis-measured the flour. Blame flows backwards along the line, and each worker gets a share.

Training needs exactly that. For each of a million weights, we need its share of blame: the slope of the loss with respect to that weight. Chapter 1 used the slope. This chapter finds it.

The slow way, and why it fails

One way is to nudge a weight by a tiny amount, run the whole network again, and see how much the loss moved. The ratio is the slope. It works, but it costs one full pass per weight. A network with a million weights needs a million passes for one gradient step. Nobody can train that way.

Backpropagation, often shortened to backprop, gets all million slopes for about the price of two passes. The trick is the chain rule.

The chain rule in one picture

The chain rule says how a slope passes along a chain. Suppose y depends on u, and u depends on w. If a nudge of w moves u by 3 times as much, and a nudge of u moves y by 2 times as much, then a nudge of w moves y by 3 × 2 = 6 times as much. Slopes along a chain multiply.

A network is a long chain. A weight changes a sum, the sum changes a neuron’s output, that output changes the sums of the next layer, and so on until the loss. Multiply the slopes along the chain and you have the weight’s share of blame.

The slide’s formula, symbol by symbol

Look at one weight Wij(l). It touches the loss only through the sum aj(l) that it feeds. So the chain has two links. The slide writes them, and then gives the second link a name.

∂Rn/∂Wij(l)
What we want: how much the loss on example n changes if this one weight changes.
∂Rn/∂aj(l)
First link: how much the loss changes if the sum aj changes. We name this blame δ.
∂aj/∂Wij
Second link. Since aj = ∑ Wij zi, nudging Wij moves the sum by exactly zi.
δnj(l)
The blame at neuron j of layer l, for example n.
zi(l−1)
The output of the neuron below, saved during the forward pass.

Read the result in plain words. A weight’s slope is the blame at the neuron it feeds, times the signal it carried in. A weight that carried a big signal into a blamed neuron gets a big slope. A weight that carried zero gets zero.

Passing blame backwards

The slide stops after defining δ. We still need δ for every layer. At the output it is easy: for a squared loss and a plain output, R = (f − y)2, so δ = 2(f − y).

For a hidden neuron j in layer l, its sum aj changes only its output zj = σ(aj). That output then feeds every neuron k of the next layer through the weight Wjk(l+1). Apply the chain rule over those links and you get the recursion.

δj(l)
The blame at neuron j in this layer.
σ′(aj)
The slope of the bend at this neuron’s sum. For the ReLU it is 1 if aj > 0 and 0 otherwise.
∑k
Add over every neuron k in the next layer that this neuron feeds.
Wjk(l+1)
The weight on the line from this neuron to neuron k.
δk(l+1)
The blame already computed one layer later. This is why we go backwards.

As matrices, with W(l) of shape dl−1 × dl: the blame moves back by δ(l−1) = σ′(a(l−1)) ⊙ (W(l) δ(l)), where ⊙ multiplies element by element. The slopes are the outer product z(l−1) δ(l)T, one slope for every weight.

Worked example, every step

Take the network from Chapter 0 with x = (1, 2) and a target y = 3. Forward: the hidden sums are −1 and 2.5, the ReLU outputs are 0 and 2.5, and f = 1×0 + 2×2.5 = 5. The loss is (5 − 3)2 = 4.

Backward. The output blame is δ = 2(5 − 3) = 4. The output weights get slopes δ × z = 4×(0, 2.5) = (0, 10). Pass the blame to the hidden neurons. Neuron 1: σ′(−1) = 0, so its blame is 0. Neuron 2: σ′(2.5) = 1, so its blame is 1 × 2 × 4 = 8.

The first-layer slopes are blame times input. Neuron 2 gets (8×1, 8×2) = (8, 16). Neuron 1 gets (0, 0). Check one by the slow way: raise the weight 0.5 to 0.501. The sum becomes 2.501, f becomes 5.002, the loss becomes 4.008004, and the ratio 0.008004/0.001 = 8.004. It matches the 8 from backprop.

Trace the blame

Choose a phase. Forward shows the numbers going in. Backward shows the blame δ in yellow and the slope on every line. Update takes one small step and reports the new loss. Then change the inputs and the target.

1.0
2.0
3.0

Same toy network as Chapter 0, squared loss, ReLU hidden layer. The update uses learning rate 0.01. The check compares the backprop slope of the weight from x1 to neuron 2 with a nudge of 0.0001 and a second full pass. All numbers are computed live.

Drag x2 down until neuron 2 goes silent. In the backward phase every slope into that neuron turns to 0. The neuron has no say in the answer, so it gets no blame, so its weights do not move. That is the quiet danger of the ReLU.

Cost, and a failure to watch for

Backprop needs the forward values a and z for every layer, so the network must store them. That memory is why large networks need big accelerators. The compute is about two forward passes: one forward, one backward.

Here is the failure. Symptom: a part of the network stops learning, and the loss stalls. Measurement: for each hidden neuron, count how often its ReLU output is exactly 0 across the training set. A neuron at 100% is dead: it gets no blame, so it never recovers. Fix: lower the learning rate (a huge step can push a neuron permanently negative), or use a leaky ReLU that lets a small slope through.

In the worked example, why does neuron 1 get a blame of exactly 0?

Chapter 3

Width and Depth

Count the bends a network can make, and see why folding beats adding more units

You want to copy a smooth curve using only straight sticks. One stick gives a line. Two sticks joined at an angle give a corner. With ten sticks the copy looks round. Use a hundred and you cannot see the corners at all.

A ReLU network does exactly this. Each hidden ReLU adds one bend. Slide 5 states the consequence in three lines. A two-layer network, which means one hidden layer, can compose arbitrary functions to arbitrary precision. It may need infinitely many hidden neurons. And deeper networks need fewer neurons for the same approximation error. Let us see all three.

One bend per unit

A single ReLU unit on one input is the function (x − t)+. It is 0 to the left of the point t. To the right it is a ramp that rises with slope 1. So it is a flat line with one bend at t.

Now add several units with different bend points t1, …, tm and different output weights cj. The network computes f(x) = a + s·x + ∑j cj (x − tj)+. At each bend point tj the slope of the curve changes by exactly cj. You get a chain of straight pieces, joined at m bends. We call it piecewise linear.

To copy a target curve, place the bends evenly and choose each cj so that the chain passes through the target at every bend. This is a constructed network, not a trained one. It shows what the network can represent.

Bend a line into a curve

Width mode: the warm chain copies the blue target using m ReLU units in one hidden layer. Depth mode: fold a tent shape k times, two units per fold. Switch between them.

3
3

Width mode: target 0.8 sin(2πx) on [0, 1]; the bends sit at j/(m + 1) and the chain is the exact straight-line interpolation of the target at those points. Depth mode: the tent map g(x) = 2(x)+ − 4(x − 0.5)+ on [0, 1], two ReLU units per fold. The count of pieces is exact. Neither mode involves training.

Slide the width up. At m = 1 the best chain is flat and misses by 0.8. At m = 3 the chain has the right overall wave. At m = 9 the corners are hard to see. Each time you double the number of pieces, the worst miss falls by about four. A smooth curve needs only about 1/√(error) bends.

Why “infinitely many”

The slide says the hidden layer may need infinitely many neurons. That is not a promise that it does. It means: for any precision you ask, there is a finite m that reaches it, but no single m works for every function and every precision. Ask for 100 times less error and you need about 10 times more units on this curve.

Inputs with many numbers make it worse. A curve over 2 inputs is a surface, and covering it with flat tiles needs a grid of bends. If one input needs 10 bends, two inputs need about 100. A signal window with 240 numbers is far out of reach for a single layer built this way.

Folding: depth multiplies, width only adds

Depth works differently. Take a tent shape on [0, 1]: it rises from 0 to 1 over the first half, then falls back to 0. Two ReLU units make it: g(x) = 2(x)+ − 4(x − 0.5)+.

Now feed the tent into another tent. The second tent folds the first one’s whole curve in half. The result has 4 straight pieces. Feed that into a third tent and you get 8 pieces. After k folds the curve has 2k pieces, and the network used only 2k units.

A one-hidden-layer network with m units makes at most m + 1 pieces on a one-number input. To make 2k pieces it needs at least 2k − 1 units. At k = 10 the deep network uses 20 units and the shallow one needs 1,023. Fold paper in half ten times and you get 1,024 layers from ten folds. The same logic applies here.

This is the reason behind the slide’s third bullet. Each layer reuses everything the layers before it built. A shallow network must build every feature from scratch, side by side. (The folding example is a known construction by Telgarsky, 2016, Benefits of depth in neural networks. It is a clean case, not a proof that every real task folds this well.)

What the theorem does not say

Approximation says a good network exists. It says nothing about finding it. Gradient descent from Chapter 1 still has to reach those weights, and it needs examples enough to tell a good fit from a lucky one. The next chapter shows what happens when there are far more weights than examples.

Symptom: a wide, shallow network keeps missing the fine structure of the data. Measurement: plot training error against the number of hidden units. If the error falls only like 1/m2, you are paying quadratically for precision. Fix: add layers, so each layer can build on the last.

Folding the tent shape 8 times gives 256 straight pieces. Roughly how many hidden units does the folded deep network use, and how many would one hidden layer need?

Chapter 4

Too Many Weights

Fit six dots with a network that has far more knobs than dots, and see that the optimizer picks the answer

A teacher gives you six dots on a page and says: draw any smooth curve through all of them. Easy. You can pass through the dots in many ways. Some curves are calm between the dots. Others swing wildly. All of them score full marks on the dots you were given.

Now give a network 193 weights and the same six dots. The training loss can reach zero in huge numbers of ways. So which curve do you get? Slide 6 asks this question, and answers it in two sentences. We will see both with a real network, trained live on this page.

The slide’s network

The slide uses a two-layer network with a scalar output: f(x) = ∑j=1m wj(2) (xT wj(1))+. Read it in pieces. The input x is dotted with the weight vector wj(1) of hidden unit j. The ReLU, written (u)+ = max(0, u), clips it. Then the output weight wj(2) scales it, and we add over all m units.

The training labels are y ∈ {+1, −1}. Zero training loss means f(xn) = yn for every example n. That is N equations. The network has m(d + 1) unknowns, where d is the length of x. When m is large, there are far more unknowns than equations.

One equation, three unknowns

School algebra already knows this. The equation w1 + w2 + w3 = 3 has one equation and three unknowns. The answer (3, 0, 0) works. So does (1, 1, 1) and (5, −1, −1). There are infinitely many.

Now run gradient descent from w = (0, 0, 0). The slope of the loss (w1 + w2 + w3 − 3)2 with respect to each wi is the same number, 2(sum − 3). So every step adds the same amount to every weight. The weights stay equal, and the walk ends at (1, 1, 1). It never reaches (3, 0, 0).

Of all perfect answers, gradient descent picked the one with the smallest length: √3 = 1.73, against 3 for (3, 0, 0). This is a true fact for linear least squares started at zero. The method did not ask for the shortest answer. The shortest answer came from how the walk moves.

Inductive bias: the choice nobody asked for

The slide gives it a name. The numerical optimizer (gradient descent, stochastic gradient, momentum and so on) may have an inductive bias. That is a built-in preference among solutions that fit the data equally well. It comes from the starting weights, the step rule and the shape of the network.

This matters because the training examples cannot tell the solutions apart. Only the preference can. Whether a network behaves well on new inputs depends on which perfect fit it was steered to, and the data alone does not say.

Fit six dots, again and again

Pick a width, then press Train. A real ReLU network starts from random weights and runs 3,000 gradient steps on the six blue dots. Train several times. Compare the curves between the dots.

Real training in your browser. Network f(x) = c + ∑ w2j ReLU(w1j x + bj), plain gradient descent on the mean squared error, learning rate 0.05, 3,000 steps, random Gaussian start. Six points with labels +1 or −1 are made up for the demo. A fit counts as perfect when the training loss is below 0.001.

With 3 units the network has only 10 weights for 6 equations. It cannot bend enough, and the loss stays high. With 16 units it usually gets close. With 64 units it reaches a loss near zero every time. Yet the curves between the dots differ from start to start. They agree where there is data. They disagree in the gaps and past the ends.

That is the two-sentence message of the slide, made visible. Zero training loss can have multiple solutions. Which one you land on is decided by the optimizer and the start.

What this means for you

It is surprising that very large networks, with far more weights than examples, often work well on new data. A classical view would predict they memorize noise. Explaining why they do not is an active research area, and the inductive bias of gradient descent is part of the story. We have shown the mechanism in the simplest case. We have not shown that it explains deep nets in general.

For practice, here is the failure. Symptom: training loss is near zero, but the loss on held-out data is high. Measurement: keep a validation set and plot both losses. Fix: more data, stopping early, adding a small penalty on the weights, or choosing a network shape that encodes what you know. Chapter 5 is the last: convolution builds in the knowledge that a pattern means the same thing wherever it appears.

A later lecture, Convex Neural Networks, returns to two-layer ReLU networks of exactly this form. For the link between this chapter and kernel methods, see Kernels.

Two runs of the same network, from different random starts, both reach zero training loss but give different curves between the training points. What does this show?

Chapter 5

Convolution: One Filter, Everywhere

Slide a small grid of weights across a picture and count what it saves compared with a dense layer

You look for a friend in a crowd photo. You do not memorize “the face is at pixel 120 across and 80 down”. You scan, and your eyes use the same idea of “my friend” at every spot. A pattern is the same pattern wherever it sits.

The hero at the top of this page showed what goes wrong without that idea. A dense detector stores a separate weight for every position, so it knows the pattern only where it learned it. Slides 7 to 10 introduce the fix: the convolutional neural network, or CNN. The slides credit LeCun and colleagues, 1998, Gradient-based learning applied to document recognition.

A dense layer on a picture is wasteful

Take a small 32 by 32 grey picture. It has 1,024 numbers. Suppose we want a layer that makes 6 feature maps, each 28 by 28. That is 28 × 28 × 6 = 4,704 output numbers. A dense layer connects every input to every output: 1,024 × 4,704 = 4,816,896 weights. Nearly five million, for one small layer.

It is also blind to structure. It does not know that pixel 5 and pixel 6 are neighbours. It cannot reuse anything it learned at one spot at another.

The filter: a small reusable detector

A filter, also called a kernel, is a tiny grid of weights, such as 3 by 3 or 5 by 5. Place it over a patch of the picture. Multiply each weight by the pixel under it. Add the nine products. That sum is one output number.

Then slide the filter one pixel and do it again. Repeat across the whole picture. The outputs form a new picture, the feature map. It lights up wherever the patch looks like the filter. This sliding sum is a convolution.

Y[i, j]
One number of the feature map, at row i and column j.
∑a ∑b
Add over every row a and column b of the filter.
K[a, b]
The filter weight at row a, column b. Training learns these.
X[i + a, j + b]
The pixel under that filter weight when the filter sits at (i, j).

A note for signal-processing readers. A textbook convolution flips the filter first. Deep-learning libraries skip the flip, which is strictly a cross-correlation. Since the filter is learned, the flip makes no difference to what the network can do. The 1D version of this sum is the FIR filter you met in Linear Systems. The only new part is that the taps are learned.

A worked patch

Take the vertical-edge filter with rows (−1, 0, 1) repeated three times. Put it over a patch whose left two columns are dark (0) and right column is bright (9). Each row gives (−1)×0 + 0×0 + 1×9 = 9. Three rows give 27. The filter fires strongly.

Now put it over a flat patch where every pixel is 5. Each row gives −5 + 0 + 5 = 0. The total is 0. A filter built from differences ignores flat regions and shouts at edges. Try it in the lab below. Move your finger or mouse over either picture to place the filter.

Kernel lab

Left: the input picture. Right: the feature map made by the chosen filter (warm is positive, blue is negative). Touch either picture to place the filter. The bottom row shows the patch, the filter, and the sum.

A 28 by 28 picture of a digit 2, drawn with a few strokes on this page (not a dataset image). The filters are the standard hand-made 3 by 3 kernels for identity, blur, sharpen and edges, like the operations listed on slide 10. Output is 26 by 26 because the filter stays fully inside the picture.

Look at the two edge filters. One answers to boundaries that run up and down, the other to boundaries that run side to side. A trained CNN does not use these hand-made ones. It learns the nine numbers by gradient descent. But the job is the same.

Shapes and counts, the slide’s example

Slide 8 gives a layer: input 32 × 32 × 1, six 5 × 5 filters, stride 1, padding 0. The output is 28 × 28 × 6. Stride is how many pixels the filter jumps each time. Padding is a border of zeros added around the picture.

The size rule: out = ⌊(n + 2p − f)/s⌋ + 1. Here (32 + 0 − 5)/1 + 1 = 28. The trainable parameters are the weights plus one bias for each filter: 5×5×1×6 + 6 = 156. Each of the 28 × 28 × 6 outputs reads 26 numbers (25 weights and a bias), so there are 28 × 28 × 156 = 122,304 connections, all using just 156 stored numbers.

That is the saving: 156 parameters against 4,816,896. The same 156 numbers are reused at every one of the 784 positions. This weight sharing also means a shifted picture gives a shifted feature map, which is called translation equivariance. During backprop, the slope of a shared weight is the sum of its slopes at all positions.

Shape calculator

Set up a layer. The defaults are the slide’s. The boxes show input and output sizes to scale.

32
5
1
0
6

One input channel, as on slide 8. Parameters are f × f × 1 × K + K. The dense layer would connect every input number to every output number, with no bias counted. The formulas are exact.

Try padding 2 with a 5 × 5 filter: the output stays 32 × 32. People call that “same” padding. Try stride 2: the output halves. Try stride 3 with n = 32, f = 5: the division is not whole, so the last few columns never get a window. That is the failure to check: symptom a shape mismatch error three layers later; measurement print the shape after every layer; fix pick p and s so (n + 2p − f) divides by s.

A layer has 10 filters of size 3 × 3 on a one-channel picture. How many trainable parameters does it have, with one bias per filter?

Chapter 6

ReLU, Pooling and LeNet

Keep only the strong responses, shrink the map, and stack the pattern into a digit reader

After a filter slides over a picture, the feature map holds thousands of numbers. Most are small. Some are large and positive, where the filter found its pattern. Some are negative, where the picture looked like the opposite of the filter. For a question such as “is there a vertical edge near here?”, you want to keep the strong yes answers and forget the rest.

Two small steps do this, and the lecture shows both. The first is the ReLU. The second is pooling. Then slide 12 puts the whole stack to work on handwritten digits.

ReLU on a feature map

Slide 11 shows a feature map before and after a rectified linear unit, with credit to R. Fergus. Every negative number becomes 0. Every positive number stays as it is. The picture goes from grey with bright and dark edges to mostly black with bright edges only.

Why use the ReLU and not a smooth S-shaped curve? Three reasons. It is cheap: one comparison. Its slope is exactly 1 for any positive input, so the blame from Chapter 2 passes through unshrunk. And it makes many outputs exactly 0, so only a few neurons speak at a time. The cost is the dead neuron from Chapter 2.

Pooling: summarize a small neighbourhood

Pooling cuts the map into small blocks and replaces each block by one number. In max pooling the number is the largest in the block. Slide 9 shows a 2 by 2 window with stride 2. The 28 × 28 × 6 map becomes 14 × 14 × 6. Each map is a quarter of its size, and the picture is still recognizable.

Count what pooling stores. Max pooling has no weights: it only compares. The slide shows the original LeNet version, which averages the four numbers, scales the average by one learned coefficient, and adds one learned bias for each map. That is 2 numbers per map, 12 for six maps, and 14 × 14 × 6 × (4 + 1) = 5,880 connections.

Pooling also builds a little tolerance for movement. Suppose an edge sits in one pixel of a block. Shift the picture by one pixel. The edge is still inside the same block, so the block’s maximum is the same. The map of the larger picture changes, but the pooled map changes less.

Convolve, rectify, pool

Four stages from the same digit: the input, the filter response (warm positive, blue negative), the response after ReLU, and the pooled map. Pick a filter and a pool. Then shift the picture by one pixel and read how much each map moves.

Same hand-drawn 28 by 28 digit as Chapter 5, one 3 by 3 filter, stride 1 and no padding (26 by 26), pooling 2 by 2 with stride 2 (13 by 13). The change percentages are computed here: the length of the difference between the two maps divided by the length of the original map.

Read the percentages. Without pooling the ReLU map moves a lot when the digit moves one pixel. Pooling reduces that, but does not remove it. A 2 by 2 window tolerates shifts up to about its own size. Stack many pooling steps and the tolerance grows, which Chapter 7 returns to.

The recipe: convolve, rectify, pool, repeat

A CNN repeats three steps. Convolve with a bank of filters. Apply the ReLU. Pool. Each round turns a big map with few channels into a smaller map with more channels. At the end, flatten the last maps into one long list. Feed that list to ordinary dense layers. Finish with softmax, as in Chapter 1.

LeNet on handwritten digits

Slide 12 shows a LeNet reading the digit 8, credit A. Harley. Early layers light up on strokes and short edges. Later layers light up on larger pieces of the shape. The last layer has ten outputs, one for each digit, and the 8 gets the highest.

Here are the sizes in the classic design, with our own parameter count. We assume each filter sees all maps of the layer below. Original LeNet-5 used a sparse connection table in one layer, so its real total differs a little.

LayerOutput shapeParameters
Input32 × 32 × 10
Conv 5×5, 6 filters28 × 28 × 6156
Pool 2×214 × 14 × 60 (max) or 12 (slide)
Conv 5×5, 16 filters10 × 10 × 162,416
Pool 2×25 × 5 × 160
Conv 5×5, 120 filters (one number per filter)12048,120
Dense 120 to 848410,164
Dense 84 to 10, softmax10850
Total61,706

Check one row. The second convolution has 16 filters. Each reads a 5 × 5 window on all 6 maps, so 5 × 5 × 6 = 150 weights plus 1 bias is 151 numbers per filter. Sixteen filters give 2,416. The whole network has about 62 thousand parameters. The first dense layer of Chapter 5, on a single small layer, had 4.8 million.

The failure to watch for: pooling too hard throws away where. Symptom: the network says an eye is present but cannot say where. Measurement: print the map size after every stage. When it reaches 1 × 1 too early, position is gone. Fix: pool less, or use a stride-1 stack. Classification can live with lost position. Tracking an object cannot.

What does 2 by 2 max pooling with stride 2 keep, and what does it throw away?

Chapter 7

ImageNet and the Revolution of Depth

See how stacked filters grew from digits to a thousand object classes, what they learn, and how a tiny nudge can fool them

A digit reader has ten answers and tiny pictures. Now imagine a program that must look at any photo and name the main object: a tabby cat, a school bus, a magpie. There are a thousand names to choose from. In 2010 this was far out of reach. By 2015 the best programs beat a human labeller on a standard test. Slides 13 to 19 tell that story and then show two strange things about what these networks learned.

The data: ImageNet

The ImageNet challenge, run each year from 2010, uses 1,000 object classes. The slide lists 1.2 million training images and 100 thousand test images. The slide cites Russakovsky and colleagues (2015) for the dataset. A model gets a photo and must name its object. The usual score is the top-5 error: the model makes five guesses, and it counts as right if the true class is among them.

Why five guesses? Many photos contain more than one object, and some classes are close, such as two breeds of terrier. Five guesses is a fairer test.

The revolution of depth

Slide 15 shows the winners of each year as a row of bars. The error falls year after year, and the number of layers rises. The last bar is a network with 152 layers whose error is below the human mark on the chart. The slide reads the 2016 winner as 2.991% error against 5.1% for a human.

The turning point was AlexNet (slide 16), by Krizhevsky, Sutskever and Hinton in 2012. It had five convolution layers and three dense layers, used the ReLU, and trained on two graphics cards. It cut the top-5 error to 15.3% when the next best entry had 26.2%. Everything before it was hand-built features. After it, learned filters took over.

Why does depth help here? Each layer sees a bigger part of the picture than the one below. A filter on the first layer looks at a 3 by 3 patch. A filter on the second layer looks at 3 by 3 first-layer outputs, which together cover 5 by 5 pixels. The window each neuron can see is its receptive field. Stack layers and it grows. Add pooling and it grows much faster, because one pooled pixel stands for several.

How much can one neuron see?

Each line shows the side of the patch one neuron can see after L layers of 3 by 3 filters. The dashed line is a 224 by 224 photo, the usual ImageNet input. Drag the depth and compare the two lines.

10

Exact arithmetic, not a trained network. Stack A: 3 by 3 convolutions with stride 1, so the side grows by 2 each layer. Stack B: the same, plus a 2 by 2 pool with stride 2 after every second convolution; each pool adds one step of the current spacing and doubles the spacing. Photo size 224 is the common ImageNet input.

Without pooling, 20 layers see only 41 by 41 pixels. With a pool after every second layer, the same count sees the whole photo and more. That is why real networks pool: they must connect far-apart parts of a picture without 100 layers.

What the layers learn

Slide 17 shows the filters of the first AlexNet layer, credit H. Scholte and colleagues. They are not random. Many are oriented edges at different angles, others are blobs of colour. Nobody designed them. Gradient descent found them, and they look like the first stage of the visual cortex. The slide’s credit hints at that link to neuroscience.

Slide 18 shows a second way to look. Pick one neuron deep in the network and ask: which input maximizes its output? Start from noise and take gradient steps on the pixels, not the weights. This is activation maximization, shown on the slide with credit to D. Wei and colleagues. Neurons in the first layers want edges and blobs. In the middle they want textures and parts, such as an eye or a wheel. Near the output they want whole objects. Depth builds a hierarchy: edges, then parts, then objects.

The surprise: adversarial examples

Slide 19 shows a panda, a faint pattern that looks like static, and the sum of the two. A person still sees a panda. The network calls the sum a gibbon with high confidence. In the paper this comes from (Goodfellow, Shlens, Szegedy, 2015), the panda scored 57.7% and the doctored image scored 99.3% for gibbon, and the change was 0.007 of the brightness range per pixel.

The recipe is short. Compute the gradient of the loss with respect to the input pixels. Move every pixel a tiny amount, ε, in the direction of the gradient’s sign. This is the fast gradient sign method.

Why does it work? Take a linear scorer with d inputs and weights w. A change of ε in each pixel in the direction sign(w) changes the score by ε times the sum of |wi|. That sum grows with d. In 150,000 pixels, a change too small to see adds up to a huge push. The device below shows the effect in the simplest case that has it.

Nudge every pixel

A 12 by 12 picture with a faint class pattern buried in noise. The classifier reads that pattern. Raise ε and move every pixel against the classifier. Watch the score cross zero while the picture barely changes.

0.000

Toy model, not ImageNet. 144 pixels, a smooth blob shared by both classes, a random plus-or-minus pattern of size 0.06 added for class A and subtracted for class B, and Gaussian noise of 0.18 per pixel. The linear classifier scores the pattern, so a change of ε per pixel moves its score by 144ε. Deep networks are fooled in a similar way (Goodfellow et al., 2015) but are not linear.

Look at the numbers. The noise already in the picture is 0.18 per pixel. The flip happens near ε of 0.05 or 0.06, smaller than that noise. Random noise cancels itself across 144 pixels. A change that is aimed at the classifier does not.

Symptom: a confident wrong answer on a picture that looks normal. Measurement: attack your own model with the sign method and plot accuracy against ε. If accuracy collapses at an ε far below visible, the model is fragile. Fix: train on perturbed pictures too. This helps, but it is an arms race, and no defence is complete.

Why can a change of 0.05 per pixel flip the toy classifier, when noise of 0.18 per pixel does not?

Chapter 8

Signals: Dense Net or 1D Convolution?

Read activity from a phone’s accelerometer and see why the same data scores 76% with one net and 92% with the other

Back to the phone in your pocket. Every twentieth of a second it records three numbers: how hard it is pushed forward, sideways and up. Slide 20 shows three such traces. They are wavy and noisy. You can tell them apart only by their rhythm. Slow and gentle: walking. Fast and hard: jogging. Almost flat: sitting.

This task is called human activity recognition. The slides take the example, with credit to N. Ackermann, from a published tutorial. We follow the slides.

Cutting the stream into windows

The phone produces a stream that never ends. A network wants a fixed-size input. So we cut the stream into windows, short pieces of equal length, and give each window one label. We assume a window of 80 readings, which is 4 seconds at 20 readings per second, with 3 axes. The input is a table of shape 80 × 3, which is 240 numbers.

The dense network

Slides 21 and 22 show the plain approach. Flatten the 80 × 3 table into a list of 240 numbers. Pass it through four dense layers. The last layer gives six outputs, one per activity. The slide reports 68,606 parameters and a test accuracy of 0.76. About one window in four is wrong.

The flaw is the one from the hero. The weight on reading 17 is a separate number from the weight on reading 18. A step that begins a tenth of a second later lands on different weights. The network must see every possible start time in training, or it will guess. Flattening also throws away the fact that readings 17 and 18 are neighbours in time.

The 1D convolutional network

Slide 23 uses a 1D convolution: the filter slides along time only. It is the same sum as in Chapter 5, but with one index. A filter of length 10 looks at 10 neighbouring readings, in all 3 axes, and gives one number per position. A bank of 100 such filters gives 100 numbers per position.

The slide lists the stack: Conv(length 10, 100 filters), Conv(10, 100), MaxPool(3), Conv(10, 160), Conv(10, 160), and GlobalAveragePooling. It reports 520,486 parameters and a test accuracy of 0.92. The dense network got 0.76.

The last item is new. Global average pooling averages each filter’s response over the whole window and returns one number per filter. After the last layer there are 160 filters, so it gives 160 numbers, however long the window was. It keeps “how strongly did this pattern appear?” and drops “when?”. That is exactly the shift tolerance the dense network lacks.

Try it. The filter below is tuned to a rhythm. The response is cut at zero by a ReLU, then averaged over time. Change the phase and the average hardly moves.

Listen for a rhythm

Top: one axis of a motion trace. Middle: the response of one length-10 filter after the ReLU, with its time average as a dashed line. Bottom: that average for all three motions. Pick a motion and a filter, then press New phase.

Synthetic traces at 20 readings per second, made up for this demo: walking is a 2 Hz wave of size 1, jogging a 3.2 Hz wave of size 1.3, sitting is small noise of size 0.08, and every trace has noise. The slow filter is a cosine with a period of 10 readings, the fast one a period of 6, the jerk filter is a difference of neighbours. These are hand-made filters. A trained network learns its own.

Look at the bottom bars. The slow filter gives its biggest average for walking, the fast filter for jogging, and neither says much for sitting. Press New phase several times. The three bars hold nearly still, because the average over the window forgets when the wave started.

Counting the parameters, layer by layer

The slide gives only the total. We can rebuild it, which is the best check that we understand the stack. We assume 3 input axes and 6 classes, and a final dense layer from the 160 averaged numbers to 6 outputs. The slide lists six layers and the total only works out with that last dense layer.

Add them: 3,100 + 100,100 + 160,160 + 256,160 + 966 = 520,486. It matches the slide. Pooling layers add no weights.

The parameter ledger

Each bar is one layer’s parameters. The labels under each name show how long the signal is after that layer. Change the window length and the filter length.

80
10

Our reconstruction of the slide’s stack: 3 input axes, 6 classes, valid convolutions (no padding), max pooling of 3. The total at window 80 and filter length 10 is the slide’s 520,486. The dense network’s 68,606 is the slide’s number; its layer widths are not on the slide.

Notice what the window length changes. Nothing in the parameter count: a convolution does not care how long the signal is. Only the lengths shrink. Slide the window down to 40 with filter length 10, and the last convolution has almost nothing left to look at.

What the comparison does and does not show

The convolutional net has 7.6 times more parameters and scores 16 points higher. Do not read this as “more parameters, better accuracy”. Chapter 4 showed that more weights alone do not choose a good solution. The point is the shape: shared filters, a local view, and a time average match how a rhythm is built. The dense net spends its weights learning each position separately.

To be fair: the two numbers come from one tutorial run, on one data split, with different widths. They illustrate the gap. They are not a controlled experiment. Symptom: a dense net that fits training windows but fails on new people. Measurement: test accuracy on a person the model never saw. Fix: use a convolutional stack, and split by person, not by random window.

What does global average pooling keep, and what does it drop?

Chapter 9

Spectrograms: Sheet Music for Any Sound

Cut a signal into short windows, take a Fourier transform of each, and stack the results into a picture a CNN can read

Look at a page of sheet music. It does not draw the air pressure of the sound. It says which notes play, and when. Left to right is time. Up and down is pitch. You can see a rising scale, a held chord, a sudden drum hit.

A signal like speech is only air pressure over time: a long list of numbers. A spectrogram is sheet music made from those numbers. Slide 24 gives the plan: take 1D signals x1[n], x2[n] and so on, turn each into a two-dimensional picture such as a spectrogram or a wavelet transform, and train a 2D convolutional network on the pictures. Then every tool of Chapters 5 and 6 applies.

Why not the whole-clip Fourier transform?

The discrete Fourier transform (DFT) from Lecture 6 tells you which frequencies a clip contains. But it adds up the whole clip, so it forgets when each frequency happened. A word played backwards has the same magnitude spectrum as the word played forwards. Speech is mostly about change over time: a vowel, then a burst, then a hiss.

The fix is old and simple. Look through a small window. Take the DFT of what you see. Slide the window along, and do it again. Each position gives one column of the picture. That is the short-time Fourier transform, or STFT. Our lesson on the STFT builds it in detail. Here is the formula from slide 25.

X[n, k]
One number of the picture: how much of frequency bin k is present in the window that starts at sample n. It is a complex number; its size is the picture’s brightness.
∑m=0L−1
Add over the L samples inside the window. m counts from the window’s left edge.
x[n + m]
The signal sample that sits m steps after the window start n.
w[m]
The window: a weight for each position inside it. The slide uses w[m] = 1 for 0 ≤ m ≤ L−1 and 0 elsewhere, a plain box.
e−j(2π/N)km
A spinning pointer that completes k turns over N steps. Multiplying by it and adding checks how much of that spin the signal has.

Slide 26 adds the version for any frequency. Replace the fixed grid 2πk/N by a free number λ, in radians per sample: X[n, λ] = ∑ x[n + m] w[m] e−jλm. The DFT version just samples this smooth curve at λ = 2πk/N. Pad the window with zeros so that N is larger than L and you sample it more finely, which draws a smoother picture without adding information.

The spectrogram is the squared size, |X[n, k]|2, drawn as brightness. Practitioners usually take a logarithm of it, so quiet parts stay visible. The hop, the number of samples the window moves each time, sets how many columns you get.

A worked size

Take 1 second of speech at 16,000 samples per second. Use a window of 400 samples (25 ms) and a hop of 160 (10 ms). The number of windows is ⌊(16,000 − 400)/160⌋ + 1 = 98. With N = 512, bins k = 0 to 256 are distinct, since the rest mirror them. The picture is 98 columns by 257 rows. These are common settings, not the slides’; they show the shape a CNN receives.

The trade you cannot avoid

A window of L samples at sampling rate fs lasts L/fs seconds and separates frequencies that differ by about fs/L hertz. Make the window long and each row is thin, but each column smears over a long time. Make it short and the reverse. Their product is fixed. This is the time-frequency uncertainty of the STFT.

Worked example at fs = 8,000 Hz. L = 64: window 8 ms, rows 125 Hz tall. L = 256: window 32 ms, rows 31.25 Hz tall. Four times the window gives four times finer rows and four times blurrier time.

Make the picture

The signal has a steady 1,000 Hz tone, a rising chirp, and a short click. Pick a window length. Short windows pin down the click. Long windows pin down the tone. Press Play to hear it.

Synthetic signal made for this page: 0.5 s at 8,000 samples per second with a 1,000 Hz tone, a chirp from 400 to 2,800 Hz between 0.05 s and 0.30 s, a click at 0.40 s, and a little noise. The DFT of each window is computed exactly in your browser with N equal to the window length and a hop of half a window. Brightness is the log of the squared size, over a 50 dB range. The tone width in the read-out counts the rows within 10 dB of the peak in one column. The Hann window is added for comparison; the slide uses the box.

Compare the extremes. At L = 16 the click is a sharp vertical line, but the tone and chirp are fat bands 500 Hz tall. At L = 256 the tone is a thin line, the chirp is a clean diagonal, and the click is a block tens of milliseconds wide. Try the Hann window: it tapers the edges, so the box window’s spill, called leakage, drops and the bands look cleaner.

The STFT is a convolution in disguise

Look at the formula again. For one bin k, X[n, k] is a sum of x[n + m] times a fixed list of weights w[m]e−j2πkm/N. That is a 1D convolution along time, with one complex filter per frequency bin. The STFT is a layer of 1D convolutions with filters fixed in advance. A CNN can start from that, or learn the filters itself. Both appear in speech systems.

Symptom: a spectrogram where the part you care about is a faint smear. Measurement: compute the thickness, in rows and columns, of a known tone and a known click, as the read-out above does. Fix: choose the window length for the feature that matters, or compute two spectrograms with different windows and give both to the network.

You double the window length. What happens to the spectrogram?

Chapter 10

Speech Commands, End to End

Follow a one-second clip of someone saying “stop” through data, spectrogram, network and confusion matrix

A smart speaker hears a one-second clip. It must decide: was that “stop”, “go”, some other word, or only room noise? It has to answer fast, on a small chip, for every voice. The last ten slides of the lecture build exactly this, in a few lines of MATLAB, using every idea from this lesson.

The slides show screenshots of code and plots. We read them for the ideas and rebuild the ideas here. We do not need MATLAB to understand any step.

The data: ten words and two extras

Slide 27 names the Speech Commands data set. The network must recognize ten spoken commands: yes, no, up, down, left, right, on, off, stop and go. The slide loads a short clip of a person saying “stop” and plays it. Two more labels exist: unknown, for any other word, and background noise.

Slide 28 lists how many clips each label has. The table shows 11 rows. Ten commands have between 1,839 and 1,885 clips each. “unknown” has 6,483. The rows add up to 25,021 clips.

That imbalance is deliberate: “unknown” pools many different words, so it has more clips. It is also a trap, as the next device shows.

The lazy model

Bars show the clip count for each label from the slide’s table. Switch to the lazy model, which ignores the audio and answers “unknown” every time, and see its score two ways.

Counts are the slide’s table (11 labels; the slide has no row for background noise). Accuracy is the share of all clips the model labels right. Balanced accuracy is the mean of the per-label recalls. Both are exact arithmetic on the table.

The lazy model never hears a word. It still gets 6,483 out of 25,021 right, which is 25.9%. Its balanced accuracy, the average over the 11 labels, is 1 in 11, or 9.1%. The first number flatters it. The second tells the truth. Always ask for the per-label score.

From sound to picture

Slides 29 to 31 turn each clip into a spectrogram with the STFT of Chapter 9. They show the waveform and the spectrogram of three clips side by side. A waveform is a messy squiggle. The spectrogram shows distinct blobs: the bright bands of a vowel, the short burst of a “t” or “p”. Shape differences between words are plain to the eye, so a CNN can learn them.

The data flow is simple. In: one clip, about 16,000 numbers. After the STFT: a picture, with time across and frequency up, as in the worked size of Chapter 9. After the network: 12 numbers that add up to 1. The largest one is the answer.

Training and validation

Slides 32 and 33 split the clips into a training set, which the network learns from, and a validation set, which it never trains on. Two bar charts show that both sets have the same label proportions, so the split keeps the imbalance in both. Ideally the validation clips also come from other speakers. A network tested on the voices it trained on looks better than it is.

The slide also shows the network in code: a small stack of convolution layers, each followed by a nonlinearity and pooling, ending with a dense layer and softmax. This is the recipe of Chapter 6 applied to the spectrogram image.

Slides 34 and 35 train it. The progress plot has two curves. Accuracy rises fast and then flattens. The loss falls and flattens. Watch the gap between the training curve and the validation curve. A small gap means the network learned something that carries to new clips. A growing gap means it is memorizing, which is the symptom from Chapter 4.

The confusion matrix

Slide 36 shows the result as a confusion matrix. Each row is a true label. Each column is what the network said. The cell at row no and column go counts clips of “no” that the network heard as “go”. A perfect network has numbers only on the diagonal.

Two summaries come from the matrix. The recall of a label is its diagonal cell divided by its row total: of all true “no” clips, how many did we catch? The precision is the diagonal cell divided by its column total: of everything we called “no”, how much really was?

A worked case. Suppose 100 true “no” clips: 92 heard as “no”, 5 as “go”, 3 as other things. Recall is 92/100 = 92%. Suppose the “no” column holds those 92 plus 8 clips of other words, 100 in all. Precision is 92/100 = 92%. A network can score high on one and low on the other. Always read both.

Read the confusion matrix

Rows are the true label, columns what the network said. Green is right, red is a mistake. Touch a cell. Switch between counts, recall (each row as a percentage) and precision (each column as a percentage).

Illustrative, not the slide’s numbers. We built a matrix for the slide’s 11 labels: validation sizes are one fifth of the table’s counts, every label is right about 93% of the time, 90% for unknown, and we added plausible mix-ups (no and go, on and off, off and up, down and go). Counts are rounded, so totals can differ by one.

Click the cell for “no” heard as “go”. Then click “off” heard as “up”. Each such pair sounds alike: a short vowel after a voiced start, a similar burst. The matrix tells you where to put effort, which a single accuracy number cannot.

Symptom: a good overall accuracy and an unhappy user, because one command keeps failing. Measurement: read the recall of each row and look for rows below the others. Fix: collect more clips for that label and its confusable partner, or give the network a longer window around the burst.

A lazy model answers “unknown” for every clip and scores 25.9% accuracy on the table. What does this teach about judging a classifier?

Chapter 11

Field Guide

Keep the numbers, the checklist and the core code, then pick the right pipeline for your own signal

Lecture 16 in one paragraph. A network is layers of weighted sums with bends between them. Training lowers a loss by walking downhill, and backpropagation gives the slope of every weight in two passes. One hidden layer can copy any curve but may need very many units, and depth reuses work. Far more weights than data leaves many perfect fits, and the optimizer chooses. Convolution reuses one small filter everywhere, ReLU and pooling keep strong responses, and stacking gives edges, parts, then objects. For sensor streams use 1D convolutions, and for sound turn the clip into a spectrogram first. Check per-label recall, not accuracy alone.

Pick the pipeline

Choose a kind of signal. The boxes show the stages from the chapters, with the data shape after each one.

Shapes are illustrative settings from this lesson (a 224 by 224 colour photo, an 80 by 3 motion window, one second of 16 kHz sound with a 25 ms window and 10 ms hop, a table of 20 numbers). They are starting points, not the slides’ exact choices.

The numbers to keep

WhatValueWhere
Dense layer, 32×32 picture to 28×28×64,816,896 weightsChapter 5
Conv layer, six 5×5 filters156 parameters, 122,304 connectionsSlide 8
Pooling layer, 2×2, six maps5,880 connectionsSlide 9
LeNet-style network, our count61,706 parametersChapter 6
ImageNet1,000 classes, 1.2 M train, 100 k testSlide 14
2016 winner, ImageNet top-5 error2.991% (human 5.1%), 152 layersSlide 15
AlexNet, 2012, top-5 error15.3% against 26.2% for second placeKrizhevsky et al.
Activity recognition, dense net68,606 parameters, accuracy 0.76Slide 22
Activity recognition, 1D CNN520,486 parameters, accuracy 0.92Slide 23
Speech Commands table25,021 clips, unknown 6,483 (25.9%)Slide 28
Spectrogram of 1 s at 16 kHz (25 ms window, 10 ms hop)98 columns by 257 rowsChapter 9, illustrative

The words to keep

Checklist before you train

The core as code

Three short pieces carry the lesson: backprop for the toy network, a 1D convolution layer with global pooling, and the STFT. All three run as written with NumPy. The first prints the slopes (0, 10) and (8, 16) that we found by hand in Chapter 2.

python
import numpy as np

# 1. Backprop for a 2 -> 2 -> 1 ReLU network, squared loss
def forward(W1, W2, x):
    a1 = W1 @ x                       # (2,) raw sums
    z1 = np.maximum(0, a1)            # (2,) after ReLU
    return a1, z1, W2 @ z1             # f has shape (1,)

def backward(W1, W2, x, y):
    a1, z1, f = forward(W1, W2, x)
    d2 = 2 * (f - y)                  # blame at the output
    gW2 = np.outer(d2, z1)            # slope of each output weight
    d1 = (a1 > 0) * (W2.T @ d2)     # blame passed back through the ReLU
    gW1 = np.outer(d1, x)             # slope of each first-layer weight
    return gW1, gW2

# 2. A 1D convolution layer, ReLU, global average pooling
def conv1d(x, K, b):
    # x: (T, C_in), K: (k, C_in, C_out), valid convolution -> (T-k+1, C_out)
    k = K.shape[0]
    return np.stack([np.tensordot(x[t:t+k], K, axes=([0, 1], [0, 1])) + b
                     for t in range(x.shape[0] - k + 1)])

h = np.maximum(0, conv1d(x, K, b))     # (71, 100) for T=80, k=10, 100 filters
g = h.mean(axis=0)                    # (100,) one number per filter

# 3. STFT power: window L, hop, zero-padded to N points
def stft_power(x, L=400, hop=160, N=512):
    w = np.ones(L)                    # the slide's box window
    frames = [x[n:n+L] * w for n in range(0, len(x) - L + 1, hop)]
    return np.abs(np.fft.rfft(frames, n=N, axis=1)) ** 2   # (98, 257) for 1 s at 16 kHz

Where it sits in the field

Everything here is about local, shared structure. Convolutions assume that nearby values matter together and that a pattern means the same thing anywhere. That fits images, sensor streams and spectrograms. It fits less well when the important link is between far-apart parts. The next lectures take on that case: attention lets every position look at every other, and transformers for signals build whole models from it. The wavelet pictures of slide 24 are in Wavelets, and Diffusion and Autoencoders use the same convolutional blocks to generate and compress.

Keep going

The takeaway. A pattern means the same thing wherever it appears. Build that fact into the network, with one small filter reused everywhere, and you need far fewer weights and far less luck. Then test it on every label, not on the average.

Now teach it back. Open Teach and draw the backward pass for the toy network, or press Present to explain convolution to a friend. Or go back to the hero and move the pattern again: you now know why the sliding filter does not care.

Credit. These slides are from Stanford EE269, taught by Mert Pilanci: course site, slides. Slide images credit R. Fergus, A. Harley, H. Scholte and colleagues, D. Wei and colleagues, and N. Ackermann. All text, devices and examples here are our own. Sources: LeCun et al., 1998, Gradient-based learning applied to document recognition; Krizhevsky, Sutskever and Hinton, 2012, ImageNet classification with deep convolutional neural networks; Russakovsky et al., 2015, ImageNet Large Scale Visual Recognition Challenge; Goodfellow, Shlens and Szegedy, 2015, Explaining and harnessing adversarial examples; Telgarsky, 2016, Benefits of depth in neural networks.

EE269 Lecture 16: Deep Learning for Signals
Course: Stanford EE269 · Slides · Back to Gleams