ML / DL Refresher, Part 2

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.

Train three models on XOR

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

A Line Cannot Learn XOR

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.

Two lines make a line

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.

Say it aloud

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.

x
x the input: the two numbers of one scene.
W1
W-one the weights of layer one.
b1
b-one the bias of layer one, one number per output.
W2
W-two the weights of layer two.
b2
b-two the bias of layer two.
W2W1
W-two W-one one matrix: the product of the two weight matrices.
W2b1 + b2
W-two b-one plus b-two one constant vector.
In plain words

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 numbers

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.

Fold the plane with one ReLU

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%.

0%

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.

The road

  1. The MLP: one layer is a matrix, a bias and a bend; track the shapes.
  2. Activations: why sigmoid stops deep nets learning, and ReLU does not.
  3. Backprop: the chain rule, by hand, on a net you can hold.
  4. Optimizers: momentum and Adam, raced down a narrow valley.
  5. CNNs: one small kernel, reused across an image.
  6. Sequences: RNN, LSTM and attention.
  7. Generative models: VAE, GAN, diffusion, and the reparameterization trick.
  8. Uncertainty: an ensemble that knows where it has no data.
  9. Field guide: numbers, checklist, code, links, credit.
Why can two linear layers with nothing between them not solve XOR?

Chapter 1

The MLP: Shapes Through Layers

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 φ.

Say it aloud

a equals phi of W x plus b.

a
a the activation: the layer's output, one number per unit.
φ
phi the activation function, ReLU here.
W
W the weight matrix, shape (d-out, d-in): one row of weights per output unit.
x
x the input vector, d-in numbers long.
b
b the bias, one number per output unit.
In plain words

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 numbers

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.

Trace the shapes, count the weights

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.

128
32

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.

A fully connected layer takes 784 inputs and has 128 outputs. What is the shape of W?

Chapter 2

Activations and the Vanishing Gradient

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.

ActivationOutput rangeLargest slopeSlope far from 0
Sigmoid0 to 10.25near 0 (it saturates)
Tanh−1 to 11near 0 (it saturates)
ReLU, max(0, z)0 and up11 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.

Say it aloud

Sigma-prime of z equals sigma of z times one minus sigma of z.

σ′(z)
sigma-prime of z the slope of the sigmoid at z: how far the output moves per unit of z.
σ(z)
sigma of z the sigmoid's output, 1/(1 + e−z), between 0 and 1.
1 − σ(z)
one minus sigma of z what is left to reach 1.
In plain words

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.

With numbers

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.

Watch the gradient fade with depth

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.

10
0.0

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.

Why are deep nets of sigmoid units hard to train?

Chapter 3

Backpropagation: The Chain Rule With Bookkeeping

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.

Say it aloud

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.

∂L/∂w1
d-L by d-w-one the gradient we want: how fast L changes as w1 grows.
∂L/∂ŷ
d-L by d-y-hat the slope of the loss: ŷ − y.
∂ŷ/∂a
d-y-hat by d-a the slope of the output layer: w2.
∂a/∂z1
d-a by d-z-one the slope of ReLU: 1 if z1 > 0, else 0.
∂z1/∂w1
d-z-one by d-w-one the slope of z1 = w1x in w1: x.
·
times multiply the local slopes along the path.
In plain words

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.

With numbers

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.

Push values forward, gradients back

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.

0.5

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.

In the worked example, ∂L/∂w1 = 4. What does the 4 tell you?

Chapter 4

Momentum and Adam

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.

Say it aloud

v becomes beta v plus g; then w becomes w minus eta v.

v
v the velocity: a fading sum of past gradients, one number per weight.
←
becomes overwrite the old value with the new one.
β
beta the memory, 0.9 here: each step keeps 90% of the old velocity.
g
g the gradient of the loss for this batch.
w
w the weight that training changes.
η
eta the learning rate.
In plain words

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 numbers

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.

Race three optimizers down a narrow valley

Grey is SGD, orange is momentum, teal is Adam, from the same start. Press Run, then raise η until each one breaks.

0.05

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.

What does Adam add on top of momentum?

Chapter 5

Convolution: One Small Kernel, Reused Everywhere

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.

Slide a kernel over a small image

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.

Say it aloud

out equals the floor of n plus two p minus k, over s, plus one.

out
out the width of the feature map.
⌊ ⌋
the floor of round down to a whole number.
n
n the image width in pixels.
p
p the padding: zeros added on each side, so 2p in total.
k
k the kernel width.
s
s the stride: pixels the kernel jumps each step.
In plain words

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.

With numbers

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.

What does weight sharing buy a convolution?

Chapter 6

Sequences: RNN, LSTM and Attention

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.

Say it aloud

Attention of Q, K, V equals softmax of Q times K-transpose over root d, times V.

Attention
attention the output: one new vector per token.
Q
Q the queries, one row per token.
KT
K-transpose the keys, turned so each query meets each key in a dot product.
√d
root d the square root of the key length; it keeps the scores small.
softmax
softmax turns each row of scores into weights of 0 or more that sum to 1.
V
V the values, one row per token.
In plain words

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 numbers

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.

Pick a query, read its attention

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.

ModelSteps between token 1 and token 100Trains all steps at once
RNN99No
LSTM99, on a protected pathNo
Transformer1Yes

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.

For one query token, what do its softmax attention weights always do?

Chapter 7

Generative Models and the Reparameterization Trick

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.

ModelCore ideaKnown weakness
K-meansClustering: give each point to its nearest centre, move each centre to its points' mean, repeat.You choose the number of clusters.
PCADimension reduction: keep the directions of largest variance.Linear only.
VAEAn encoder maps data to a bell curve over codes; a decoder rebuilds the data.Samples tend to be blurry.
GANA generator makes fakes; a discriminator tries to spot them.Unstable training, mode collapse.
DiffusionAdd 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.

Say it aloud

z equals mu plus sigma times epsilon.

z
z the latent code the decoder receives.
μ
mu the mean the encoder outputs for this input.
σ
sigma the spread the encoder outputs, above 0.
ε
epsilon noise from a standard bell curve (mean 0, spread 1), drawn outside the network.
In plain words

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 numbers

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.

Move the randomness outside

Top: fixed noise draws ε. Bottom: the codes z they become. Drag μ and σ; the noise stays put, so each z moves smoothly.

1.5
0.50

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 = μ + σε.

Why does a VAE need the reparameterization trick?

Chapter 8

Uncertainty: Knowing When You Do Not Know

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.

KindWhat it isDoes more data help?
AleatoricNoise in the world, like a blurry sensor.No
EpistemicThe 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).

Say it aloud

s of x squared equals one over M times the sum over m of f-m of x minus f-bar of x, squared.

s(x)2
s of x squared the variance of the ensemble at x; its root s is the spread.
1/M
one over M divide by the number of networks, 5 here.
Σm
the sum over m add one term for each network.
fm(x)
f-m of x network m's prediction at x.
f̄(x)
f-bar of x the mean of all M predictions at x.
In plain words

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.

With numbers

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.

Open a gap in the data

Blue dots are training data. Thin lines are five networks, and the pink band is the mean ± 2s. Widen the gap.

0.45

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.

MethodIdea
Bayesian nets, Gaussian processesKeep a distribution over weights or functions; predict a distribution.
Dropout at test timeDrop random units, predict many times, read the spread.
EnsemblesTrain several nets; their disagreement is the doubt.
Conformal predictionWrap 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.

Five networks agree on familiar inputs but fan out on a new one. Which uncertainty does the spread show?

Chapter 9

Field Guide

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.

TermOne lineNumber to remember
NonlinearityA bend between layers; without it, layers collapse to one.XOR: line 24 of 48, ReLU net 48 of 48
Layera = φ(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
BackpropMultiply local slopes from the loss back to each weight.Worked net: ∂L/∂w1 = 4
Momentumv ← βv + g, w ← w − ηv.β = 0.9: steady steps grow 10 times
AdamDivide 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
Attentionsoftmax(QKT/√d)V: a weighted average of values.Scores 8, 4, 0 at d 16: 0.67, 0.24, 0.09
Reparameterizationz = μ + σε, noise drawn outside the net.Slope of z in σ is ε
Ensemble spreadThe root of the mean squared distance from the mean prediction.Gap example: 0.14 to 1.01

Checklist before you train

  1. Put an activation between every pair of linear layers.
  2. Print the shape after each layer once.
  3. Use ReLU (or a variant) in hidden layers, and count dead units.
  4. Check one gradient against a finite difference.
  5. Plot the loss per step; if it grows by a steady factor, lower η.
  6. For a robot, report a spread with each prediction.

The core, as code

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]

Keep going

The takeaway. Stack layers with a bend between them, define a loss, multiply local slopes back to every weight, and step with momentum or Adam. Change the layers for images or sequences, change the loss to generate. Then ask the model how sure it is.

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.

Credit and source

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.

Introduction to Robot Learning · CMU 16-831 · Lecture 4
The course site · Slides PDF · Back to Gleams