One straight line cannot split a ring from its centre. Add a few hidden units, let gradient descent tune them, and the line bends until it can.
Learn what a hidden layer computes, how backpropagation finds every weight’s share of the blame, and why two layers are enough to draw almost any shape.
Pick a pattern. Set the hidden units to 0 and press Train: a single line fails. Then raise the units and train again. Watch the boundary bend around the points. Then we build, piece by piece, everything underneath: the layer, the loss, the gradient, the chain rule, and the proof that shapes come from lines.
You need a little calculus (a derivative says how fast one number changes when another does) and the idea of a dot product. We build the rest from zero.
Based on Lecture 15 of Stanford EE269: Signal Processing for Machine Learning, taught by Mert Pilanci (March 2019). Lecture slides. The decision-region slides credit Bhiksha Raj. Every idea is re-taught here in our own words and devices; it follows Adaptive Filters and leads to Deep Learning.
Toy data made in your browser: 80 points from a seeded generator, the same on every visit. The network has 2 inputs, tanh hidden units and one sigmoid output, and trains on all 80 points at once by gradient descent with momentum 0.9 (learning rate 0.15). With 0 hidden units it is a single line. Accuracy is counted on the training points, not on new ones.
Chapter 0
See a simple signal problem that no linear method can solve, and meet the idea that fixes it: let the machine learn its own features
A small vibration sensor sits on a motor. Every tenth of a second it reports two numbers: how much the motor shakes up and down, and how much it shakes side to side. When the motor is healthy, both numbers stay close to a calm middle value. When a bearing starts to fail, the motor shakes harder in some direction. Sometimes it shakes more up and down, sometimes more side to side, sometimes both.
Plot every reading as a dot. The healthy dots make a cloud in the centre. The faulty dots make a ring around it. Your job is to write a rule that says “healthy” or “faulty” for any new dot. The first rule most of us reach for is a line.
A linear classifier picks a direction and a cut-off. For a reading with two numbers x = (x1, x2), it computes one score, w1x1 + w2x2 + b, and says “faulty” if the score is above zero. The numbers w1 and w2 are weights (how much each reading counts) and b is the bias (a fixed shift). Where the score is exactly zero, the rule draws a straight line. Everything on one side is “faulty”, everything on the other is “healthy”.
Earlier lectures in this course used rules like this, from the Bayes classifier to the support vector machine. They work well when one straight cut can separate the classes. A ring around a cloud has no such cut. Any line you draw leaves dots of the wrong colour on at least one side. Try it yourself below.
Blue dots are healthy readings, pink dots are faulty ones. In the first mode you turn a line; the device always slides the line to its best position for that angle. In the second mode you describe each dot by one new number, its distance from the centre, and cut that.
Toy readings, not real sensor data: 40 healthy and 40 faulty dots from a seeded generator, the same on every visit. Accuracy is counted on these 80 dots. In the first mode the line takes the best offset for the angle you choose, so you see the best a line can do at that angle.
Turn the line through all 180 degrees. The best any line can do on these 80 dots is 61 right and 19 wrong, 76%. Now switch to the second mode. A cut-off on distance from the centre gets all 80 right. The data did not change. Only the way we described each dot changed.
That new number is a feature: a quantity we compute from the raw input so that the problem gets easier. Here the feature is r = √(x12 + x22). Engineers in signal processing have built features by hand for decades: the energy in a frequency band, the zero-crossing rate of an audio clip, the peak of a spectrum, the mel-frequency cepstral coefficients (MFCCs) of the cepstrum lesson. Each one is a nonlinear function of the raw samples, chosen by a person who understood the signal.
Hand design has two limits. It needs a person who already knows which feature will work. And it does not scale: a camera gives 784 numbers for a tiny 28 by 28 picture, a microphone gives 16,000 numbers per second, and nobody can guess the right features by staring at them.
This lecture takes the other road. Let the network learn its features. A neural network is a stack of small units. Each unit takes a weighted sum of what it receives and bends the result with a fixed nonlinear function. The weights are set by an optimisation procedure, driven by data. The hero at the top of this page did exactly that for the ring: three hidden units were enough to learn the distance-like feature we just built by hand.
This lesson follows the lecture’s 38 slides in order. Slides are one short paragraph each in the deck, so every chapter below adds the worked numbers and devices the slides leave to the speaker.
Chapter 1
Follow three sensor numbers through a layer of learned features to a prediction, and name every part on the way
Back to the motor. This time the sensor gives three numbers per reading: the up and down shake, the side to side shake, and the casing temperature, each scaled to the range 0 to 1. A technician wants one of three answers: healthy, failing bearing, or loose mount. A network that does this has three layers of numbers, and the lecture draws them as columns of circles.
The left column is the input: the three readings, x1, x2, x3. The slide writes d for how many there are. The right column is the output: one number for each answer the technician wants, y1, …, yK, here K = 3. In the middle sits the hidden layer: M numbers z1, …, zM that nobody gave us and nobody reads. They are hidden because they are neither input nor answer. They are the network’s own private features.
A unit (also called a neuron) is a small function. It takes all the numbers from the column before it, multiplies each by its own weight, adds them up, and then bends the sum with a fixed curve. Think of a unit as a detector with a dial for each input. Turn up the dial for side shake and the unit starts to respond to side shake. The bend makes its answer smooth: close to 0 for a clear no, close to 1 for a clear yes, and in between when unsure.
Read the two equations as a data flow. The input x has shape (d). The hidden layer multiplies it by a table of weights (M × d), bends every entry, and produces z of shape (M). The output stage multiplies z by a second table (K × M) and applies g, giving y of shape (K). Two tables of weights are everything the network knows.
Take the reading x = (0.8, 0.2, 0.5) and three hidden units with sigmoid curves, σ(u) = 1/(1 + e−u). The weights below are made up for the example. Unit 1 has α1 = (1.2, −0.8, 0.5). Its weighted sum is 1.2 × 0.8 − 0.8 × 0.2 + 0.5 × 0.5 = 0.96 − 0.16 + 0.25 = 1.05. The sigmoid of 1.05 is 0.741. Unit 2, with α2 = (−0.7, 1.1, 0.9), sums to −0.56 + 0.22 + 0.45 = 0.11 and gives 0.527. Unit 3, with α3 = (0.4, 0.6, −1.3), sums to 0.32 + 0.12 − 0.65 = −0.21 and gives 0.448. So z = (0.741, 0.527, 0.448).
Now the output stage. The three output rows give scores of 0.718, 0.414 and 0.601. Those raw scores are not yet answers. Drag the readings in the device below, and watch the scores become answers.
Left: your three readings. Middle: the three hidden units, brighter when they respond more. Right: the three outputs. Line thickness shows the size of each weight. Drag a reading, then switch the output between classification and regression.
Illustrative: the 18 weights are made up for this page (they are not trained), with no bias terms, as in the lecture’s equations. The arithmetic is exact. The three class names are our own labels for the example.
The slide lists the two standard choices for g. For regression, where the answer is a number on a scale (a temperature, a price), g is the identity: g(u) = u. The output is just the weighted sum, f(x) = βTz. Flip the device to regression and the raw scores 0.72, 0.41, 0.60 are the answers.
For multi-class classification, we want one probability per class, all positive, adding up to 1. The softmax does that. It raises e to each score, then divides by the total: gk(u) = euk / ∑j euj. Here e0.718 = 2.050, e0.414 = 1.513, e0.601 = 1.824, and the total is 5.387. The three shares are 38.1%, 28.1% and 33.9%. Raising to a power makes every share positive. Dividing by the total makes them add up to 1.
Training needs a target in the same shape. The lecture uses one-hot encoding: if the true class is k, the target vector y is ek, the k-th ordinary basis vector, a 1 in slot k and 0 everywhere else. For “loose mount” (class 3) the target is (0, 0, 1). The network’s job is to push its third share toward 1.
Suppose we removed the bend, so each unit just reports its weighted sum. Then the output would be βT(αx), and by regrouping, (βTα)x: one weight table again. The hidden layer would vanish and we would be back to a linear rule. The nonlinear bend is what lets a hidden unit make a decision of its own.
How many numbers does the network store? Each of M hidden units has d weights, and each of K outputs has M weights. The total is M·d + K·M, plus M + K biases if we add them. For a 28 by 28 image, d = 784. With M = 100 hidden units and K = 10 classes, that is 78,400 + 1,000 = 79,400 weights (79,510 with biases). The first table is almost all of the cost, because the input is wide.
Chapter 2
Repeat the layer rule as many times as you like, then choose the one number that says how wrong the network is
One hidden layer can already bend a line. Nothing stops us from feeding the hidden layer into another hidden layer, and that one into a third. Picture a chain of filters in a sound studio: each filter takes the sound from the one before it and reshapes it. A deep network is a chain of such reshaping steps, where each step is the same small rule with its own weights.
The lecture writes the rule for any layer, numbered l from 1 to L. The input is layer 0. Each later layer first forms a weighted sum of the layer below, then bends it.
As tensors, layer l holds a weight table W(l) of shape (nl−1 × nl), where nl counts the units in layer l. If you feed B readings at once, the layer below hands over a table of shape (B × nl−1), one matrix multiply gives (B × nl), and the bend acts on every entry. The deck keeps biases out of the formula. A bias is a weight on a fixed extra input of 1, so it fits the same rule, and the device below uses one per unit.
Chapter 1 showed that a layer without a bend collapses into a single weight table. That is true at any depth: two plain weight tables multiply into one, three into one, a hundred into one. A hundred-layer network with no bend is exactly as powerful as a line. The bend is what stops the collapse. Try it below: choose a bend, then add hidden layers and see how the curve of a one-input network changes.
The warm curve is the network’s output y as you move the input x from left to right. Choose the bend, then raise the hidden layers. Press New weights to draw a different random network.
Illustrative: each hidden layer has 6 units, weights are random draws from a seeded generator (not trained), and each unit has a bias. The curve is computed exactly at 240 points; “turns” counts the places where the curve changes from rising to falling or the reverse.
With no bend the output is a straight line at every depth: zero turns. With tanh or sigmoid the curve is smooth and bends. With ReLU it is built from straight pieces that meet at corners. How many turns a curve has depends on the random weights and the depth, so press New weights a few times and watch the count change. The three bends are the common choices. Sigmoid, 1/(1 + e−u), squeezes any number into (0, 1) and has a steepest slope of 0.25. Tanh squeezes into (−1, 1) with a steepest slope of 1. ReLU (rectified linear unit), max(0, u), passes positive numbers unchanged and clips negative ones to zero, with a slope of 1 or 0. Chapter 5 shows why those slopes matter.
Training needs one number that says how wrong the network is on an example. The lecture names the two standard scores and writes both as a sum over the N training examples, Rn(Θ) being the score of example n, and Θ all the weights, (W(1), …, W(L)).
For regression, use squared loss: Rn = (yn − f(xn))2. If the target is 1.0 and the network says 0.644, the score is (1.0 − 0.644)2 = 0.126. Squaring makes every miss positive and makes a big miss cost much more than a small one: missing by 0.2 costs 0.04, missing by 0.4 costs 0.16.
For classification, use cross-entropy loss: Rn = −∑k ynk log fk(xn). Because the target is one-hot, every term but one is zero, and the score is just −log of the share the network gave to the right class. In Chapter 1 the network gave the right class (loose mount) 33.9%, so the score is −ln(0.339) = 1.08. If it gave 90%, the score would be 0.11. If it gave 1%, the score would be 4.6. Being confidently wrong is punished very hard, and being right with high confidence costs almost nothing.
Chapter 3
Turn “find good weights” into “walk to the bottom of a landscape”, and see what batch steps, noisy steps and many valleys do to the walk
You are on a foggy hillside and you want to reach the lowest point. You cannot see it. You can feel the ground under your feet, so you know which way is down and how steeply. A sensible plan: take a step in the steepest downhill direction, feel again, and repeat. That is the whole idea of gradient descent.
For a network, the hillside is the loss. Every setting of all the weights Θ is a place on the map, and the height there is the total loss over the training set. The slide writes that total as ∑n=1N Rn(Θ). Training means finding weights where the height is low.
The slope of the ground in each direction is the gradient: for every weight, a number that says how much the loss grows if that weight grows a little. Walking downhill means subtracting a small multiple of it. The multiple is the learning rate η, the length of each step.
Take the simplest hill there is: one weight w and the loss R(w) = (w − 3)2. The slope is 2(w − 3). Start at w = 0 with η = 0.1. The slope is −6, so the step is w ← 0 − 0.1 × (−6) = 0.6. The new slope is −4.8, so w ← 0.6 + 0.48 = 1.08. Then 1.46, 1.77, 2.02, and so on. Each step shrinks the distance to 3 by a factor of 1 − 2η = 0.8. After 10 steps the weight is 2.68, still 0.32 away.
Now try η = 1.1. The factor is 1 − 2.2 = −1.2. Each step jumps past the bottom and lands 1.2 times as far away on the other side. The weight swings wider and wider. This is the first failure of training, and it comes from a step that is too long.
The sum in the rule runs over all N examples. For a million examples, one step costs a million gradient calculations. The lecture’s fix is stochastic gradient descent (SGD): pick one example at random, index nt, and step along its slope alone.
One example gives a rough sense of downhill, much like feeling the ground with a single toe. A step costs 1 example instead of N. The path wobbles, but it still heads down on average. In practice, people draw a small handful (a minibatch, often 32 to 256 examples) and average their slopes, which keeps most of the saving and smooths the wobble.
The slide ends on a warning: non-convex optimization problem. A convex loss, like the single hill above, has one bottom, and every downhill walk reaches it. The loss of a network with hidden units is not convex. It has many valleys, and which one you reach depends on where you start and how you walk. Try it. Click the map to choose a starting point, then press Walk.
The map is a toy loss over two weights; dark is low, bright is high. Green rings mark valley floors, the lowest one filled. Click or tap the map to move the start. Raise the noise to make steps stochastic. Raise the learning rate until the walk breaks.
Toy loss, not a trained network: a bowl plus two cosine ripples and a small tilt, so it has several valleys. Gradients are exact. With noise above 0, each step adds a random push to the slope; real SGD noise comes from which examples are drawn, so this is an illustration of its effect, not a model of it. A walk stops when the slope is tiny or after 500 steps.
Start A, B and C reach different valleys at the same learning rate. Some valley floors are higher than others, so where you start matters. The lecture states this plainly and moves on, and it is honest: nothing guarantees the lowest valley. Experience says the valleys that gradient descent finds are usually good enough for networks with enough hidden units.
Chapter 4
Work out the slope of every weight in a network with the chain rule, one layer at a time, and check it with real numbers
Gradient descent needs one number per weight: how much the loss changes if that weight moves a little. A network can hold millions of weights. We cannot afford to nudge each one and re-run the network to measure the change. That would take a million forward passes for every single step.
Picture a factory line of five stations. The final product comes out wrong. Who is to blame? You start at the end and ask each station: how much did you contribute to the error you see? Each station answers using what the station after it told it, plus what it did itself. One walk from the end of the line back to the start gives every station its share of blame. That walk is backpropagation.
The chain rule says: if A changes B and B changes C, then the change in C per change in A is the change of B per A, times the change of C per B. A bicycle with two gears is the usual picture: if the pedal turns the wheel twice and the wheel turns the road three times, the pedal turns the road six times. Slopes multiply along a chain.
Use the notation of Chapter 2. A weight Wij(l) only enters the loss through one number, the pre-activation aj(l) of unit j in layer l. So the chain rule gives two factors. The lecture gives the second a name: δnj(l) = ∂Rn/∂aj(l), the delta of the unit, which says how much the loss of example n changes if that unit’s pre-activation changes. Think of delta as the unit’s blame.
The result is easy to remember: the slope of a weight is the blame of the unit it feeds times the signal it carried. A wire that carried a big signal into a unit with a lot of blame has a steep slope.
How do we get delta for a hidden unit? Its pre-activation aj(l) reaches the loss only through the units in the next layer. So its blame is the sum of what each next-layer unit k tells it. Each message is that unit’s own blame, δk(l+1), times how strongly unit j’s output enters it. The next layer computes ak(l+1) = ∑r Wrk(l+1) σ(ar(l)), so changing aj changes it by Wjk(l+1) σ′(aj(l)), where σ′ is the slope of the bend.
At the very end of the chain, with squared loss and an output that is read straight from the last pre-activation, the starting blame is δ(L) = 2(a(L) − yn). This is the lecture’s boundary condition: twice the miss, with its sign. A network that overshoots has positive blame, and one that undershoots has negative blame.
Here is the smallest network that shows every step: one input, two hidden sigmoid units, one linear output, no biases. Use x = 1.5, target y = 1, first-layer weights (0.8, −0.6), second-layer weights (0.5, 0.9). All numbers are rounded to four places.
Forward. The sums are a1 = 0.8 × 1.5 = 1.2 and a2 = −0.6 × 1.5 = −0.9. The hidden outputs are z1 = σ(1.2) = 0.7685 and z2 = σ(−0.9) = 0.2891. The output is 0.5 × 0.7685 + 0.9 × 0.2891 = 0.6444. The loss is (0.6444 − 1)2 = 0.1264.
Backward. Start with the output blame: δ(2) = 2(0.6444 − 1) = −0.7112. The slopes of the output weights are blame times signal: −0.7112 × 0.7685 = −0.5466 and −0.7112 × 0.2891 = −0.2056. For the hidden blame we need the bend’s slope, σ′ = z(1 − z): 0.7685 × 0.2315 = 0.1779 and 0.2891 × 0.7109 = 0.2055. Then δ1(1) = −0.7112 × 0.5 × 0.1779 = −0.0633 and δ2(1) = −0.7112 × 0.9 × 0.2055 = −0.1315. The first-layer slopes are blame times input: −0.0633 × 1.5 = −0.0949 and −0.1315 × 1.5 = −0.1973.
Step through it yourself below. At the end of the walk the device also measures one slope the slow way, by nudging the weight and re-running the network, so you can see that the two agree.
Press Next step to reveal one stage at a time. Purple numbers are forward values. Yellow numbers are the backward blame and the slopes. Change the input or the target first if you like; every number is recomputed.
Exact arithmetic on the weights above (0.8, −0.6, 0.5, 0.9), which are chosen for the example and not trained. Slopes shown are for the one training example, with squared loss. The update at the last step uses a learning rate of 0.5.
The last step applies gradient descent with η = 0.5: the output weights become 0.7733 and 1.0028, the first-layer weights 0.8474 and −0.5013. Running the network again gives 0.9252 and a loss of 0.0056, down from 0.1264. One backward sweep, one step, and the loss fell by a factor of 22.
Chapter 5
See backpropagation as a second network run in reverse, count what it costs, and find out when the blame fades before it arrives
The slides titled “Backpropagation visually explained” boil the last chapter down to two lines: the blame at a hidden unit, and the blame at the output. Then the deck switches to pictures of the forward network and the same network run backward. The picture is the point. Backpropagation is a second pass over the same wires, with the arrows turned around.
On the forward pass, a signal enters at the left and each unit adds up its inputs, bends the sum, and passes it on. On the backward pass, blame enters at the right, as 2(output − target). Each unit adds up what the units to its right send back, multiplies by the slope of its own bend, and passes the result left. The weights are the same ones. Only the direction changes.
In practice nobody loops over units one at a time. A layer’s blame for a whole batch is one matrix. If layer l+1 holds a blame table Δ(l+1) of shape (B × nl+1), then the blame table of layer l is
The slope of the weights in layer l is then one more matrix multiply, Z(l−1)T Δ(l), of shape (nl−1 × nl): the same shape as the weight table itself, as it must be. Here is the whole thing for a tanh network with a linear output and squared loss. Note how few lines it is.
pythonimport numpy as np def forward(x, Ws): # x: (B, d); Ws[l]: (n_in, n_out) zs, as_ = [x], [] for W in Ws[:-1]: a = zs[-1] @ W # (B, n_out): the sums, kept for later as_.append(a); zs.append(np.tanh(a)) out = zs[-1] @ Ws[-1] # (B, K): linear output return zs, as_, out def backward(zs, out, y, Ws): B = len(y) delta = 2 * (out - y) / B # (B, K): blame at the output grads = [None] * len(Ws) grads[-1] = zs[-1].T @ delta # signal times blame for l in range(len(Ws) - 2, -1, -1): delta = (delta @ Ws[l + 1].T) * (1 - zs[l + 1] ** 2) # blame moves left grads[l] = zs[l].T @ delta return grads # one table per weight table
The forward pass multiplies each weight table once. The backward pass multiplies by each table twice: once to move the blame left, once to form the slopes. So one full step costs about three times a forward pass, however many weights there are. The naive way, nudging each weight and re-running the network, needs one forward pass per weight. For the 79,400-weight network of Chapter 1 that is 79,400 passes, against the 3 passes’ worth of work of backpropagation. The cost is paid in memory instead: the forward pass must store every sum and every output until the backward pass reads them.
Look again at the blame rule. At every layer the blame is multiplied by a weight and by the slope of the bend. Across L layers these factors multiply: the blame that reaches the first layer is the output blame times a long product of weights and slopes. A product of many numbers smaller than 1 collapses toward zero. A product of many numbers larger than 1 explodes. Either way, the early layers get a useless signal.
Sigmoid has a steepest slope of 0.25, so even in the best case each layer cuts the blame to a quarter. After 10 layers that is at most 0.2510, about one millionth. The device below runs this on a simple chain of units, one per layer, all sharing one weight, and prints the blame at each layer on a log scale.
Each bar is the size of the blame at one layer, as a fraction of the blame at the output (the rightmost bar, always 1). Every ten steps down the scale is a factor of ten. Choose a bend, then change the depth and the shared weight.
Illustrative: a chain of single units, input 0.5, every layer using the same weight, the blame at the output set to 1. Forward values and bend slopes are computed exactly, and each layer’s blame is the next layer’s times the weight times the bend slope. Real networks have many units per layer and different weights; the product of factors, and the way it can shrink or grow, is the same.
With sigmoid and a weight of 1, 12 layers already cut the blame at the first layer to 7.5 × 10−8 of the output blame. Tanh does far better in this setting, 0.24 after 12 layers, because its steepest slope is 1. ReLU has a slope of exactly 1 for positive sums, so with a weight of 1 the blame passes through untouched. Raise the weight to 2 on the ReLU chain and the blame doubles at every layer, reaching 2,048 times the output blame after 12 layers: the opposite failure. Real networks avoid both with careful starting weights and, later in this course, with extra paths that skip layers.
Chapter 6
Start from the simplest on-off unit, pair two of them into a pulse, and add pulses until a network has drawn a waveform
The second half of the lecture asks a different question. We know how to train a network. What can a trained network do? What shapes of function can it represent at all? To find out, the deck goes back to the oldest and simplest unit, one that does not bend smoothly at all. It makes a hard yes-or-no decision.
A threshold unit adds up its weighted inputs and compares the sum with a number T, the threshold. If the sum reaches T, the unit outputs 1. Otherwise it outputs 0. The lecture draws it as a circle with a sum sign, a threshold box, and a single output wire.
With one input, the weighted sum is just x (take w = 1). The unit outputs 0 for every x below T and 1 for every x from T upward. Its graph is a step: flat, a jump, flat. A step has no wiggle in it. It looks like a poor building block for a smooth waveform. Watch what two of them can do.
Take two threshold units with thresholds T1 and T2, where T1 is smaller. Send both into an output unit with weights +1 and −1. The output is step(x − T1) − step(x − T2). Left of T1, both steps are 0, so the output is 0. Between T1 and T2, the first step has turned on and the second has not: 1 − 0 = 1. Right of T2, both are on: 1 − 1 = 0. The result is a pulse, a block of height 1 that stands on the interval between the two thresholds.
Now give the output weights h and −h instead. The block has height h. With T1 = 0.25, T2 = 0.5 and h = 0.8: at x = 0.1 the output is 0; at x = 0.3 it is 0.8 − 0 = 0.8; at x = 0.7 it is 0.8 − 0.8 = 0. Two hidden units give one block of any width, at any place, with any height.
Now put several pulses side by side. Each pair of hidden units adds one more block, so N pulses use 2N hidden units, and the output is the sum of N blocks. Choose the block heights to follow a target function, one height per block. The sum is a staircase that hugs the target. Try approximating x2 on the interval from 0 to 1 with four blocks of width 0.25. The heights, taken at the block centres, are 0.1252 = 0.016, 0.3752 = 0.141, 0.6252 = 0.391 and 0.8752 = 0.766. The staircase is off by at most 0.23, at the right-hand edge of the last block. Eight blocks bring the worst gap down to about 0.12.
Signal-processing readers know this picture. It is exactly how an analogue-to-digital converter turns a smooth voltage into steps (see the quantisation lesson), and how the Haar wavelet builds a signal from blocks (see the wavelet lesson). A one-hidden-layer network of threshold units is a learned staircase. The slide that shows a wavy signal covered by blocks makes this point, and credits Bhiksha Raj for the figure.
The faint curve is the target signal. The warm curve is what the hidden units build. Choose a signal and a kind of unit, then raise the number of pieces. Purple ticks along the bottom mark where the hidden units switch on.
Toy signals made of sines on the interval 0 to 1 (a decaying 5-cycle tone, a chirp, and a mix of a 3-cycle and an 8-cycle tone). Heights and corners are read straight from the signal, not trained, so the error shown is a fair upper bound for what training could reach with the same units. Error is the root-mean-square gap divided by the root-mean-square of the signal, measured at 2,000 points.
Try the numbers. For the tone burst, 16 blocks (32 threshold units) leave an error of 55% of the signal’s strength. 40 blocks (80 units) bring it to 23%. The staircase gets better slowly, because each doubling of the blocks only halves the error. Now switch to ReLU. A ReLU unit is a straight ramp that starts bending at a chosen point, so a sum of ramps is a chain of straight pieces. With 40 ReLU units the error on the same burst is 6%. Straight pieces follow a slope. Flat steps cannot.
Chapter 7
Turn each threshold unit into a line on a map, then combine the lines into a polygon and the polygons into any shape you like
The sensor from Chapter 0 gives two numbers per reading, so each reading is a point on a map. A good rule marks a region of the map as “healthy”. An engineer might want the region to be a pentagon, because the manufacturer’s data sheet says normal operation lies inside certain limits. Can a network draw a pentagon? The lecture’s answer is a series of slides that build it up one line at a time.
Take a threshold unit with two inputs. It fires when w1x1 + w2x2 ≥ T. The edge of that region, where the sum equals T exactly, is a straight line. Every point on one side makes the unit fire and every point on the other side leaves it silent. So a threshold unit is a half-plane detector: it paints half of the map with a 1. The weights tilt the line, and the threshold slides it. The first slides of the series show a yellow half-plane appearing and rotating.
A layer of N such units is N lines, drawn on the same map. A point on the map gets a vector of N ones and zeros, one per line, telling you which side of each line it is on. The slides put small numbers in each patch of the map: how many of the lines fire there.
Now add one more unit on top, with weight 1 from every line unit and a threshold of N. The sum of its inputs is the number of lines that fire. The unit fires only when that number reaches N, which means every line fires. That is a logical AND: the point is on the right side of the first line, and the second, and the third, and all the rest. The set of points on the right side of every line is the intersection of the half-planes, and for lines it is always a convex polygon (a shape with no dents, like a pentagon).
A worked example with three lines makes the rule concrete. Let unit 1 fire when x ≥ 0, unit 2 when y ≥ 0, and unit 3 when x + y ≤ 1. The AND unit has threshold 3. The point (0.2, 0.2) fires all three: 3 ≥ 3, inside. The point (0.8, 0.8) fires units 1 and 2 but not 3 (0.8 + 0.8 = 1.6 is more than 1): the count is 2, outside. The point (−0.1, 0.3) fires 2 and 3 but not 1: count 2, outside. The triangle is the only place where the count reaches 3.
The number threshold is also a knob. Lower the threshold from N to N−1 and the AND turns into “all but one”. The region grows spikes beyond each edge, a star shape. Try it in the device.
Each purple line is one threshold unit. Darker purple on the map means more of the lines fire there. The green area is where the top unit fires. Switch lines on and off, and move the threshold. Then add the second shape.
Illustrative geometry: each pentagon is five lines tangent to a circle (centre and size chosen for the picture). Everything shown is exact threshold arithmetic: a line unit fires on one side, the AND fires when at least the chosen number of its lines fire, the OR fires when either shape does. Areas are counted on a 70 by 70 grid over the map.
One polygon is convex, so it cannot have a dent or a hole. Real regions often do. The fix is one more layer. Build several polygons, each with its own group of line units and its own AND unit. Then add a final unit with weight 1 from every AND and a threshold of 1. It fires when at least one AND fires: a logical OR. The set where it fires is the union of the polygons.
Switch the device to two shapes and count the units: 10 line units, 2 AND units and 1 OR unit, 13 in all, in three layers. The slides finish this build with a jagged blue shape and a tree of units above it: any shape that can be cut into convex pieces can be drawn this way, and any smooth curved region can be covered closely by small enough polygons. That is why the lecture says three layers are enough to draw any decision region.
It also settles what each layer is for. The first layer cuts the map with lines. The second layer joins lines into convex pieces. The third layer joins pieces into one region. A network does not need to be told this. Training finds weights that do jobs like these, although they are rarely as clean as the hand-built ones.
Chapter 8
Drop the AND, sum the lines instead, and watch a tower rise over the shape, then add towers until any region is covered
The last chapter built regions with three layers: lines, then ANDs, then an OR. Slide 23 puts the question that drives the next eleven slides. Is it possible to get the same decision region in two layers instead of three? Fewer layers would mean a simpler network. The answer is yes, at a price, and the way to see it is to stop asking each region for a yes-or-no verdict and look at the raw count instead.
Take N line units, laid out evenly around a circle of radius r. Each line is tangent to the circle, so the lines together wrap a regular polygon around it, a triangle for N = 3, a square for N = 4, and so on. Every unit fires on the side facing the circle. Now let the single output unit simply add up the N outputs, with no AND and no threshold. The output is the number of lines that fire at the point: a whole number from 0 up to N.
Where is the count N? Only inside the polygon, where every line fires. Step across one edge and one line stops firing, so the count drops to N−1. Move toward a corner and across two edges and it is N−2. The lecture draws this with four lines that cross in an X: the count is 4 in the centre and falls on the arms. Plot the count as a height above the map and you see a tower: a flat top over the polygon, with stepped sides that fall away.
Let the number of lines be large and spread evenly. Put a point at distance d from the centre. A line with its normal pointing at angle θ has the point on its firing side when d cos(θ − φ) ≤ r, where φ is the direction of the point. If d ≤ r, every line fires: the count is N. If d > r, the lines that fail are those whose normals point close to the point’s direction, within an angle of arccos(r/d) on either side. That removes the fraction 2 arccos(r/d) / 2π of the lines. So the count is
Put numbers in. At d = 1.2r, arccos(1/1.2) = 33.6°, so the fraction is 1 − 33.6/180 = 0.81. At d = 2r, arccos(0.5) = 60° and the fraction is 0.67. At d = 10r, arccos(0.1) = 84.3° and it is 0.53. Far away, arccos(0) = 90° and the fraction settles at exactly 0.5.
| Distance from the centre | Share of lines that fire | With N = 8 lines |
|---|---|---|
| Inside the circle (d ≤ r) | 100% | 8 |
| d = 1.2 r | 81% | 6.5 |
| d = 2 r | 67% | 5.3 |
| d = 4 r | 58% | 4.6 |
| d = 10 r | 53% | 4.3 |
| Very far away | 50% | 4.0 |
So the tower stands at N over the circle and slides down toward N/2 far away. The lecture states the result in one line: it is N inside the cylinder and N/2 outside. The slow slide down, the tail, is why the lecture specifies a small radius: a tower of small radius looks like a thin cylinder rising from a flat floor at N/2. Try it below.
Left: the map. Purple shade is the count of lines that fire; green is where the count reaches your threshold. Right: the count along one ray from the centre of a tower, as steps for the real lines and a dashed curve for the formula. Raise the lines, move the threshold, then add more towers.
Exact counts of N lines tangent to a circle of radius 0.2 on a map from −1 to 1; the three towers sit at fixed spots. The device sets the threshold to N for one tower and to 2.1 N for three (try the other values, the window is narrow) whenever you change the lines or the towers. Area is measured on a 70 by 70 grid and compared with the true area of the discs.
One tower marks one disc. For a region with several lobes, or one big irregular shape, put a tower at each place and let the output unit add all the towers together, then compare with a threshold. The slides call this “adding circles”: the final picture fills a pentagon with a crowd of small discs, and the result matches the pentagon. A shape drawn this way needs no AND and no OR layer. It needs more units. Every small disc costs N line units, and a pentagon needs many small discs.
Look at the three-tower case. Each tower alone is at least N/2 everywhere, so the sum has a floor of 3N/2. Inside one disc, that tower adds N and the other two add a little over N/2 each, so the sum is a little over 2N. Outside every disc the sum is lower, but not by much, because the tails of the other towers add up. The gap that the threshold has to fit into is thin. Try thresholds near 2N in the device and see how the green region responds.
Chapter 9
State what one hidden layer is guaranteed to do, say exactly what the guarantee leaves out, and count the units that a deeper network saves
Chapters 6 and 8 each built a different shape from simple units, and each time the recipe was the same: put many small bumps side by side and let the output unit add them up. Slide 35 gives that recipe a name and a promise. It shows a picture of a hidden layer feeding an output sum, next to a field of blue blocks of different heights, like a 3D bar chart that traces out a surface.
The lecture states it in one line: two-layer networks (one hidden layer, in the lecture’s counting) can compose arbitrary functions to arbitrary precision. This is the universal approximation theorem. Cybenko (1989) proved it for sigmoid hidden units, and Hornik (1991) widened it to a broad family of bends. In plain words: pick any continuous function on a bounded region and any error you can tolerate, however tiny. Some one-hidden-layer network gets within that error everywhere on the region.
The idea behind the proof is the one you already used. Each pair of hidden units is a bump. A sum of bumps is a bar chart. A bar chart with narrow enough bars follows a smooth curve as closely as you like. The theorem is the statement that you can always make the bars narrow enough.
Slide 36 adds the sentence that matters most in practice: the network may require infinitely many neurons in the hidden layer. The theorem says a good enough network exists. It does not say how big it must be. It does not say that gradient descent will find its weights. It does not say that the network will do well on data it has not seen. Chapter 6 gave a measured instance: to follow a chirp with threshold blocks, 16 blocks missed it by 83%, and following it better took many more. The promise is real and it is expensive.
Slide 37 gives the other half: deeper networks need fewer neurons for the same approximation error. The lecture states this without a proof. Here is a concrete case where you can count it exactly.
Take the tent map on the interval from 0 to 1: it rises from 0 at x = 0 to 1 at x = ½ and falls back to 0 at x = 1. Two ReLU units build it: T(x) = 2 ReLU(x) − 4 ReLU(x − ½). Check: at x = ¼ it is 2 × 0.25 − 0 = 0.5; at x = ½ it is 1; at x = ¾ it is 1.5 − 4 × 0.25 = 0.5; at x = 1 it is 2 − 2 = 0. The output of T always stays between 0 and 1.
That last fact lets us feed T into another copy of itself. T(T(x)) is a tent whose two halves are each squeezed into a tent: two peaks, four straight pieces. T(T(T(x))) has four peaks and eight pieces. Every layer of two more ReLU units doubles the number of pieces. After k layers, 2k hidden units draw a sawtooth of 2k straight pieces.
Now count what one hidden layer would need. A single ReLU unit adds one corner to a curve. A sum of M units has at most M corners, so at most M + 1 straight pieces. A curve with 2k pieces therefore needs at least 2k − 1 units in a single hidden layer. The device below shows both counts.
The warm curve is the output of a network with the chosen number of layers, two ReLU units each. Fainter curves show the output after each earlier layer. The bars show how many units a deep network uses, and how many a single hidden layer would need for the same curve.
Exact construction (Telgarsky 2016 gives the formal version; the lecture states the claim without proof). Each layer computes 2 ReLU(z) − 4 ReLU(z − 1/2) of the layer before it. The single-layer count is a lower bound: a sum of M ReLU units has at most M + 1 straight pieces. This builds one special curve by hand; it does not say how much depth a trained network uses on real data.
At k = 3, the deep network uses 6 units and draws 8 pieces; one layer needs at least 7. At k = 6 it is 12 units against at least 63. At k = 10 it is 20 against at least 1,023. At k = 20 it is 40 against more than a million. Depth multiplies, and width only adds.
That is the trade slide 37 points to. The polygon net of Chapter 8 spent a crowd of units on a shape that three layers draw with a handful. Width buys universality in one step. Depth buys it cheaply, if the training procedure of Chapter 5 can still carry blame through all those layers.
Chapter 10
Keep the numbers, the terms and the code that this lecture teaches, and see where to go next
A neural network is a linear model applied to features that it learns for itself. A layer takes a weighted sum and bends it. Stacked layers repeat the rule. Training minimises a loss by walking downhill, and backpropagation finds every weight’s slope with one backward sweep of blame. The second half of the lecture asks what such a network can draw. Threshold units make half-planes. AND and OR turn half-planes into any shape in three layers. Summing the lines instead gives a tower, and towers give two layers of universal approximation, at the price of width. Depth buys the same reach with far fewer units.
| What | Number | Why it matters |
|---|---|---|
| Best line on the ring | 61 of 80 right (76%); a distance feature: 80 of 80 | The right feature can beat any line (Chapter 0) |
| Weights, 784 inputs, 100 hidden, 10 classes | 78,400 + 1,000 = 79,400 (79,510 with biases) | The first table is almost all the cost (Chapter 1) |
| Softmax of the example scores | 38.1%, 28.1%, 33.9% | Shares are positive and add to 100% |
| Cross-entropy at 33.9%, 90%, 1% | 1.08, 0.11, 4.6 | Confident and wrong costs the most (Chapter 2) |
| Gradient descent on (w − 3)2 | error × (1 − 2η) per step; η = 0.1 gives 0.8; η > 1 diverges | A step that is too long fails (Chapter 3) |
| One backprop step, η = 0.5 | loss 0.1264 → 0.0056; slope −0.0949 matches the finite difference | Check your gradient numerically (Chapter 4) |
| Cost of backpropagation | about 3 forward passes, against 79,400 for nudging each weight | Why deep learning is affordable (Chapter 5) |
| Blame after 12 sigmoid layers, weight 1 | 7.5 × 10−8 of the output blame; sigmoid slope ≤ 0.25 | Early layers can stop learning |
| Staircase vs ramps on the tone burst | 16 blocks: 55%; 40 blocks: 23%; 40 ReLU units: 6% error | Straight pieces follow slopes better (Chapter 6) |
| Polygon with N sides around a circle | area N·tan(π/N)/π: 1.156 (N = 5), 1.055 (8), 1.013 (16) | Curves cost lines (Chapter 7) |
| Polygon net | N inside, about N/2 far away; N(1 − arccos(r/d)/π) between | A tower, from two layers (Chapter 8) |
| Tent map, k layers of 2 units | 2k units, 2k pieces; one layer needs ≥ 2k − 1 | Depth multiplies, width adds (Chapter 9) |
| Term | Meaning |
|---|---|
| Hidden unit | A weighted sum, then a bend. Its output is a learned feature. |
| Pre-activation a | The weighted sum before the bend. Backprop stores it. |
| Softmax, one-hot | Scores to shares that add to 1; a target with a single 1 in the true class. |
| Loss R | One number for how wrong the network is. Squared for regression, cross-entropy for classes. |
| Delta δ | The blame of a unit: how the loss changes with its pre-activation. |
| Threshold unit | Fires 1 when its weighted sum reaches T. In 2-D it detects a half-plane. |
| Universal approximation | One hidden layer can get as close as you like to any continuous function, given enough units. |
This is the hero of the page in about 20 lines of NumPy: six tanh units, one sigmoid output, cross-entropy loss, gradient descent on the 80-point ring. With the sigmoid and cross-entropy together, the blame at the output is simply p − y. A run of this exact script reaches 100% training accuracy by step 300, with the loss falling from 0.68 to 0.12, and to 0.009 by step 3,000.
pythonimport numpy as np rng = np.random.default_rng(0) a = rng.uniform(0, 2*np.pi, 80) r = np.r_[0.42*np.sqrt(rng.uniform(0, 1, 40)), rng.uniform(0.66, 0.92, 40)] X = np.c_[r*np.cos(a), r*np.sin(a)] # (80, 2) readings y = np.r_[np.zeros(40), np.ones(40)][:, None] # (80, 1) labels H = 6 W1, b1 = rng.normal(0, 1.1, (2, H)), np.zeros(H) # (2, H), (H,) W2, b2 = rng.normal(0, 0.5, (H, 1)), np.zeros(1) # (H, 1), (1,) for step in range(3000): A = X @ W1 + b1 # (80, H) the sums Z = np.tanh(A) # (80, H) hidden features p = 1 / (1 + np.exp(-(Z @ W2 + b2))) # (80, 1) probability of class 1 D2 = (p - y) / len(y) # (80, 1) blame at the output D1 = (D2 @ W2.T) * (1 - Z**2) # (80, H) blame moves left W2 -= 0.5 * Z.T @ D2; b2 -= 0.5 * D2.sum(0) W1 -= 0.5 * X.T @ D1; b1 -= 0.5 * D1.sum(0) print(((p > 0.5) == y).mean()) # training accuracy
Everything in this lecture is the base layer of the next ones. Convolutional and recurrent networks reuse the same backward sweep with a different wiring. Deep learning picks up where Chapter 9 leaves off. Attention and the transformer, in the attention lesson, are layers of the same family. Convex neural networks returns to Chapter 3’s warning, that the loss is non-convex.
Now press Present or Teach and explain, from memory, how blame travels back through two layers with the numbers of Chapter 4, and why a pentagon needs six units in three layers but a crowd of units in two. Then go back to the network at the top, set the pattern to Spiral, and find how many hidden units it takes before the boundary bends around both arms.
Re-taught from Lecture 15 of Stanford EE269, Signal Processing for Machine Learning, by Mert Pilanci (Stanford University, March 2019). Course site: web.stanford.edu/class/ee269. Slides: web.stanford.edu/class/ee269/slides.html. The decision-region figures in the lecture credit Bhiksha Raj. All text, numbers, devices and code on this page are our own re-telling.