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,
- defines
dot,normandmatmulusing only Python loops and lists, no NumPy; - checks each one against NumPy on 100 random inputs, and stops loudly if any check fails;
- defines
numeric_grad, which works out the gradient of any function by nudging, and uses it to check a gradient worked out by hand; - 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:
dotis the : a runningtotal, addingx * yfor each pair fromzip(a, b).normreusesdot: the length is the square root of a vector dotted with itself, since .matmulreusesdottoo: entry is row of dotted with column of . Column is[B[r][j] for r in range(d)]. Check the inner sizes first, and raise aValueErrorthat says what's wrong if they differ.
Try writing them yourself before you look. Here's one way:
, and , as in lesson 1.2. Work out the top-left entry of the matrix product by hand to be sure: .
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).
All 300 checks pass: 100 each for dot, norm and matmul. The last cell tries a matrix times a 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):
In words: is a vector of zeros with a 1 in place , so nudges only input . 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:
Over 100 random points, the largest gap between the nudge and the formula is about . That's rounding, not a mistake. The rule of thumb: below , 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:
In words: is what you want to know (sick), is the evidence (a positive test). The bottom counts both ways to see the evidence: true and the evidence shows, or false and it shows anyway.
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,normandmatmulwritten 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 againstA.T. - Write
cosine(a, b)fromdotandnorm(lesson 1.3), and test it against the NumPy version. - Write
entropy(p)andcross_entropy(p, q)(lesson 1.11), test them, and makecross_entropyclipqso a 0 can't producenan. - Use
numeric_gradto check lesson 1.7's neuron: write the loss as a function of the vector 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.
- Goodfellow, Bengio and Courville, Deep Learning, chapter 2: Linear Algebra: the dot product, norms and the matrix product
- Goodfellow, Bengio and Courville, Deep Learning, chapter 4: Numerical Computation: gradients, and checking them numerically
- NumPy: numpy.isclose: comparing floats with a tolerance
- The Python Language Reference: The assert statement: stopping with an AssertionError when a check fails