Index Ai Academy
Foundation · Putting it together

Training a small network

The backward pass in matrix form, gradient checks, a full training loop, and reading loss curves.

About 45 minutes · Free lesson

What it covers6

Why it matters

Lesson 110 ran a network forward with weights someone had already chosen. This lesson chooses them. Training is the loop of lesson 79 with lesson 110's network inside it: forward pass, loss, backward pass, update, repeated. The only new piece is the backward pass written for whole matrices at once, and even that is old: it's lesson 81's "multiply along the path" with the matrix products of lesson 56, and its first line is lesson 105's p − y. Each line can be checked two ways, by its shape and by a numerical slope, so nothing has to be taken on trust. At the end the network learns to read trail signs from 24 examples and is judged on 12 it never saw, and you'll be able to read the loss curve of a real training run and say whether its learning rate is right.

What you'll be able to do

  • Write the backward pass in matrix form, dZ₂ = P − Y down to dW₁ = Xᵀ dZ₁, and justify each line by its shape
  • Run the full loop, forward, loss, backward, update, and check the slopes against a numerical estimate and PyTorch's loss.backward()
  • Train a two-layer network on trail signs to high accuracy on held-back signs
  • Read a training run: a learning rate too low, too high and about right, and training versus held-back accuracy
Quick check
Have a guess before you start. In lesson 105, softmax followed by cross-entropy had a very simple slope with respect to the scores. What was it?
  1. 1 − p
  2. y − p²
  3. log p
  4. p − y
Show the answer

p − y

That one line, done for every row of a batch, is the first line of the backward pass: dZ₂ = P − Y.

The math: the backward pass in matrix form

Purpose. Get the loss's slope for every weight in the network, for a whole batch, in five lines.

The forward pass of lesson 110 was Z₁ = XW₁ + b₁, A₁ = relu(Z₁), Z₂ = A₁W₂ + b₂, P = softmax(Z₂), and the loss averaged −log of each right-class chance. The backward pass runs the same steps in reverse, each line one link of the chain rule:

lineformulawhy
1dZ₂ = (P − Y) ÷ nlesson 105's slope, averaged over the batch
2dW₂ = A₁ᵀ dZ₂, db₂ = column sums of dZ₂Z₂ = A₁W₂: each weight's slope sums input × push over the batch
3dA₁ = dZ₂ W₂ᵀthe push travels back through the same weights, turned around
4dZ₁ = dA₁, set to 0 where Z₁ ≤ 0relu passes the push only where the unit was on
5dW₁ = Xᵀ dZ₁, db₁ = column sums of dZ₁the same rule as line 2, one layer down

Every "d" matrix has exactly the shape of the matrix it's the slope of: that alone fixes where each transpose goes.

Quick check
From lesson 81: a value feeds two later steps, which send back slopes 0.3 and −0.1. What is its slope?
  1. 0.2
  2. −0.03
  3. 0.4
  4. 0.3
Show the answer

0.2

Across paths, slopes add: 0.3 + (−0.1) = 0.2. The matrix product dZ₂ W₂ᵀ does exactly this adding for every hidden unit.

The picture. Here are the five lines on a network small enough to draw: one sign with three features, two hidden units and two classes. Each column of circles is one matrix, entry by entry, with values inside and slopes (∂) below. Press Next to send the slopes back one line at a time, and watch the bottom hidden unit.

Try it now

Shapes decide the transposes. Now a whole batch: 8 signs, 2 features, 4 hidden units and 3 classes. This picture draws the network as boxes, with each matrix's shape on the arrow it travels along: forward along the top, back along the bottom. Each weight's slope lands on its own layer's box. Watch it come out the same shape as the weight.

Symbols and formula.

dZ2=1n(P−Y),dW2=A1⊤dZ2,dA1=dZ2W2⊤,dZ1=dA1⊙[Z1>0],dW1=X⊤dZ1dZ_2 = \tfrac{1}{n}(P - Y),\quad dW_2 = A_1^{\top} dZ_2,\quad dA_1 = dZ_2 W_2^{\top},\quad dZ_1 = dA_1 \odot [Z_1 > 0],\quad dW_1 = X^{\top} dZ_1

In plain words: start from "predicted minus true"; each weight matrix's slope is its layer's input, transposed, times the push arriving at its output; the push passes back through a layer by its weights turned around, and through relu only where the unit was on.

One entry by hand. dW₂'s entry (j, c), hidden unit j to class c, is Σᵢ A₁[i, j] × dZ₂[i, c]: the sum over the batch of "how active unit j was" times "how much class c's score should move". In the picture the sum had one term. Over a batch, a unit that was off for every example gets a row of zeros, like the picture's bottom unit. ⊙ means multiply entry by entry, * in NumPy.

Quick check
W₁ is 2 × 4. What shape must dW₁ be, and which product gives it?
  1. 2 × 4, from Xᵀ dZ₁
  2. 2 × 4, from X dZ₁ᵀ
  3. 4 × 2, from dZ₁ᵀ X
  4. n × 4, from dZ₁ alone
Show the answer

2 × 4, from Xᵀ dZ₁

A slope has its weight's shape. Xᵀ dZ₁ is (2 × n)(n × 4) = 2 × 4, summing over the batch.

In your own words
In your own words: why does every slope matrix have exactly the shape of its weight matrix?

Write a sentence or two, then compare it with a good answer in the lesson.

In Python: the full loop, checked

Purpose. Train the network, and prove the backward pass right before trusting it.

import numpy as np

rng = np.random.default_rng(7)
centers = np.array([[0.9, 0.2, 0.1], [0.2, 0.9, 0.3], [0.1, 0.3, 0.9]])
X = np.zeros((36, 3))
y = np.zeros(36, dtype=int)
for i in range(36):
    X[i] = centers[i % 3] + rng.normal(0, 0.15, 3)
    y[i] = i % 3
Xtr, ytr, Xte, yte = X[:24], y[:24], X[24:], y[24:]
Y = np.zeros((24, 3))
for i in range(24):
    Y[i, ytr[i]] = 1.0

def train(lr):
    r = np.random.default_rng(1)
    W1, b1 = r.normal(0, 0.5, (3, 4)), np.zeros(4)
    W2, b2 = r.normal(0, 0.5, (4, 3)), np.zeros(3)
    losses = []
    for step in range(300):
        Z1 = Xtr @ W1 + b1
        A1 = np.maximum(Z1, 0)
        Z2 = A1 @ W2 + b2
        E = np.exp(Z2 - Z2.max(axis=1, keepdims=True))
        P = E / E.sum(axis=1, keepdims=True)
        if step % 50 == 0:
            losses.append(round(float(-np.mean(np.sum(Y * np.log(P), axis=1))), 3))
        dZ2 = (P - Y) / 24
        dW2, db2 = A1.T @ dZ2, dZ2.sum(axis=0)
        dZ1 = (dZ2 @ W2.T) * (Z1 > 0)
        dW1, db1 = Xtr.T @ dZ1, dZ1.sum(axis=0)
        W1, b1, W2, b2 = W1 - lr * dW1, b1 - lr * db1, W2 - lr * dW2, b2 - lr * db2
    train_acc = np.mean(np.argmax(np.maximum(Xtr @ W1 + b1, 0) @ W2 + b2, axis=1) == ytr)
    test_acc = np.mean(np.argmax(np.maximum(Xte @ W1 + b1, 0) @ W2 + b2, axis=1) == yte)
    print("rate", lr, "loss", losses, "accuracy", round(float(train_acc), 2), round(float(test_acc), 2))

train(0.01)
train(0.5)
train(5)
It runs right here in your browser, with nothing to install.

Thirty-six signs are made around three typical feature profiles, one per class; 24 train the network and 12 are held back. train runs the loop 300 times from the same starting weights, keeping the loss every 50 steps, then prints that list and the training and held-back accuracy. At rate 0.5 the loss falls from 1.044 to 0.006 and every sign is read correctly. The other two rates go wrong in two different ways, which the last part of the lesson reads.

Code flow. Here is the same loop on the math part's one sign, run three times with no biases. Step through it: the first pass fills in every number from the picture, the last line moves both weight matrices, and the right class's chance, P's second entry, climbs on each pass. With one sign there is only one row, so the softmax divides by a plain .sum(), and with scores this small it can skip subtracting the largest score first.

Quick check
What does this print? (The first backward line for a batch of 2.)
import numpy as np

P = np.array([[0.7, 0.2, 0.1], [0.1, 0.6, 0.3]])
Y = np.array([[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]])
print(((P - Y) / 2).round(2).tolist())
  1. [[-0.3, 0.2, 0.1], [0.1, 0.6, -0.7]]
  2. [[0.35, 0.1, 0.05], [0.05, 0.3, 0.15]]
  3. [[-0.15, 0.1, 0.05], [0.05, 0.3, -0.35]]
  4. [[0.15, -0.1, -0.05], [-0.05, -0.3, 0.35]]
Show the answer

[[-0.15, 0.1, 0.05], [0.05, 0.3, -0.35]]

P − Y pushes each right class down by its missing chance and every other class by its stolen one; ÷ 2 averages over the batch.

A named mistake: a backward pass that's almost right. A missing transpose usually crashes, but a missing "÷ n", a forgotten relu mask or a sign error runs and trains, just badly. The guard is a gradient check: nudge one weight by a tiny h both ways, measure the loss's change, and compare with the backward pass's slope (lesson 81). At the starting weights of the runs above, the slope for W₁[0, 0] comes out 0.02854243 both ways.

Worked example

Worked example: a gradient check on one weight

Compare the backward pass's slope for W₁[0, 0] with a central difference, at the starting weights.

import numpy as np

rng = np.random.default_rng(7)
centers = np.array([[0.9, 0.2, 0.1], [0.2, 0.9, 0.3], [0.1, 0.3, 0.9]])
X = np.zeros((36, 3))
Y = np.zeros((36, 3))
for i in range(36):
    X[i] = centers[i % 3] + rng.normal(0, 0.15, 3)
    Y[i, i % 3] = 1.0
X, Y = X[:24], Y[:24]
r = np.random.default_rng(1)
W1, b1 = r.normal(0, 0.5, (3, 4)), np.zeros(4)
W2, b2 = r.normal(0, 0.5, (4, 3)), np.zeros(3)

def loss(W1):
    Z2 = np.maximum(X @ W1 + b1, 0) @ W2 + b2
    E = np.exp(Z2 - Z2.max(axis=1, keepdims=True))
    return -np.mean(np.sum(Y * np.log(E / E.sum(axis=1, keepdims=True)), axis=1))

Z1 = X @ W1 + b1
Z2 = np.maximum(Z1, 0) @ W2 + b2
E = np.exp(Z2 - Z2.max(axis=1, keepdims=True))
dZ1 = ((E / E.sum(axis=1, keepdims=True) - Y) / 24 @ W2.T) * (Z1 > 0)
back = (X.T @ dZ1)[0, 0]
up, down = W1.copy(), W1.copy()
up[0, 0] = up[0, 0] + 0.000001
down[0, 0] = down[0, 0] - 0.000001
print(round(float(back), 8), round(float((loss(up) - loss(down)) / 0.000002), 8))
In the lesson you can change this and run it.

Both numbers are 0.02854243. The backward pass got its slope from five matrix lines, the central difference by brute force from two forward passes. They share no code past the forward pass, so their agreement is strong evidence the backward pass is right; libraries run checks like this on every new layer type. Copies matter: nudging W1 itself would move the point every later slope is measured at (lesson 78).

Quick check
What does this print?
import numpy as np

A1 = np.array([[2.0, 0.0], [1.0, 3.0]])
dZ2 = np.array([[-0.5, 0.5], [0.1, -0.1]])
print((A1.T @ dZ2).round(2).tolist())
  1. [[-0.9, 0.3], [0.9, -0.3]]
  2. [[-0.5, 0.5], [0.1, -0.1]]
  3. [[-1.0, 1.0], [0.1, -0.1]]
  4. [[-0.9, 0.9], [0.3, -0.3]]
Show the answer

[[-0.9, 0.9], [0.3, -0.3]]

dW₂[0, 0] = 2 × (−0.5) + 1 × 0.1 = −0.9: summed over both examples. Unit 1 was off for the first example, so only the second counts: 3 × 0.1 = 0.3.

Drill

Write the backward pass

Fill in backward so it returns dW1, db1, dW2 and db2 for the network, using the five lines from the table. The test checks every shape and compares one slope with a gradient check.

import numpy as np

def forward(X, W1, b1, W2, b2):
    Z1 = X @ W1 + b1
    A1 = np.maximum(Z1, 0)
    Z2 = A1 @ W2 + b2
    E = np.exp(Z2 - Z2.max(axis=1, keepdims=True))
    return Z1, A1, E / E.sum(axis=1, keepdims=True)

def backward(X, Y, W1, b1, W2, b2):
    Z1, A1, P = forward(X, W1, b1, W2, b2)
    n = len(X)
    dW1 = np.zeros_like(W1)
    db1 = np.zeros_like(b1)
    dW2 = np.zeros_like(W2)
    db2 = np.zeros_like(b2)
    return dW1, db1, dW2, db2

r = np.random.default_rng(3)
X = r.normal(0, 1, (6, 2))
Y = np.zeros((6, 3))
for i in range(6):
    Y[i, i % 3] = 1.0
W1, b1, W2, b2 = r.normal(0, 0.5, (2, 4)), np.zeros(4), r.normal(0, 0.5, (4, 3)), np.zeros(3)
dW1, db1, dW2, db2 = backward(X, Y, W1, b1, W2, b2)
print(dW1.shape, db1.shape, dW2.shape, db2.shape)
In the lesson, your code is checked as you write it.

Plot the three runs. A loss curve is the first thing anyone checks in a training run. This cell types in the losses the first cell printed and draws one line per learning rate: label= names each line, and plt.legend() shows the names.

import matplotlib.pyplot as plt

steps = [0, 50, 100, 150, 200, 250]
plt.plot(steps, [1.044, 1.014, 0.984, 0.95, 0.917, 0.884], label="rate 0.01")
plt.plot(steps, [1.044, 0.083, 0.024, 0.013, 0.009, 0.006], label="rate 0.5")
plt.plot(steps, [1.044, 1.099, 1.099, 1.099, 1.099, 1.099], label="rate 5")
plt.xlabel("step")
plt.ylabel("training loss")
plt.legend()
plt.show()
Quick check
On your plot, which run is still falling steadily at step 250, so that more steps would help it most?
  1. rate 0.5
  2. None: all three have flattened
  3. rate 0.01
  4. rate 5
Show the answer

rate 0.01

Rate 0.01 drops about 0.03 every 50 steps and hasn't flattened: it needs more steps or a bigger rate. That's what too low looks like.

In your own words
The gradient check agreed to eight decimal places. What kinds of mistakes would it have caught, and is there anything it couldn't catch?

Write a sentence or two, then compare it with a good answer in the lesson.

In AI and ML: reading a training run

Purpose. Diagnose a training run from its loss curve and its two accuracies.

The loop you just wrote is the whole of training, so it lights almost the whole map. Only the parts for models of words (vectors, attention, sampling) and for the size of a run (memory, cost) stay dark.

Your plot holds three runs of the same network, data and starting weights. Too low (0.01) creeps: still falling at the end, it needs more steps or a bigger rate. About right (0.5) drops fast, then flattens near 0. Too high (5) jumps past the bottom on the first steps, and here something worse happens: every hidden unit switched off for every sign, relu blocked every slope (lesson 109's dead neurons), and the loss froze at 1.099, which is log 3, the loss of guessing a third for every class. A loss stuck at exactly log(classes) is the signature of a network that has stopped learning.

Quick check
A run's training loss stays at 0.693 from step 20 onward, on a two-class problem. What's the likely story?
  1. The learning rate is too small
  2. It has found the best possible weights
  3. It stopped: 0.693 is log 2, a 50/50 guess
  4. It overfits
Show the answer

It stopped: 0.693 is log 2, a 50/50 guess

log(number of classes) is the loss of equal guesses. Frozen there usually means dead units, often from a learning rate that was too high.

Live training. The playground runs this same loop, forward, loss, backward, update, many times a second on points of two kinds, and draws the training and test loss as it learns. Its hidden units use tanh, an S-shaped bend like the sigmoid, unless you pick ReLU. It starts at a learning rate of 0.01. With random weights it guesses about 50/50, so its loss starts near log 2; what matters is whether it moves.

Train versus held back. In the first cell both accuracies matched, because the three kinds of sign are well separated. On harder data, training accuracy rising while held-back accuracy stalls or falls is overfitting (lesson 101). Leave a playground run going at 0.5 to see it start: the training loss keeps falling while the test loss levels off, then starts to climb.

In PyTorch. Real training code almost never writes the five lines. As in lesson 81, loss.backward() works out every slope by the chain rule and stores each in the .grad of every tensor made with requires_grad=True. This cell does the five lines by hand on the first cell's starting network, then lets PyTorch do them.

import numpy as np
import torch
import torch.nn.functional as F

rng = np.random.default_rng(7)
centers = np.array([[0.9, 0.2, 0.1], [0.2, 0.9, 0.3], [0.1, 0.3, 0.9]])
X = np.zeros((24, 3))
y = np.zeros(24, dtype=int)
Y = np.zeros((24, 3))
for i in range(24):
    X[i] = centers[i % 3] + rng.normal(0, 0.15, 3)
    y[i] = i % 3
    Y[i, i % 3] = 1.0
r = np.random.default_rng(1)
W1, b1 = r.normal(0, 0.5, (3, 4)), np.zeros(4)
W2, b2 = r.normal(0, 0.5, (4, 3)), np.zeros(3)

# the forward pass and the five lines, by hand
Z1 = X @ W1 + b1
A1 = np.maximum(Z1, 0)
Z2 = A1 @ W2 + b2
E = np.exp(Z2 - Z2.max(axis=1, keepdims=True))
dZ2 = (E / E.sum(axis=1, keepdims=True) - Y) / 24
dW2, db2 = A1.T @ dZ2, dZ2.sum(axis=0)
dZ1 = (dZ2 @ W2.T) * (Z1 > 0)
dW1, db1 = X.T @ dZ1, dZ1.sum(axis=0)

# the same network in PyTorch, and its backward pass
tW1, tb1 = torch.tensor(W1, requires_grad=True), torch.tensor(b1, requires_grad=True)
tW2, tb2 = torch.tensor(W2, requires_grad=True), torch.tensor(b2, requires_grad=True)
scores = torch.relu(torch.tensor(X) @ tW1 + tb1) @ tW2 + tb2
loss = F.cross_entropy(scores, torch.tensor(y))   # softmax and the average -log p in one call
loss.backward()
print("loss", round(loss.item(), 3), "slope of W1[0, 0]", round(tW1.grad[0, 0].item(), 6))
for name, mine, auto in [("dW1", dW1, tW1), ("db1", db1, tb1), ("dW2", dW2, tW2), ("db2", db2, tb2)]:
    print(name, "largest gap:", round(float(np.abs(mine - auto.grad.numpy()).max()), 6))

It prints the loss 1.044, the first cell's loss at step 0, and W₁[0, 0]'s slope 0.028542, the gradient check's number to six places. Every largest gap is 0.0 to six places: loss.backward() is your five lines.

Drill

Train to 90% on held-back signs

Use your forward and backward lines in a training loop on the sign data (seed 7 for the data, seed 1 for the weights). Choose a learning rate and a number of steps so that test_acc, the accuracy on the 12 held-back signs, is at least 0.9, and record final_loss, the training loss after the last step.

import numpy as np

rng = np.random.default_rng(7)
centers = np.array([[0.9, 0.2, 0.1], [0.2, 0.9, 0.3], [0.1, 0.3, 0.9]])
X = np.zeros((36, 3))
y = np.zeros(36, dtype=int)
for i in range(36):
    X[i] = centers[i % 3] + rng.normal(0, 0.15, 3)
    y[i] = i % 3
Xtr, ytr, Xte, yte = X[:24], y[:24], X[24:], y[24:]
Y = np.zeros((24, 3))
for i in range(24):
    Y[i, ytr[i]] = 1.0
r = np.random.default_rng(1)
W1, b1 = r.normal(0, 0.5, (3, 4)), np.zeros(4)
W2, b2 = r.normal(0, 0.5, (4, 3)), np.zeros(3)
lr = 0.01
steps = 10
for step in range(steps):
    Z1 = Xtr @ W1 + b1
    A1 = np.maximum(Z1, 0)
    Z2 = A1 @ W2 + b2
    E = np.exp(Z2 - Z2.max(axis=1, keepdims=True))
    P = E / E.sum(axis=1, keepdims=True)
    dZ2 = (P - Y) / 24
    dW2, db2 = A1.T @ dZ2, dZ2.sum(axis=0)
    dZ1 = (dZ2 @ W2.T) * (Z1 > 0)
    dW1, db1 = Xtr.T @ dZ1, dZ1.sum(axis=0)
    W1, b1, W2, b2 = W1 - lr * dW1, b1 - lr * db1, W2 - lr * dW2, b2 - lr * db2
final_loss = 0
test_acc = 0
print(final_loss, test_acc)
In the lesson, your code is checked as you write it.
In your own words
Your run reached 100% on the held-back signs. Why might the same network do worse on signs photographed in a new forest?

Write a sentence or two, then compare it with a good answer in the lesson.

Goes deeper in

Practice what you just read

  • 4 code examples you can edit and run
  • a practice exercise that checks your code
  • a 5-question quiz
  • 10 review cards for spaced repetition

Try a quiz question

What is the first line of the backward pass for softmax and cross-entropy?

  1. dZ₂ = (P − Y) ÷ n
  2. dW₁ = Xᵀ dZ₁
  3. dA₁ = dZ₂ W₂ᵀ
  4. P = softmax(Z₂)

Answer it at the end of the lesson to see if you're right, and why.

Before this lesson

Keep learning

Where this lesson leads.

575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.

Foundation · about 96 hours of study

Foundation math

From whole numbers to the math inside a neural network: each idea by hand, in Python, and in AI 118 lessons All free
  1. Numbers and place value FreeWhat a digit's place is worth, the number line, and Python as a calculator that never tires.36 min
  2. Multiplying and dividing: groups FreeEqual groups, quotient and remainder, and cutting training data into batches.35 min
  3. Order of operations, and names for numbers FreeBrackets, powers, then multiply and divide, then add and subtract; variables hold numbers.36 min
  4. Numbers below zero FreeThe number line through zero, sign rules, distance from zero, and an error's direction and size.37 min
  5. Fractions: equal parts, equal fractions, adding FreePieces of a whole, equal fractions, and re-cutting to add; accuracy as a fraction.45 min
  6. Multiplying and dividing fractions FreeA share of a share, dividing by flipping, and why chances in a row get small.35 min
  7. Decimals and rounding FreeFractions in place value, rounding, and why 0.1 + 0.2 isn't exactly 0.3.36 min
  8. Percentages FreePer hundred, percent change, percentage points, and the accuracy and error rates of models.35 min
  9. Ratios, rates and proportion FreeSharing in a ratio, rates per unit, scaling, and splitting data 80/10/10.35 min
  10. Powers and roots FreeRepeated multiplying, the laws of exponents, square roots, and squared error.43 min
  11. Very big and very small numbers FreePowers of ten, e-notation like 3e-4, orders of magnitude, and a model's size in memory.36 min
  12. Bits, bytes and floats: how numbers are stored FreeBase 2, what n bits can hold, a float as sign, power and digits, and a tensor's memory.35 min
  13. Review: find the slip (numbers) FreeBroken calculations to fix, mixed practice from the whole module, and its formula sheet.34 min
  14. Letters for numbers FreeVariables, terms and like terms, substitution, and a model's formula as a Python function.41 min
  15. Expanding and factoring FreeBrackets as areas, pulling out common factors, and a squared error expanded into a bowl.41 min
  16. Solving equations: keep the balance FreeThe same move on both sides, undoing steps in reverse, and running a model's formula backward.41 min
  17. Rearranging a formula FreeMaking any letter the subject, round-trip checks, and planning a training run.36 min
  18. Inequalities and true-or-false FreeRanges, flipping the sign, if and elif, and the thresholds, clips and ReLU inside a model.42 min
  19. Functions: a rule from input to output Freef(x) notation, tables and graphs, domain and range, loops over lists, and loss as a function.42 min
  20. Chaining and undoing functions Freeg(f(x)), inverses that undo, scaling and unscaling, and a network as a chain.42 min
  21. Straight lines: slope and intercept FreeRise over run, the line through two points, and a model's weight and bias as slope and intercept.42 min
  22. Two equations, two unknowns FreeSubstitution and elimination, where lines cross, and why models are fitted, not solved.42 min
  23. Quadratics: bowls and their lowest point FreeRoots by factoring and by formula, the discriminant, the vertex, and the best weight of a model.42 min
  24. Exponentials: growth and decay FreeThe same factor each step, the number e, and decaying learning rates.43 min
  25. Logarithms: the power question FreeTo what power?, the laws of logs, and adding log-probabilities instead of multiplying.45 min
  26. Sequences and Σ FreeArithmetic and geometric sequences, Σ as a loop that adds, and mean squared error.40 min
  27. Weighted and moving averages FreeWeights that add to 1, a window average, the exponential moving average, and smoothing a loss curve.35 min
  28. Sets, and reading the symbols FreeSets, union and intersection, ℝⁿ and f : ℝⁿ → ℝᵐ, and reading a paper's first equation.41 min
  29. Review: find the slip (algebra) FreeBroken algebra and code to fix, mixed practice from the whole module, and its formula sheet.34 min
  30. Transposing step by step: undo in reverse order FreeA formula's layers, the opposite of each, peeling from the outside in, conditions, and round-trip checks.35 min
  31. Formulas with fractions: clear them first FreeClearing denominators, cross-multiplying, a letter in the bottom, and reciprocal formulas like 1/R = 1/R₁ + 1/R₂.35 min
  32. When the letter appears twice: collect and factor FreeGathering the letter on one side, factoring it out, dividing by the bracket, and rearranging precision and F1.35 min
  33. Squares, roots and powers FreeSquare roots with ±, squaring to undo a root, cube and nth roots, and the √d inside attention.40 min
  34. When the letter is squared and plain: quadratics FreeRearranging into ax² + bx + c = 0, the formula, completing the square, and choosing the root that fits.35 min
  35. Letters in the power: exponentials and logarithms FreeTaking logs to bring a power down, exponentiating to free a letter, and the logit that undoes the sigmoid.40 min
  36. Rearranging inequalities: when the sign flips FreeThe four moves on an inequality, negatives and reciprocals that flip it, logs below 1, and sample sizes.35 min
  37. Inverse functions, lines and scaling FreeUndoing a function by making x the subject, domains that allow it, line forms, and unscaling predictions.40 min
  38. Sequences and sums: find n, a, d and r FreeEvery letter of the arithmetic and geometric formulas as the subject, and an average's window from its decay.40 min
  39. Combining formulas: substitute and eliminate FreePutting one formula inside another to remove a letter, and sizing a training run from a time or money budget.35 min
  40. Review: rearrange anything (algebra) FreeBroken rearrangements to fix, mixed practice from the whole algebra block, a strategy chart, and its formula sheet.35 min
  41. Coordinates and distance FreePoints as (x, y), Pythagoras, distance in any number of coordinates, and nearest neighbors.42 min
  42. Angles, degrees and radians FreeMeasuring a turn, converting units, arcs, and the angle between two arrows.36 min
  43. Sine and cosine FreeAcross and up: right triangles, the unit circle, and directions and rotations.42 min
  44. Waves: height, speed and shift FreeAmplitude, period and phase, sampling a wave, and position codes in transformers.37 min
  45. Review: find the slip (shapes and waves) FreeBroken geometry and code to fix, mixed practice from the module, and its formula sheet.29 min
  46. Angles, triangles and waves: rearranging with sin, cos and tan FreeSides and angles from SOH CAH TOA, principal values, arcs, polar coordinates, and a wave's time and period.45 min
  47. Vectors: lists of numbers that point FreeA list, a point and an arrow; components, dimension, NumPy arrays, and data as vectors.42 min
  48. Adding and scaling vectors FreeComponent-wise sums, scalar multiples, mixes, and the weight update w − ηg.43 min
  49. Length and distance: norms FreeL2, L1 and max norms, unit vectors, distance, and the norms inside losses and clipping.42 min
  50. The dot product FreeMultiply in pairs and add; a·a as squared length; a @ b; one neuron as a dot product.43 min
  51. Angle, cosine similarity and projection FreeDirection without length, perpendicular vectors, shadows, and search by meaning.45 min
  52. Perpendicular directions: bases and coordinates FreeOrthonormal directions, coordinates as dot products, rebuilding a vector, and taking a direction out.35 min
  53. Matrices: tables of numbers FreeRows, columns and entries; two-dimensional arrays and slices; a data set as a matrix.41 min
  54. Adding, scaling and transposing matrices FreeEntry-by-entry sums and scalings, the transpose, mean images, and tables turned around.36 min
  55. A matrix times a vector FreeEach row dotted with the vector, the size rule, A @ x, and a layer acting on one example.42 min
  56. Matrix multiplication FreeRow meets column, the size rule, order matters, and a batch through a layer: X W + b.45 min
  57. Identity, diagonal, triangular and symmetric FreeFour patterns and their jobs: rescaling, distance tables, and the causal mask.37 min
  58. Matrices as movements of space FreeStretches, flips, shears and rotations; columns as landing spots; chaining; a layer moving data.42 min
  59. Determinant and inverse FreeThe area factor ad − bc, singular matrices, undoing a matrix, and redundant features.42 min
  60. Solving systems by elimination FreeAugmented matrices, row moves, back-substitution, the three outcomes, and fitting weights.45 min
  61. Independence, span and rank FreeRedundant vectors, span, rank, outer products, and low-rank updates like LoRA.42 min
  62. Eigenvectors: directions that only stretch FreeAv = λv, checking candidates, np.linalg.eig, and the main direction of a data cloud.41 min
  63. SVD and PCA: the important directions first FreeA matrix as pieces by size, the best rank-k copy, compression, and PCA maps of data.45 min
  64. Tensors, shapes and broadcasting FreeAxes and shapes, reshape, axis=, broadcasting, and shapes through a small model.43 min
  65. One-hot vectors and lookup tables: embeddings FreeA one-hot row picks a table's row, a sentence looked up as vectors, and a score for every word.35 min
  66. Sliding dot products: convolution FreeA small pattern slid along a list and over a grid, output sizes, stride and padding, and shared weights.40 min
  67. Review: find the slip (vectors and matrices) FreeShape slips to fix, mixed practice from the module, and its formula sheet with shapes.36 min
  68. Vector equations: rearranging with arrows FreeSolving for a vector or a scale, recovering a gradient from two weight snapshots, and an angle from a dot product.40 min
  69. Matrix equations: multiply by the inverse, on the correct side FreeNo dividing by a matrix: inverses from the left or right, order, transposes, and the normal equations.40 min
  70. Rates of change FreeChange over change, secants, rates from readings with np.diff, and reading a loss curve.41 min
  71. Limits: what a value heads toward FreeApproaching from both sides, holes, corners and jumps, epsilon, and judging activations.37 min
  72. The derivative: slope at a point FreeShrinking secants, f′(x) and dy/dx, Δy ≈ f′Δx, and which way a weight should move.45 min
  73. Derivative rules FreeConstants, powers, multiples, sums, eˣ and ln x, checked numerically, and a squared error's slope.41 min
  74. The product rule and the chain rule FreeProducts and chains of functions, forward then backward, and one neuron's dL/dw.45 min
  75. Lowest points and curvature Freef′ = 0, the second-derivative test, tables, local and global minima, and convex losses.43 min
  76. Standing in for a curve near a point FreeTangent lines, a curvature term, growing error, and why learning rates must be small.37 min
  77. Partial derivatives FreeOne input at a time, ∂, nudging in Python, and the two slopes of a line's loss.41 min
  78. The gradient FreeAll the slopes as a vector, steepest climb and descent, a numerical gradient, and the loss gradient.42 min
  79. Gradient descent FreeStepping against the gradient, the learning rate, a training loop, and fitting a line.45 min
  80. Faster descent: momentum and Adam FreeMomentum and Adam by hand, the bias correction, and three optimizers down one narrow valley.40 min
  81. The chain rule with many paths: backpropagation by hand FreeGraphs, multiply along paths and add across them, gradient checks, and a 2-2-1 network by hand.45 min
  82. Automatic differentiation: how PyTorch finds every slope FreeA tape of steps walked backward, and requires_grad, backward(), .grad, zero_grad() and no_grad().40 min
  83. Jacobians and Hessians FreeSlopes of vector functions, a layer's Jacobian, second partials, and bowls, domes and saddles.42 min
  84. Integrals: adding up thin slices FreeStrip and trapezoid sums, summing undoes differencing, probability as area, and AUC.43 min
  85. Review: find the slip (calculus) FreeCalculus slips to fix, mixed practice from the module, and its formula sheet.36 min
  86. Rearranging in calculus: slopes, steps and constants FreeSetting a slope to zero, Newton's step, the chain rule turned around, constants from a point, and learning rates.45 min
  87. Counting: choices, orders and groups FreeThe counting principle, factorials, ordered picks and groups, and why attention's cost grows with the square of the length.43 min
  88. Probability: from counts to chances FreeEqually likely outcomes, the complement, distributions, seeded simulation, and a next-word model.43 min
  89. Combining events: and, or, independent FreeThe or rule, independence, probability trees, drawing with and without replacement, and chains of steps.42 min
  90. Conditional probability and Bayes' rule FreeConditionals from tables, why P(A | B) isn't P(B | A), Bayes' rule, and precision and recall.45 min
  91. Random variables and distributions FreeUncertain numbers, the probability of a range, sampling by slices, and sampling versus argmax.42 min
  92. Expected value, variance and standard deviation FreeProbability-weighted averages, spread in the data's own units, and a training loss as an expected value.42 min
  93. Bernoulli, binomial, uniform and normal FreeYes-or-no trials, counts of yeses, the 68-95-99.7 rule, z-scores, and an accuracy's error bar.45 min
  94. Two variables at once: covariance and correlation FreeJoint tables and marginals, covariance, correlation, the covariance matrix, and features that carry the same information.45 min
  95. Review: find the slip (probability) FreeProbability slips to fix, mixed practice from the module, and its formula sheet.36 min
  96. Probability formulas: solve for the missing chance FreeConditionals, Bayes' rule for the prior, the or rule, expected values, variance, and z-scores turned around.45 min
  97. Describing data: center, spread and scale FreeMean, median and mode, variance and standard deviation, percentiles, outliers, and standardizing features.42 min
  98. Samples, the law of large numbers and the central limit theorem FreeSamples and populations, the standard error σ/√n, the bell of averages, and error bars on test scores.43 min
  99. Is the difference real? Comparing two models FreePaired differences, a bootstrap interval, what a p-value is and isn't, and why many tries make lucky wins.40 min
  100. Maximum likelihood FreeLikelihoods as products, log-likelihoods as sums, grid search, underflow, and the negative log-likelihood loss.45 min
  101. Linear regression: the best line FreeResiduals, least squares by formula, three roads to one line, the matrix form, and train versus test error.45 min
  102. Logistic regression: a line that answers yes or no FreeThe sigmoid, the log loss, its slope p − y, a training loop, and choosing a threshold.45 min
  103. Scoring a classifier: confusion table, precision, recall, F1 FreeThe four cells, accuracy, precision, recall and F1, and what moving a threshold does to each.35 min
  104. Softmax: scores into probabilities FreeExponentiate and share out, shifting and temperature, the safe softmax, and a classifier's last step.43 min
  105. Surprise, entropy and cross-entropy FreeSurprise in bits, entropy, cross-entropy and KL divergence, perplexity, and a language model's loss.45 min
  106. KL divergence: how far one distribution is from another FreeKL by hand, cross-entropy as entropy plus KL, why it isn't symmetric, and a soft-target loss.35 min
  107. Review: find the slip (statistics and information) FreeStatistics slips to fix, mixed practice from the module, and its formula sheet.38 min
  108. Statistics and information: n, z, logits and bits FreeSample sizes from error bars, inputs from probabilities, logit gaps from softmax, and chances from bits and losses.40 min
  109. One neuron, start to finish FreeWeighted sum, activation, loss, slopes and update, by hand and in code, and what one straight line can and can't split.45 min
  110. A layer and a small network as matrices FreeTwo layers on a batch, the shape of every matrix, adding a hidden unit, and XOR solved.45 min
  111. Training a small network FreeThe backward pass in matrix form, gradient checks, a full training loop, and reading loss curves.45 min
  112. The same network in PyTorch Freenn.Sequential with the NumPy weights loaded, the same loss and slopes, then SGD and mini-batches.45 min
  113. Attention as matrix math FreeScaled dot-product scores, the causal mask, a row-by-row softmax, and blending value vectors.45 min
  114. Residual connections and layer norm FreeAdding the input back and why its slope keeps learning alive, layer norm by hand, and add and norm.40 min
  115. A transformer block, start to finish FreeA sentence through embeddings, attention, add and norm, a small network and next-word scores, every shape named.45 min
  116. Planning a model: rearranging the formulas of a working network FreeLayer widths from parameter counts, sizes from memory and compute, the attention scale, and a training plan.40 min
  117. Final test: transpose any formula FreeSlips to fix from every topic, mixed practice of every kind of rearranging, the strategy chart and the full sheet.45 min
  118. Capstone: a sign reader from the formulas FreeBuild, train and test a trail-sign classifier with NumPy alone, and report its accuracy with an error bar.45 min
Part of a free course 118 lessons

The Foundation Math For Ai & ML: from arithmetic to attention

Learn the math behind AI from arithmetic up: numbers, algebra, vectors and matrices, calculus, probability and statistics, each shown as numbers moving and checked in Python, ending with a network you build and train from the formulas.

Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write