Project 2 of 14, for Aaesha
Tiny Autograd Engine
A micrograd-style autograd engine: numbers that remember how they were made, so one backward() shares out the blame for a mistake, the puzzle every learning brain has to solve. Drawn as a graph, then a neuron that trains on it.
Sign up free to open itLog in
Act 7 needs a free account, so your work is saved as you go. Act 1 is open to everyone.
The brief
- AaeshaWhen a network gets an answer wrong, which of its numbers is to blame? Brains have the same puzzle, funnily enough.
- AaeshaNobody knows yet how a brain shares out the blame, but a network can do it mechanically.
- NeilAt the moment somebody rewrites backward by hand every time, and it's usually me, and I usually get it wrong.
- AaeshaSo every number gets its own receipt, and I'm a big fan of receipts.
In engine.py, finish Value: one number that remembers how it was made. + is already written, as the pattern for the rest.
Value(data)keeps the number in.data, its gradient in.grad(starting at 0), the values it was made from in.parents(a tuple, empty for a number you typed in) and the operation's name in.op.a * b,a ** 2(the power is a plain number),a.exp()anda.relu()each make a newValuethat records its parents and a_backwardfunction: how blame arriving at the new value passes back to each parent. Blame is added to a parent's.grad, never written over it. Plain numbers mixed in, as in2 * a, work too.backward(): put every value this one was made from in order, each after its parents; set this value's.gradto 1; then go through the order backwards, calling each value's_backward.
Then, in neuron.py, a neuron built on the engine:
Neuron(n_inputs)keeps a list ofValueweights in.weights, one per input, and aValuein.bias, all starting at 0.parameters()gives back the weights, then the bias. Calling the neuron on a night's readings gives the sigmoid of the weighted sum, as aValue.train(neuron, nights, labels, rate, steps): each step, set every gradient to 0, work out the mean squared error over every night, callbackward(), and move each weight against its gradient. It returns the loss at each step.- Run as a program, it learns the stargazing log and gives tonight's chance.
Loss: 0.2500 at the start, 0.0476 at the end Agrees with 24 of 24 nights Tonight: 0.90, go ahead
What you learn
What's in it
- Numbers with receipts
- Each card passes blame back
- One card, used twice
- Who passes the blame first
- How Paul would do it
- Fix Yahya's version
- The tiny engine
- Start each step from zero
- Backward, twice
- A jump has no slope
- A neuron on cards
- Ship it