A straight line gets XOR wrong: logistic regression stalls at the coin-flip loss, 0.69. One hidden layer with a ReLU gets all 48 points right. Depth plus a bend, trained by the chain rule, is the engine in every network a robot runs.
Pick a model, then press Train. Watch the loss and the shaded region. Then we build, piece by piece, the layer, the activation, backprop, the optimizer, and the networks for images, sequences, new samples and doubt.
You need Part 1 (a linear model, a loss, gradient descent) and a little Python. We build the rest from zero.
Based on Lecture 4 of CMU 16-831: Introduction to Robot Learning (Spring 2024), taught by Guanya Shi. Slides: Lecture 4 PDF, on the lectures page. It follows Lecture 3, Refresher Part 1.
A real training run in your browser: 48 points in four clusters, cross-entropy loss, 800 steps of full-batch gradient descent, 6 hidden units. The data and the starting weights are a fixed toy, made for this page.
Chapter 0
See why stacked linear layers stay one line, and how one bend fixes it
Your robot sees four kinds of scene. Two mean stop, two mean go. On a square, "stop" sits at corners (0,0) and (1,1), and "go" at (0,1) and (1,0). This pattern is XOR, short for "exclusive or".
A linear model takes a weighted sum of the inputs, adds a constant, and cuts the plane with one straight line. No line puts both stop corners on one side and both go corners on the other. In the hero, the line gets 24 of 48 points right.
Try two linear layers. Call the input x. Layer one multiplies by a weight matrix W1 and adds a bias b1. Layer two does the same with W2 and b2.
W-two times the bracket W-one x plus b-one, plus b-two, equals W-two W-one times x, plus W-two b-one plus b-two.
Run x through layer one, then layer two, and multiply out the bracket. What is left is one matrix times x plus one constant: a single linear layer.
With made-up one-number layers: W1 = 2, b1 = 1, W2 = 3, b2 = −1. Two layers give 3(2x + 1) − 1 = 6x + 2. At x = 1 both sides give 8. Still one line.
So depth alone buys nothing. The fix is a nonlinearity, a bent function between the layers. The simplest is ReLU: it keeps a positive number and turns a negative number into 0.
Left: the four scenes. Right: where a hidden layer of two units sends them, and the output's cut. Drag the bend from 0 to 100%.
Hand-set weights. A classic XOR solution: h1 = ReLU(x1 + x2), h2 = ReLU(x1 + x2 − 1), output h1 − 2h2, cut at 0.5. At bend b, the negative side keeps a slope of 1 − b.
With no bend, the four corners land on one straight line, with stop at both ends and go in the middle. No cut splits them. The ReLU folds the negative half onto zero. That lifts (0,0) off the line, and one straight cut works.
Symptom: a two-class model's loss stalls near 0.69 and never falls.
Measure: 0.69 is ln 2, the loss of a coin flip. Print the layers and check for an activation between each pair.
Fix: add the missing activation. A forgotten one turns a deep net into a linear model.
Chapter 1
Follow one image through matrix, bias and bend, and count where the weights live
A handwritten digit is 28 by 28 pixels. Flatten it and you get 784 numbers. You want 10 scores, one per digit. A multilayer perceptron (MLP) gets there with a stack of layers. Each layer multiplies by a weight matrix, adds a bias and bends the result.
Name the parts first. The input is a vector x. The layer holds a weight matrix W and a bias vector b. The raw output is the pre-activation z. The bent output is the activation a, and the bending function is φ.
a equals phi of W x plus b.
For each row of W, multiply it number by number with x and add up. Add that unit's bias from b. Pass the result through phi to get that unit's a.
With made-up numbers, x = (1, 2, −1). The row (−1, 2, 1) with bias 0 gives −1 + 4 − 1 = 2, so a = 2. The row (1, −1, 0) gives 1 − 2 = −1, and ReLU makes a = 0.
Stack two layers: 784 to 128 to 10. Then W1 has shape (128, 784) and W2 has shape (10, 128). A softmax at the end turns the 10 scores into probabilities that sum to 1. A batch of N images is an (N, 784) matrix, and one matrix multiply handles all N rows.
Top: the tensors one batch makes, blue for data and pink for activations. Bottom: the weights, warm orange. Change the hidden width and the batch size.
Shapes and counts are exact for a 784 to H to 10 MLP. The boxes use a square-root scale so the small ones stay visible.
At H = 128 the net has 101,770 weights, and W1 with b1 holds 98.7% of them. The batch size changes the activations, never the weights.
Symptom: "shapes (32,784) and (128,784) not aligned".
Measure: print each tensor's shape after each layer.
Fix: W is (d-out, d-in) and multiplies one column x. With a batch stored as rows, write X WT + b.
Now compute a forward pass yourself, on numbers you can check by hand.
Chapter 2
Multiply small slopes through many layers and watch the training signal disappear
Training sends a signal backwards through the net (Chapter 3). At each layer, the slope of that layer's activation multiplies the signal. If the slopes are small, the signal shrinks layer by layer. This is the vanishing gradient.
| Activation | Output range | Largest slope | Slope far from 0 |
|---|---|---|---|
| Sigmoid | 0 to 1 | 0.25 | near 0 (it saturates) |
| Tanh | −1 to 1 | 1 | near 0 (it saturates) |
| ReLU, max(0, z) | 0 and up | 1 | 1 if z > 0, 0 if z < 0 |
The sigmoid squashes any number z into the range 0 to 1. Call its output σ(z). Its slope has a neat form.
Sigma-prime of z equals sigma of z times one minus sigma of z.
Find the output sigma of z, then multiply it by what is left to 1. Two numbers that add to 1 have the largest product at one half each, so the slope never passes 0.25.
At z = 0, σ = 0.5 and the slope is 0.5 × 0.5 = 0.25. At z = 2, σ = 0.881 and the slope is 0.881 × 0.119 = 0.105. Ten sigmoid layers at z = 0 pass on 0.2510, about 0.00000095, of the signal.
Left: the activation (pink) and its slope (purple). Right: the share of the gradient each layer gets, on a log scale. Pick an activation, then drag the depth and z.
Illustrative: every layer gets the same z and a weight of 1, so layer 1 gets the slope to the power of the depth. Real nets mix z values; the product behaves the same way.
ReLU has slope exactly 1 for any positive z. It passes the signal at full strength, which is why deep nets train well with it. Its flaw is the other side: for negative z the slope is 0.
Symptom: some hidden units output 0 for every input, and their weights never change. This is a dead ReLU.
Measure: over one batch, count each unit's share of zero outputs. 100% means dead.
Fix: Leaky ReLU (a slope of 0.01 below zero), a lower learning rate, or a better weight start.
Chapter 3
Run a tiny net forward, then trace blame back from the loss to each weight
You have a loss. Each weight now asks: if I grow a little, does the loss go up or down, and how fast? That number is the weight's gradient. Backpropagation finds every gradient in one sweep, from the loss back to the input.
Take the smallest real net. The input is x = 2. A hidden unit multiplies by the weight w1 = 0.5 to get z1, then ReLU gives a. The output multiplies by w2 = −1 to give the prediction ŷ. The loss is L = ½(ŷ − y)2, with target y = 1.
d-L by d-w-one equals d-L by d-y-hat, times d-y-hat by d-a, times d-a by d-z-one, times d-z-one by d-w-one.
Start at the loss L. Walk back one box at a time and multiply in that box's local slope. When you reach w1, the product is its gradient. This is the chain rule.
Forward: z1 = 0.5 × 2 = 1, a = 1, ŷ = −1, L = ½(−2)2 = 2. Backward: ∂L/∂ŷ = −2. Times w2 = −1 gives 2. Times the ReLU slope 1 gives 2. Times x = 2 gives ∂L/∂w1 = 4.
Press Forward: pink values flow left to right. Press Backward: purple gradients flow right to left. Then drag w1 below 0 and run both again.
The net and its numbers are the worked example above. The page computes every value live from the slider.
The gradient 4 says: grow w1 and the loss grows 4 times as fast. So gradient descent moves w1 down. With a learning rate of 0.1, w1 becomes 0.1, w2 becomes −0.8, and the loss falls from 2 to 0.67.
The bookkeeping is the trick. Backprop saves each forward value and reuses each partial product, so the backward sweep costs about one or two forward passes. That is why a net with a billion weights can train.
Symptom: the code runs, but the loss rises or wobbles.
Measure: a gradient check. Nudge one weight by h = 0.00001 both ways and compute (L(w + h) − L(w − h))/(2h).
Fix: it must match your gradient to several digits. If not, find the box whose local slope is wrong.
Chapter 4
Race three optimizers down a narrow valley and find where each one breaks
Lecture 3 taught gradient descent: step against the gradient, scaled by a learning rate η (eta). Deep nets use stochastic gradient descent (SGD): each step uses the gradient of a small random batch, not the whole dataset.
SGD struggles in a long, narrow valley: steep across, gentle along. A learning rate that is safe on the steep side crawls along the gentle side. A larger one makes the steep side bounce from wall to wall and blow up. SGD blows up once η times the steepness passes 2.
Momentum remembers the direction. It keeps a running velocity v, a sum of past gradients that fades by a factor β (beta) each step. Call the batch gradient g and the weight w.
v becomes beta v plus g; then w becomes w minus eta v.
Shrink the old velocity v by beta and add this step's gradient g. Then move the weight w against v, scaled by eta.
With beta 0.9 and a steady g = 1, v grows 1, 1.9, 2.71, 3.44 and levels off at 1/(1 − 0.9) = 10. Along the gentle side the step grows ten times. Across the steep side g flips sign each step, the terms cancel, and v stays near 0.53.
Adam adds a step size for each weight. It keeps a running average of each weight's squared gradient and divides that weight's step by its square root. Big gradients get smaller steps, and tiny ones get bigger steps. So each step stays near η in length, whatever the scale.
Grey is SGD, orange is momentum, teal is Adam, from the same start. Press Run, then raise η until each one breaks.
Illustrative toy without batch noise: loss = ½(0.5p2 + 20q2), 80 steps, momentum β = 0.9, Adam with its usual 0.9 and 0.999.
At η = 0.10, SGD stops converging: 0.10 × 20 = 2, so the steep side bounces wall to wall forever. Above that, it blows up. Momentum lasts until about 0.19, which is 2 × (1 + 0.9)/20. Adam survives the whole slider, because its step does not grow with the gradient.
Symptom: the loss jumps to NaN after some steps.
Measure: plot the loss per step and look for growth by a steady factor each step.
Fix: lower η by 3 to 10 times, or clip the gradient's size.
Chapter 5
Slide a 3 by 3 kernel over an image and predict the size of what comes out
A colour image of 200 by 200 pixels is 120,000 numbers. A fully connected first layer of 1,000 units needs 120 million weights. It also learns a cup on the left and a cup on the right as two separate patterns.
A convolutional neural network (CNN) builds in two assumptions. Locality: a pixel's meaning depends mostly on its neighbours, so each output looks at a small patch. Weight sharing: one small grid of weights, the kernel, slides over the whole image. The output is a feature map.
Left: an 8 × 8 image and the patch under the kernel (orange). Right: the feature map. Press Play, then change the kernel, the stride, the padding or the shift.
A toy image and three textbook kernels. Each output is the sum of patch times kernel, computed live.
Two knobs set the output size. The stride is how far the kernel jumps each step. The padding is a border of zeros around the image. Call the image width n, the kernel width k, the padding p and the stride s.
out equals the floor of n plus two p minus k, over s, plus one.
Add the padding p to both sides of n. Subtract the kernel width k: that is how far the kernel can travel. Divide by the stride s, round down, and add 1 for the first position.
Our image: n = 8, k = 3. With p = 0 and s = 1: (8 − 3)/1 + 1 = 6. With s = 2: ⌊5/2⌋ + 1 = 3. With p = 1 and s = 1: (8 + 2 − 3) + 1 = 8, the input's size.
Press Shift image: the image moves one pixel right, and the feature map moves with it. This is translation equivariance. A pooling layer then keeps the largest value in each 2 × 2 block. It shrinks the map and makes the final answer invariant: shift the cup, still "cup". LeNet (1998) stacked conv, pool, conv, pool, then fully connected layers.
Symptom: the fully connected layer after the convolutions throws a size error.
Measure: apply the output-size formula to each conv and pool layer by hand.
Fix: set padding and stride so the sizes work, and compute the flatten size from the formula.
Chapter 6
Carry the past step by step, then let every step look at every other one
A robot's joint sensors report 100 times a second. To predict the next reading, the model needs a summary of the past. A recurrent neural network (RNN) reads one step at a time and carries a hidden state, a vector that sums up what it has seen.
Chapter 2's disease returns. A link between step 1 and step 100 sends the gradient back through 100 multiplications. At 0.9 per step, 0.9100 is 0.00003. At 1.1 per step it is 13,780, and the gradient explodes. The LSTM (long short-term memory) adds a separate cell state with gates that choose what to write, keep and read. The signal passes many steps and nothing squashes it.
The transformer drops the step-by-step state. Every token looks straight at every other token. Three linear layers turn each token into a query (what I look for), a key (what I offer) and a value (what I pass on). Stack them as matrices Q, K and V, with key length d.
Attention of Q, K, V equals softmax of Q times K-transpose over root d, times V.
For one query, take its dot product with every key in K. Divide by root d. Softmax turns the scores into weights. The output is the weighted average of the values in V.
With made-up numbers: scores 8, 4 and 0, and d = 16, so divide by 4 to get 2, 1, 0. Softmax gives 0.67, 0.24 and 0.09. With values 10, 20 and 30, the output is 14.2.
Tap a word to make it the query. The bars are its weights over all ten words. Turn off the root-d scaling and watch one word take everything.
Hand-made scores with d = 16, for illustration; a trained model learns its own. The weights are a real softmax and always sum to 1.
Without the root-d division, scores 8, 4, 0 give weights 0.98, 0.02 and 0.0003. One key takes everything, and the gradient to the others nearly vanishes. Attention has no sense of order, so a transformer adds a positional embedding to each token.
| Model | Steps between token 1 and token 100 | Trains all steps at once |
|---|---|---|
| RNN | 99 | No |
| LSTM | 99, on a protected path | No |
| Transformer | 1 | Yes |
Symptom: training loss turns to NaN on long sequences.
Measure: log the gradient's size per step; an exploding one grows by a steady factor.
Fix: clip the gradient's size, or switch to an LSTM or attention.
Chapter 7
Learn where data lives, sample new examples, and move the randomness out of the way
Every model so far had labels. Unsupervised learning finds structure without them. A generative model learns where the data lives, so it can draw new examples. For robots this is central: imitation learning fits a generative model of the expert's actions, given what the robot sees.
| Model | Core idea | Known weakness |
|---|---|---|
| K-means | Clustering: give each point to its nearest centre, move each centre to its points' mean, repeat. | You choose the number of clusters. |
| PCA | Dimension reduction: keep the directions of largest variance. | Linear only. |
| VAE | An encoder maps data to a bell curve over codes; a decoder rebuilds the data. | Samples tend to be blurry. |
| GAN | A generator makes fakes; a discriminator tries to spot them. | Unstable training, mode collapse. |
| Diffusion | Add noise step by step, then learn to remove it step by step. | Slow to sample: many steps. |
A VAE (variational autoencoder) encodes an input into a mean μ (mu) and a spread σ (sigma). Then it draws a code z from that bell curve. Training needs the gradient of the loss with respect to μ and σ, but a random draw has no slope. So draw a noise number ε (epsilon) from a standard bell curve, outside the network.
z equals mu plus sigma times epsilon.
Draw epsilon first. Stretch it by sigma and shift it by mu. Now z moves smoothly with mu and sigma: nudge mu and z moves the same amount; nudge sigma and z moves epsilon times as much.
With made-up numbers: μ = 1.5, σ = 0.5, ε = −0.8. z = 1.5 + 0.5 × (−0.8) = 1.1. The slope of z with respect to σ is ε = −0.8.
Top: fixed noise draws ε. Bottom: the codes z they become. Drag μ and σ; the noise stays put, so each z moves smoothly.
Illustrative: 24 noise draws; the marked one is fixed at −0.8 to match the worked example.
The VAE trains on the ELBO, a lower bound on how likely the data is. It has a rebuild term, plus a KL term that pulls each code's bell curve toward the standard one. Diffusion uses the same trick in its noising steps.
Symptom: the decoder learns, but the encoder's weights never change.
Measure: print the encoder's gradient size. It is zero, or missing.
Fix: the code samples z with a random call inside the graph. Draw ε outside and write z = μ + σε.
Chapter 8
Train five networks, measure where they disagree, and treat the spread as doubt
A robot arm reaches for a cup on a table it has never seen. A confident wrong grasp knocks the cup over. "I am not sure, look again" saves it. Uncertainty quantification (UQ) makes a network report how sure it is, not only what it predicts.
| Kind | What it is | Does more data help? |
|---|---|---|
| Aleatoric | Noise in the world, like a blurry sensor. | No |
| Epistemic | The model's ignorance: it has not seen this case. | Yes, data there shrinks it |
An ensemble trains several networks from different random starts. Where they agree, it is sure; where they disagree, it is not. Call the number of networks M, network m's prediction at input x fm(x), and their mean f̄(x).
s of x squared equals one over M times the sum over m of f-m of x minus f-bar of x, squared.
Ask all M networks for a prediction at x and find the mean f-bar. Square each network's distance from the mean, add them, and divide by M. The root, s, is the spread.
Five made-up predictions near the data: 1.0, 1.2, 0.8, 1.1, 0.9. The mean is 1.0 and s = √0.02 = 0.14. In a gap with no data: 0.2, 1.5, −0.6, 2.3, 0.6. The mean is 0.8 and s = √1.02 = 1.01, seven times wider.
Blue dots are training data. Thin lines are five networks, and the pink band is the mean ± 2s. Widen the gap.
Illustrative: each member is a small random-feature network (30 tanh units, ridge fit) trained on a bootstrap resample. The fits are real and run in your browser.
| Method | Idea |
|---|---|
| Bayesian nets, Gaussian processes | Keep a distribution over weights or functions; predict a distribution. |
| Dropout at test time | Drop random units, predict many times, read the spread. |
| Ensembles | Train several nets; their disagreement is the doubt. |
| Conformal prediction | Wrap any model; output a set that holds the truth with probability at least 1 − α. |
Networks are also fragile. A tiny, chosen change to an input, invisible to a person, can flip a classifier's answer. Verification tries to prove that a network behaves well on a whole region of inputs.
Symptom: a policy acts with high confidence on scenes unlike its training data.
Measure: track the ensemble spread live, against its spread on held-out training-like scenes.
Fix: past a threshold, slow down, ask for help, or collect data there.
Chapter 9
Keep the numbers, the checklist and the core code in one place
Every model in this lesson is the same recipe: differentiable layers, a nonlinearity, a loss, and backprop with an optimizer. A CNN, a transformer and a VAE change which layers and which loss. The machinery stays.
| Term | One line | Number to remember |
|---|---|---|
| Nonlinearity | A bend between layers; without it, layers collapse to one. | XOR: line 24 of 48, ReLU net 48 of 48 |
| Layer | a = φ(Wx + b), W is (d-out, d-in). | 784 to 128 to 10: 101,770 weights |
| Sigmoid slope | σ(1 − σ), never above 0.25. | 10 layers: 0.2510 ≈ 10−6 |
| Backprop | Multiply local slopes from the loss back to each weight. | Worked net: ∂L/∂w1 = 4 |
| Momentum | v ← βv + g, w ← w − ηv. | β = 0.9: steady steps grow 10 times |
| Adam | Divide each weight's step by the root of its mean squared gradient. | Common default η = 0.001 |
| Conv output size | ⌊(n + 2p − k)/s⌋ + 1. | n 8, k 3, p 0, s 1: 6 |
| Attention | softmax(QKT/√d)V: a weighted average of values. | Scores 8, 4, 0 at d 16: 0.67, 0.24, 0.09 |
| Reparameterization | z = μ + σε, noise drawn outside the net. | Slope of z in σ is ε |
| Ensemble spread | The root of the mean squared distance from the mean prediction. | Gap example: 0.14 to 1.01 |
The hero's network, trained from scratch with NumPy: forward, backward, momentum.
pythonimport numpy as np rng = np.random.default_rng(0) X = np.array([[0,0],[1,1],[0,1],[1,0]], float) # (4, 2) the four XOR scenes y = np.array([0, 0, 1, 1], float) # (4,) stop = 0, go = 1 W1, b1 = rng.normal(0, 1, (6, 2)), np.zeros(6) # W is (d_out, d_in) W2, b2 = rng.normal(0, 1, 6), 0.0 vel = [np.zeros_like(p) for p in (W1, b1, W2)] + [0.0] lr, beta = 0.1, 0.9 for step in range(2000): z1 = X @ W1.T + b1 # (4, 6) pre-activations a1 = np.maximum(0, z1) # ReLU: the bend p = 1 / (1 + np.exp(-(a1 @ W2 + b2))) # (4,) probability of go d = (p - y) / len(y) # dL/dlogit for cross-entropy gW2, gb2 = a1.T @ d, d.sum() # chain rule, output layer dz1 = np.outer(d, W2) * (z1 > 0) # back through W2, then ReLU's slope gW1, gb1 = dz1.T @ X, dz1.sum(0) grads = [gW1, gb1, gW2, gb2] vel = [beta * v + g for v, g in zip(vel, grads)] # momentum W1, b1, W2, b2 = [w - lr * v for w, v in zip((W1, b1, W2, b2), vel)] print(np.round(p, 3)) # near [0, 0, 1, 1]
Now press Present or Teach and explain from memory: why XOR needs a bend, the backprop of the tiny net, and why sigmoid nets stall. Then go back to the hero and train all three models again. Say why only one of them leaves the coin-flip loss.
This lesson re-teaches Lecture 4 of CMU 16-831, Introduction to Robot Learning (Spring 2024), taught by Guanya Shi. The course site is 16-831-s24.github.io, and the slides are the Lecture 4 PDF. The explanations, toy models and devices here are our own.