Index Ai Academy
Foundation · Putting it together

Capstone: a sign reader from the formulas

Build, train and test a trail-sign classifier with NumPy alone, and report its accuracy with an error bar.

About 45 minutes · Free lesson

What it covers16

Why it matters

This is the Foundation's final project, and it uses nearly every module. Vectors and matrices hold the signs and the weights (Module 4); the forward pass is matrix products, relu and softmax (Modules 4, 5 and 7); the loss is cross-entropy (Module 7); the backward pass is the chain rule along many paths (Module 5); the update is gradient descent (Module 5); and the honest verdict, an accuracy with an error bar, is Module 7's statistics. Nothing here is new. What's new is doing all of it at once, from an empty file, then explaining the result as an engineer would: what was built, how well it works, how sure that number is, and where it goes wrong. The guided steps below build one version together, then rebuild it in PyTorch; the brief at the end asks you to build your own and write it up.

What you'll be able to do

  • Build a trail-sign classifier with NumPy alone: data, a two-layer network, softmax and cross-entropy
  • Train it with a backward pass you have checked numerically, and plot its loss curve
  • Test it once on held-back signs and report the accuracy with a 95% error bar
  • Study its wrong predictions in a confusion table, and write a one-page report naming every formula and shape you used
  • Rebuild the same reader in PyTorch, check it reaches the same verdict, and train it on mini-batches
Quick check
Have a guess before you start. A classifier gets 27 of 30 held-back signs right. Besides the accuracy, 0.9, what should a report give?
  1. The accuracy on the training signs instead
  2. The number of hidden units only
  3. Nothing: 0.9 says it all
  4. An error bar: how far 0.9 could wobble
Show the answer

An error bar: how far 0.9 could wobble

30 signs is a small test. Lesson 98's standard error, √(0.9 × 0.1 ÷ 30) ≈ 0.055, puts the true accuracy roughly between 0.79 and 1.

The project

Purpose. Build, train and test a sign reader, then report it honestly.

A trail-sign camera describes each sign by three numbers between about 0 and 1: how pointed its shape is, how wide and how tall. Arrows are pointed, tent-site signs are wide, and trail markers are tall, but real signs are worn, tilted and half-hidden, so the numbers are noisy and the kinds overlap. The task: tell the three kinds apart.

Try it now

The model is lesson 110's network: 3 inputs, 8 hidden relu units, 3 classes, a softmax and the cross-entropy loss. Training is lesson 111's loop. The verdict is lesson 98's error bar. Six steps follow: the data, the forward pass and loss, the backward pass with its check, training, the report, and the same reader in PyTorch. Each step names the lesson it comes from.

Quick check
From lesson 98: an accuracy of 0.9 measured on 30 signs. What is its standard error, to 3 places?
  1. 0.055
  2. 0.3
  3. 0.003
  4. 0.09
Show the answer

0.055

√(0.9 × 0.1 ÷ 30) = √0.003 ≈ 0.055. A 95% range reaches 1.96 of those either side.

Step 1: the data, split once

Purpose. Make 120 signs, keep 30 aside, and never look at those 30 until the end.

The code below invents 40 signs of each kind around three typical profiles, arrow (0.9, 0.2, 0.1), tent (0.2, 0.9, 0.3) and trail (0.1, 0.3, 0.9), with noise of standard deviation 0.3 added to every number (lesson 93's normal distribution). The first 90 signs train the model; the last 30 are the test set. The labels become one-hot rows of Y, one 1 per row, so the loss can pick out each right class's chance (lesson 110).

import numpy as np

rng = np.random.default_rng(11)
centers = np.array([[0.9, 0.2, 0.1], [0.2, 0.9, 0.3], [0.1, 0.3, 0.9]])
X = np.zeros((120, 3))
y = np.zeros(120, dtype=int)
for i in range(120):
    X[i] = centers[i % 3] + rng.normal(0, 0.3, 3)
    y[i] = i % 3
Xtr, ytr, Xte, yte = X[:90], y[:90], X[90:], y[90:]
print(Xtr.shape, Xte.shape, X[0].round(2).tolist(), y[:6].tolist())
It runs right here in your browser, with nothing to install.

The very first sign, an arrow, came out (0.91, 0.61, 0.47): pointed, but wider and taller than its profile.

Quick check
What does this print?
import numpy as np

y = np.array([0, 2, 1])
Y = np.zeros((3, 3))
for i in range(3):
    Y[i, y[i]] = 1.0
print(Y.tolist())
  1. [[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]
  2. [[0.0, 2.0, 1.0]]
  3. [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
  4. [[1.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 0.0]]
Show the answer

[[1.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 0.0]]

Each row gets a single 1, in the column of its label: 0, then 2, then 1.

Step 2: the forward pass and the loss

Purpose. Turn the 90 training signs into chances and one number for how wrong they are.

Start the weights small and random, W₁ (3 × 8) and W₂ (8 × 3) from a seeded generator, with zero biases. The forward pass is lesson 110's: Z₁ = XW₁ + b₁, A₁ = relu(Z₁), Z₂ = A₁W₂ + b₂, P = softmax(Z₂) row by row. The loss is the average of −log of each sign's right-class chance. Before any training it should be close to log 3 ≈ 1.099, the loss of a model that guesses a third for every class; a starting loss far from that usually means a bug.

The picture draws the whole project as boxes, each matrix's shape on the arrow it travels along: forward along the top, the slopes back along the bottom. Its PyTorch tab is the code of Step 6.

Drill

The starting loss

Write forward(X, W1, b1, W2, b2) returning Z1, A1 and P, and loss(P, Y). Then set start to the loss on the training signs at the starting weights (seed 2), rounded to 3.

import numpy as np

rng = np.random.default_rng(11)
centers = np.array([[0.9, 0.2, 0.1], [0.2, 0.9, 0.3], [0.1, 0.3, 0.9]])
X = np.zeros((120, 3))
y = np.zeros(120, dtype=int)
for i in range(120):
    X[i] = centers[i % 3] + rng.normal(0, 0.3, 3)
    y[i] = i % 3
Xtr, ytr = X[:90], y[:90]
Y = np.zeros((90, 3))
for i in range(90):
    Y[i, ytr[i]] = 1.0
r = np.random.default_rng(2)
W1, b1 = r.normal(0, 0.5, (3, 8)), np.zeros(8)
W2, b2 = r.normal(0, 0.5, (8, 3)), np.zeros(3)

def forward(X, W1, b1, W2, b2):
    return 0, 0, 0

def loss(P, Y):
    return 0.0

start = 0
print(start)
In the lesson, your code is checked as you write it.
In your own words
Why is a starting loss near log 3 a good sign, before any training has happened?

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

Step 3: the backward pass, checked

Purpose. Get every weight's slope, and prove the code right before training on it.

Lesson 111's five lines: dZ₂ = (P − Y)/n, dW₂ = A₁ᵀdZ₂, dA₁ = dZ₂W₂ᵀ, dZ₁ = dA₁ where Z₁ > 0, dW₁ = XᵀdZ₁, with each bias's slope the column sums of its dZ. Then a gradient check: nudge one weight of W₁ up and down by 0.000001, recompute the loss each time, and compare (L₊ − L₋)/0.000002 with the backward pass's number. If they agree to six or more digits, the backward pass is right; if not, no amount of training will save it.

Quick check
Your gradient check gives 0.0412 from the nudges and 0.0824 from the backward pass, for every weight you try. What's the most likely slip?
  1. The learning rate is wrong
  2. Nothing: the two never agree exactly
  3. The data has outliers
  4. A stray factor of 2, such as a wrong n
Show the answer

A stray factor of 2, such as a wrong n

A slope off by exactly the same factor everywhere points to a constant: a wrong batch size or a missing ½.

Step 4: train, and watch the loss

Purpose. Run the loop until the loss stops falling, printing it as it goes.

Run 500 steps at learning rate 0.5 on the 90 training signs, printing the loss every 100 steps and, at the end, how many training signs the network reads right.

Worked example

Worked example: the whole training run

Train the network on the 90 signs and print the loss every 100 steps.

import numpy as np

rng = np.random.default_rng(11)
centers = np.array([[0.9, 0.2, 0.1], [0.2, 0.9, 0.3], [0.1, 0.3, 0.9]])
X = np.zeros((120, 3))
y = np.zeros(120, dtype=int)
for i in range(120):
    X[i] = centers[i % 3] + rng.normal(0, 0.3, 3)
    y[i] = i % 3
Xtr, ytr = X[:90], y[:90]
Y = np.zeros((90, 3))
for i in range(90):
    Y[i, ytr[i]] = 1.0
r = np.random.default_rng(2)
W1, b1 = r.normal(0, 0.5, (3, 8)), np.zeros(8)
W2, b2 = r.normal(0, 0.5, (8, 3)), np.zeros(3)
for step in range(501):
    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 % 100 == 0:
        print(step, round(float(-np.mean(np.sum(Y * np.log(P), axis=1))), 3))
    dZ2 = (P - Y) / 90
    dZ1 = (dZ2 @ W2.T) * (Z1 > 0)
    W2, b2 = W2 - 0.5 * (A1.T @ dZ2), b2 - 0.5 * dZ2.sum(axis=0)
    W1, b1 = W1 - 0.5 * (Xtr.T @ dZ1), b1 - 0.5 * dZ1.sum(axis=0)
print("training accuracy", round(float(np.mean(np.argmax(P, axis=1) == ytr)), 3))
In the lesson you can change this and run it.

Every line is one you've written in an earlier lesson: the forward pass of lesson 110, the backward lines of lesson 111, the update of lesson 79. The loop runs to step 500 so the last line printed is the loss after 500 updates, and the accuracy is read from the chances P of that same pass. Two choices were made by trying, and a report should say so: 8 hidden units (4 reached about the same training loss, 0.134, so either would do) and a learning rate of 0.5 (0.05 ended the same 500 steps at 0.205, still higher). Neither choice looked at the test signs.

Plot the curve. The loss column is the curve that goes in the report, as a picture. This cell types in the six losses the run printed:

import matplotlib.pyplot as plt

steps = [0, 100, 200, 300, 400, 500]
losses = [1.162, 0.158, 0.144, 0.141, 0.139, 0.138]
plt.plot(steps, losses)
plt.xlabel("step")
plt.ylabel("training loss")
plt.show()

It drops fast, then flattens: lesson 111's "about right". It doesn't reach 0, and it shouldn't: some signs are so worn that their numbers sit inside another kind's cloud, and no smooth boundary gets all of them. On the training signs the network ends 94.4% right, 0.944.

Quick check
The training loss flattens at 0.138 instead of reaching 0. What's the best reading?
  1. The network is dead
  2. Some signs sit in another kind's cloud
  3. The learning rate is too high
  4. Training must continue until the loss is 0
Show the answer

Some signs sit in another kind's cloud

Noisy, overlapping data has a floor. Driving the loss to 0 would mean memorizing the noise, which tends to hurt on new signs.

Drill

Train, then test once

Train as in the example, then score the 30 held-back signs once. Set acc to the test accuracy, low and high to the 95% range acc ± 1.96·√(acc(1 − acc)/30), rounded to 3 (cap high at 1), and wrong to the positions of the misread test signs as a list.

import numpy as np

rng = np.random.default_rng(11)
centers = np.array([[0.9, 0.2, 0.1], [0.2, 0.9, 0.3], [0.1, 0.3, 0.9]])
X = np.zeros((120, 3))
y = np.zeros(120, dtype=int)
for i in range(120):
    X[i] = centers[i % 3] + rng.normal(0, 0.3, 3)
    y[i] = i % 3
Xtr, ytr, Xte, yte = X[:90], y[:90], X[90:], y[90:]
Y = np.zeros((90, 3))
for i in range(90):
    Y[i, ytr[i]] = 1.0
r = np.random.default_rng(2)
W1, b1 = r.normal(0, 0.5, (3, 8)), np.zeros(8)
W2, b2 = r.normal(0, 0.5, (8, 3)), np.zeros(3)
for step in range(500):
    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) / 90
    dZ1 = (dZ2 @ W2.T) * (Z1 > 0)
    W2, b2 = W2 - 0.5 * (A1.T @ dZ2), b2 - 0.5 * dZ2.sum(axis=0)
    W1, b1 = W1 - 0.5 * (Xtr.T @ dZ1), b1 - 0.5 * dZ1.sum(axis=0)
acc = 0
low = 0
high = 0
wrong = []
print(acc, low, high, wrong)
In the lesson, your code is checked as you write it.
In your own words
Suppose you tried five hidden sizes and kept whichever scored best on the 30 test signs. What would be wrong with the score you then report?

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

Step 5: the report

Purpose. Say what was built, how well it works, how sure that is, and where it fails.

The verdict. 27 of the 30 held-back signs are read correctly: an accuracy of 0.9, with a 95% range from about 0.79 to 1. With only 30 test signs, "between 0.8 and 1" is all the data can honestly support; a model scoring 0.85 on the same 30 signs couldn't be called worse.

Quick check
What does this print?
acc = 0.9
se = (acc * (1 - acc) / 30) ** 0.5
print(round(se, 4), round(acc - 1.96 * se, 3))
  1. 0.3 0.312
  2. 0.0548 0.846
  3. 0.003 0.894
  4. 0.0548 0.793
Show the answer

0.0548 0.793

√(0.09 ÷ 30) ≈ 0.0548, and 0.9 − 1.96 × 0.0548 ≈ 0.793: the low end of the 95% range.

The three mistakes. Test sign 11, a trail marker, has features (1.19, −0.08, 1.0): tall, as it should be, but the noise made it as pointed as any arrow, and the network said arrow with 0.89. Sign 25, a tent-site sign, came out (0.01, 0.06, 0.61): its width was wiped out entirely, and the network said trail with 0.99. Sign 29, another trail marker, is (0.65, 0.73, 0.55), middling on all three, and was called tent with 0.93. Each mistake is a sign whose numbers really do look like another kind, and each was made with high confidence, which says the network has never been shown how unreliable a single feature can be. More worn examples in training would help more than a bigger network.

Where the mistakes fall. A confusion table (lesson 103) counts each test sign into a row for its true kind and a column for the kind the reader said. The test signs run arrow, tent, trail, ten of each, and the reader matched them everywhere except at signs 11, 25 and 29, so the cell can rebuild its answers from the drill's:

import numpy as np

yte = np.arange(90, 120) % 3
pred = yte.copy()
pred[11], pred[25], pred[29] = 0, 2, 1
table = np.zeros((3, 3), dtype=int)
for i in range(30):
    table[yte[i], pred[i]] = table[yte[i], pred[i]] + 1
print(table.tolist())

The picture shades each count; press Next to move from the signs read right to the three that weren't.

Against a simpler reader. A score means little alone, so the report also compares the network with a baseline: the same signs read by one layer with no hidden units, trained the same 500 steps. Lesson 99 showed how: score both readers on every held-back sign, take the difference per sign (+1 where only the network is right, −1 where only the baseline is, 0 where they agree) and put a 95% range around its mean. A range that includes 0 says the data can't separate the two.

A finished report holds five things: the accuracy with its range, the confusion table, the mistakes with their confidence, this interval for the difference from the baseline, and the paragraph comparing NumPy with PyTorch below.

Worked example

Worked example: the network against a one-layer baseline

Train both readers from the same signs, then compare them sign by sign on the 30 held-back ones.

import numpy as np

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

def chances(Z):
    E = np.exp(Z - Z.max(axis=1, keepdims=True))
    return E / E.sum(axis=1, keepdims=True)

r = np.random.default_rng(2)
W1, b1 = r.normal(0, 0.5, (3, 8)), np.zeros(8)
W2, b2 = r.normal(0, 0.5, (8, 3)), np.zeros(3)
V, c = np.random.default_rng(3).normal(0, 0.5, (3, 3)), np.zeros(3)
for step in range(500):
    Z1 = Xtr @ W1 + b1
    A1 = np.maximum(Z1, 0)
    P = chances(A1 @ W2 + b2)
    dZ2 = (P - Y) / 90
    dZ1 = (dZ2 @ W2.T) * (Z1 > 0)
    W1, b1 = W1 - 0.5 * Xtr.T @ dZ1, b1 - 0.5 * dZ1.sum(axis=0)
    W2, b2 = W2 - 0.5 * A1.T @ dZ2, b2 - 0.5 * dZ2.sum(axis=0)
    dZ = (chances(Xtr @ V + c) - Y) / 90
    V, c = V - 0.5 * Xtr.T @ dZ, c - 0.5 * dZ.sum(axis=0)

reader = np.argmax(np.maximum(Xte @ W1 + b1, 0) @ W2 + b2, axis=1)
baseline = np.argmax(Xte @ V + c, axis=1)
d = (reader == yte).astype(float) - (baseline == yte).astype(float)
se = d.std() / len(d) ** 0.5
print("right:", int(np.sum(reader == yte)), "and", int(np.sum(baseline == yte)))
print("signs they read differently:", int(np.sum(reader != baseline)))
low, high = d.mean() - 1.96 * se, d.mean() + 1.96 * se
print("mean difference", round(float(d.mean()), 3), "range", round(float(low), 3), round(float(high), 3))
In the lesson you can change this and run it.

Both readers get 27 of 30 and read every sign the same way, so the difference is 0 on all 30 signs and its range is 0 to 0. That does not prove the hidden layer is useless: it says these 30 signs show no gap. The three signs both readers miss, 11, 25 and 29, sit in the overlap of the kinds, which more hidden units can't unmix. To claim a gain you would need signs the baseline gets wrong and the network gets right.

Step 6: the same reader in PyTorch

Purpose. Rebuild the reader in a few lines of PyTorch, check it reaches the same verdict, then train it in mini-batches.

Lesson 112 showed that nn.Sequential, loaded with your NumPy weights, is the same network, number for number. Do it for the reader: the seed-2 starting weights, turned around into nn.Linear's one-row-per-output layout, zero biases, and optim.SGD at rate 0.5 in place of your update lines. If the two agree, every number in your report can come from either.

Worked example

Worked example: the reader in PyTorch

Train the PyTorch reader from the same start, then test it once on the 30 held-back signs.

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

rng = np.random.default_rng(11)
centers = np.array([[0.9, 0.2, 0.1], [0.2, 0.9, 0.3], [0.1, 0.3, 0.9]])
X = np.zeros((120, 3))
y = np.zeros(120, dtype=int)
for i in range(120):
    X[i] = centers[i % 3] + rng.normal(0, 0.3, 3)
    y[i] = i % 3
Xtr, ytr = torch.tensor(X[:90], dtype=torch.float32), torch.tensor(y[:90])
Xte, yte = torch.tensor(X[90:], dtype=torch.float32), torch.tensor(y[90:])
r = np.random.default_rng(2)
W1, W2 = r.normal(0, 0.5, (3, 8)), r.normal(0, 0.5, (8, 3))
model = nn.Sequential(nn.Linear(3, 8), nn.ReLU(), nn.Linear(8, 3))
with torch.no_grad():
    model[0].weight.copy_(torch.tensor(W1.T))
    model[2].weight.copy_(torch.tensor(W2.T))
    model[0].bias.zero_()
    model[2].bias.zero_()
opt = torch.optim.SGD(model.parameters(), lr=0.5)
for step in range(500):
    opt.zero_grad()
    loss = F.cross_entropy(model(Xtr), ytr)
    if step % 100 == 0:
        print(step, round(loss.item(), 3))
    loss.backward()
    opt.step()
with torch.no_grad():
    pred = model(Xte).argmax(dim=1)
wrong = []
for i in range(30):
    if pred[i] != yte[i]:
        wrong.append(i)
print("test accuracy", round((pred == yte).float().mean().item(), 3), "misread:", wrong)
In the lesson you can change this and run it.

The loss column is Step 4's, to three places: 1.162, 0.158, 0.144, 0.141, 0.139. The verdict is Step 5's: 0.9, with signs 11, 25 and 29 misread. Four lines of loop did the work of your forward pass, softmax, loss, five backward lines and update. The match is to three places, not every digit, because PyTorch keeps its numbers in float32.

Mini-batches. Real models never see all their data in one step. A DataLoader deals the 90 training signs in batches, and each step works on one batch alone. In batches of 9 an epoch is 10 steps, so 50 epochs make 500 steps, as many as the full-batch run, each on a tenth of the signs.

Drill

The reader in mini-batches

Train the PyTorch reader in batches of 9 for 50 epochs, from the same start. Set loader, steps (the number of updates), final (the loss on all 90 training signs afterward, rounded to 3), acc (the test accuracy, rounded to 3) and wrong (the positions of the misread test signs).

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader, TensorDataset

rng = np.random.default_rng(11)
centers = np.array([[0.9, 0.2, 0.1], [0.2, 0.9, 0.3], [0.1, 0.3, 0.9]])
X = np.zeros((120, 3))
y = np.zeros(120, dtype=int)
for i in range(120):
    X[i] = centers[i % 3] + rng.normal(0, 0.3, 3)
    y[i] = i % 3
Xtr, ytr = torch.tensor(X[:90], dtype=torch.float32), torch.tensor(y[:90])
Xte, yte = torch.tensor(X[90:], dtype=torch.float32), torch.tensor(y[90:])
r = np.random.default_rng(2)
W1, W2 = r.normal(0, 0.5, (3, 8)), r.normal(0, 0.5, (8, 3))
model = nn.Sequential(nn.Linear(3, 8), nn.ReLU(), nn.Linear(8, 3))
with torch.no_grad():
    model[0].weight.copy_(torch.tensor(W1.T))
    model[2].weight.copy_(torch.tensor(W2.T))
    model[0].bias.zero_()
    model[2].bias.zero_()
opt = torch.optim.SGD(model.parameters(), lr=0.5)

loader = None
steps = 0
final = 0
acc = 0
wrong = []
print(steps, final, acc, wrong)
In the lesson, your code is checked as you write it.

For the report: NumPy against PyTorch. One paragraph is enough, and it can read like this. The PyTorch reader is the NumPy reader in a few lines: from the same starting weights it printed the same losses to three places and reached the same verdict, 27 of 30, with signs 11, 25 and 29 misread. Training in batches of 9 changed the path, not the verdict: the training loss ended higher, 0.214 against 0.138, because each step followed the slope of 9 signs instead of all 90, but the same three test signs were misread. Say which version made each number in your report, and that the two were checked against each other.

In your own words
Both readers, trained both ways, misread the same three signs. What does that say about where those mistakes come from?

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

The formula sheet

Purpose. Every formula of Module 8 in one place, with what it says and its Python line.

lessonformulain plain wordsin Python
109z = w·x + b; a = relu(z); ∂L/∂wⱼ = ∂L/∂z · xⱼone neuron: sum, squeeze, blame each weight by its inputdz * x
110Z₁ = XW₁ + b₁; A₁ = relu(Z₁); Z₂ = A₁W₂ + b₂; P = softmax(Z₂)a whole batch through two layersnp.maximum(X @ W1 + b1, 0) @ W2 + b2
111dZ₂ = (P − Y)/n; dW₂ = A₁ᵀdZ₂; dZ₁ = dZ₂W₂ᵀ where Z₁ > 0; dW₁ = XᵀdZ₁the backward pass, shape by shapeA1.T @ dZ2
113softmax(QKᵀ/√d + M)Vscore, scale, mask, share out, blendA @ V
114y = x + f(x); LN(x) = γ·(x − μ)/√(σ² + ε) + βadd the input back, then recenter and rescale each vectorx + f(x), g * (x - mu) / (var + eps) ** 0.5 + b
115h = x + Attn(LN(x)); out = h + MLP(LN(h))attention, then a small network, each added backh = x + attn(ln1(x)); h + mlp(ln2(h))
112the same two-layer network, as modulesthe NumPy formulas, named once eachnn.Sequential(nn.Linear(3, 4), nn.ReLU(), nn.Linear(4, 3))
118acc ± 1.96·√(acc(1 − acc)/n)an honest test score(acc * (1 - acc) / n) ** 0.5
In your own words
All three mistakes were made with high confidence (0.89 to 0.99). Why is that more worrying than three unsure mistakes?

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

What you've built in the Foundation

You started with place value and the four operations. You've now written, from formulas you can derive, a network that reads signs: vectors and matrices to hold the data and weights, derivatives and the chain rule to train it, probability to turn scores into chances, and statistics to say how far to trust the result. Every model later in the academy, up to a transformer, is these same pieces at a larger scale: more layers, more data, attention between the inputs, and the same loop of forward pass, loss, backward pass and update. When a later lesson writes loss.backward(), you know what the five lines inside it do.

Portfolio brief

Your own sign reader

Build a three-class trail-sign reader with NumPy alone, from an empty file, and write it up in one page. The starter makes a fresh set of 150 signs with its own noise and seed, so your numbers will be your own. Treat the last 30 signs as the test set from the start and look at them once, at the very end.

Your report should read as if for a colleague who knows the math but hasn't seen your code: what you built, the choices you made and why, how well it works, how sure that number is, and where it fails.

It must

  • A train/test split made before any training, with the test signs used once, at the end
  • A two-layer network (your choice of hidden size) with relu, softmax and cross-entropy, written from the formulas
  • A backward pass checked against a central-difference gradient check on at least two weights
  • A training run with the loss printed or plotted every so often, and a sentence on what its shape shows
  • The test accuracy with a 95% error bar
  • Three wrong predictions, each with its features, the true and predicted kinds, the confidence, and a guess at why
  • A one-page report listing every formula used, with the lesson it came from, and the shape of every matrix

Go further

  • Compare two hidden sizes or two learning rates on a validation split carved from the training signs
  • Add a bootstrap range for the test accuracy and compare it with the formula's
  • Print a 3 × 3 confusion matrix and say which kinds the network confuses most
import numpy as np

def make_signs(seed, n_per_kind, noise):
    """Signs described by (pointed, wide, tall). Kinds: 0 arrow, 1 tent site, 2 trail marker."""
    rng = np.random.default_rng(seed)
    centers = np.array([[0.9, 0.2, 0.1], [0.2, 0.9, 0.3], [0.1, 0.3, 0.9]])
    n = 3 * n_per_kind
    X = np.zeros((n, 3))
    y = np.zeros(n, dtype=int)
    for i in range(n):
        X[i] = centers[i % 3] + rng.normal(0, noise, 3)
        y[i] = i % 3
    return X, y

X, y = make_signs(seed=86, n_per_kind=50, noise=0.32)
Xtr, ytr, Xte, yte = X[:120], y[:120], X[120:], y[120:]
print(Xtr.shape, Xte.shape, "kinds in the test set:", np.bincount(yte).tolist())
In the lesson, you build it here and the tutor can review it.
In your own words
Which module of the Foundation did you lean on most in this project, and where?

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

Goes deeper in

Practice what you just read

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

Try a quiz question

Why must the test signs be set aside before any training or tuning?

  1. So their score honestly predicts new signs
  2. Because training on them would be slower
  3. To make the training set balanced
  4. Because 30 is a lucky number

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
Step by step 7 steps

Build a neural network from scratch with NumPy

A two-layer classifier for trail signs written straight from the formulas: forward pass, cross-entropy, a backward pass, training, an honest test score with its error bar, and next steps in PyTorch.

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