The maths you need · lesson 12 of 12
Parts in this lesson
Adef dot(a, b): ...the formula, as a loop
Bassert np.isclose(dot(a, b), a @ b)a test against NumPy
Cnumeric_grad(f, p)the gradient by nudging (1.6 and 1.8)
Dposterior(prior, ...)Bayes’ rule as a function (1.9)

Project: maths you can run

Last updated

Reading a formula and writing it as code are different skills, and this course needs both. In this project you’ll write small Python functions for the stage’s key formulas: a dot product, a norm and a matrix product by hand, a numerical gradient, and a Bayes calculator. Then you’ll test every one against NumPy on hundreds of random inputs. The gradient checker you build here is the one you’ll use to check every derivative in Stages 3 to 6.

By the end of this lesson you can

  • Turn a formula written in symbols into a short, plain Python function
  • Test your own functions against NumPy on many random inputs, with assert and np.isclose
  • Build a numerical gradient and use it to check a hand-worked derivative
  • Write a Bayes calculator and use it to update a probability twice

Plan it

The aim: a notebook, maths.ipynb, with one small function for each key formula in this stage, each tested against NumPy. Writing the formula yourself is the surest way to find out whether you really read it.

What you'll make: a notebook that, run from the top,

  1. defines dot, norm and matmul using only Python loops and lists, no NumPy;
  2. checks each one against NumPy on 100 random inputs, and stops loudly if any check fails;
  3. defines numeric_grad, which works out the gradient of any function by nudging, and uses it to check a gradient worked out by hand;
  4. defines posterior, a Bayes calculator, and uses it on a medical test taken twice.

The one rule: no NumPy inside the hand-written functions, only lists, loops and zip. NumPy is only for checking them.

dot, norm and matmul by hand

Start with three formulas from lessons 1.2 to 1.4. Each line of code should match a piece of the symbols:

a⋅b=∑i=1daibi‖a‖=a⋅a(AB)ij=∑kAikBkj
  • dot is the ∑: a running total, adding x * y for each pair from zip(a, b).
  • norm reuses dot: the length is the square root of a vector dotted with itself, since a⋅a=∑ai2.
  • matmul reuses dot too: entry (i,j) is row i of A dotted with column j of B. Column j is [B[r][j] for r in range(d)]. Check the inner sizes first, and raise a ValueError that says what's wrong if they differ.

Try writing them yourself before you look. Here's one way:

maths.ipynb

(1,2,3)⋅(4,5,6)=4+10+18=32, and ‖(3,4)‖=5, as in lesson 1.2. Work out the top-left entry of the matrix product by hand to be sure: 1×10+2×30=70.

Check each against NumPy

Three examples that come out right don't prove much. Test on many random inputs instead, comparing with NumPy each time. assert stops the notebook with an AssertionError the moment a check fails, so silence means every check passed.

Compare floats with np.isclose (or np.allclose for arrays), never ==: your loop and NumPy add in different orders, so the last digits can differ by rounding (lesson 1.6).

maths.ipynb

All 300 checks pass: 100 each for dot, norm and matmul. The last cell tries a 1×3 matrix times a 2×2 one, and gets your own clear ValueError instead of a wrong answer or a confusing IndexError from deep inside a loop. Testing that a function fails properly on bad input is part of testing it.

numeric_grad

Now the tool you'll use most. numeric_grad(f, p) takes any function of a vector and a point, and returns the gradient there (lesson 1.8), by nudging each input in turn with the central difference (lesson 1.6):

∂f∂pi≈f(p+hei)−f(p−hei)2h

In words: ei is a vector of zeros with a 1 in place i, so hei nudges only input i. In code it's step, a copy of np.zeros_like(p) with step[i] = h.

To test it, take a function whose gradient you can work out by hand with lessons 1.6 to 1.8:

f(p)=p12p2+ep2,∇f=(2p1p2,p12+ep2)
maths.ipynb

Over 100 random points, the largest gap between the nudge and the formula is about 3×10−10. That's rounding, not a mistake. The rule of thumb: below 10−6, the hand-worked gradient is right; much above, look for a slip like lesson 1.7's forgotten inner derivative. Every time Stages 3 to 6 work out a gradient by hand, they check it exactly like this.

A Bayes calculator

Last, lesson 1.9's rule as a function. Name the arguments after what they mean, not after letters:

p(H∣E)=p(E∣H)p(H)p(E∣H)p(H)+p(E∣not H)(1−p(H))

In words: H is what you want to know (sick), E is the evidence (a positive test). The bottom counts both ways to see the evidence: H true and the evidence shows, or H false and it shows anyway.

maths.ipynb

After one positive test the chance is 0.0902, as in lesson 1.9. A second independent positive test starts from that as its prior, and the chance jumps to 0.9075. That's Bayes' rule as a way of learning: today's answer becomes tomorrow's starting point. (It only works if the two tests make mistakes independently; the same test run twice on the same sample usually doesn't.)

Finished

You've turned the stage's maths into code you can trust. Your notebook

  • has dot, norm and matmul written with plain loops,
  • checks all three against NumPy on 100 random inputs each, and checks that bad sizes raise a clear ValueError,
  • has numeric_grad, checked against a gradient worked out by hand,
  • has posterior, used for one test and then two.

Restart the kernel and run every cell from the top (lesson 0.10). If every check passes, it's done. Keep numeric_grad: you'll paste it into notebooks for the rest of the course.

Try next:

  • Add transpose(A) using only lists, and test it against A.T.
  • Write cosine(a, b) from dot and norm (lesson 1.3), and test it against the NumPy version.
  • Write entropy(p) and cross_entropy(p, q) (lesson 1.11), test them, and make cross_entropy clip q so a 0 can't produce nan.
  • Use numeric_grad to check lesson 1.7's neuron: write the loss as a function of the vector (w,b) and compare with the chain rule.

Stage 2 uses none of this maths yet: it's about what learning is and how to tell whether a model is any good. Stage 3 brings all of it back, starting with lines, gradients and gradient descent.

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Machine Learning