Your first neural network, for developers who are scared of math

Day 1 of a series for developers who are new to AI

Draw a digit in the black box, with your mouse or your finger.

The program that just read your digit is a neural network, about thirty lines of Python long. This page shows you how to build the same thing, even if you know nothing about artificial intelligence or machine learning.

Building a neural network feels out of reach. Nearly every explanation out there opens with partial derivatives and matrix products. That’s a shame, because the subject gets much friendlier once you start with practice. Developers are no dumber than anyone else, and a neural network is, after all, something you write in code.

So let’s start from code. We’ll take a three-line program that any developer can read, and grow it together, one small step at a time, until it becomes the one behind the black box. If you can read an if and a for loop, you can follow along.

We’re going to write everything by hand. In real life you’d use a specialized library, and we’ll get to that at the end, once things have fallen into place.

One word comes up throughout: “knob”. The network in the black box holds 2,410 numbers. I call them knobs, like the ones on a mixing desk: turn one, and the program’s answer shifts a little. A neural network is a set of knobs, plus a program that tunes them on its own from examples. At the end of each step, a yellow box tells you how many knobs we have and how they got tuned.

Together, we’re going to add knobs to a mixing desk, and find a way to set them right.

your drawing 2,410 knobs 3 confidence
Turn a knob, and the answer shifts a little.

A neuron is three knobs

We write a neuron in three lines of Python, then set its three numbers by hand.

A drawn digit is 64 pixels, and I don’t know how to plot a graph in 64 dimensions. So let’s begin with an easier problem: deciding whether an email is spam, using just two numbers to describe it.

Two things often give spam away:

  1. it’s stuffed with links,
  2. it’s full of CAPITAL LETTERS.

Yes, that’s a caricature. A real filter looks at plenty of other things, but two numbers are enough to understand the idea, and they fit on a graph. So I made up twenty emails. For each one I counted the links and the words in capitals, then noted whether it was spam.

If I asked you to write the filter, you’d probably start with this:

def is_spam(nb_links, nb_caps):
    return nb_links > 6 and nb_caps > 4

We’ve all written that kind of function. You eyeball a few emails, pick the 6 and the 4, and tweak them the day some spam slips through.

A neuron does the same job, except it finds its numbers by itself. Its calculation is simpler than your if, and takes four moves:

  1. It multiplies the number of links by a first number, w1.
  2. It multiplies the number of capitals by a second one, w2.
  3. It adds the two results, plus a third number, bias, which is the same for every email.
  4. It checks whether the total is above zero.

Above zero, it answers 1, “this is spam”. Otherwise it answers 0.

That third number is called the bias, and it sets how suspicious the neuron is. At −6, every email starts six points behind, and needs plenty of links and capitals to climb back above zero. At zero, a single link would be enough to cry spam.

Let’s put that in Python. Two pieces are missing from the function below, and it’s up to you to fill them in. Each one comes with a question to guide you, and if you pick the wrong answer, you’ll be told why. Once it’s complete, the code runs right here on the page.

It prints 1 for the first email (spam) and 0 for the second. This three-line function is a complete neuron. The diagram below walks through the first email.

links 8 capitals 9 × 0.5 × 0.5 4 + 4.5 bias − 6 2.5 > 0 ? output 1
The first email, worked out by hand.

The two multipliers, w1 and w2, are called weights. The higher a weight, the more its input counts in the decision. The bias sets the bar: at −6, the rest of the calculation has to go above 6 before the neuron answers 1. Try it. Change −6 to −10 in the block and run it again: the first answer drops to 0.

Those two weights and that bias are our three knobs. With 0.5, 0.5 and −6, the neuron got two emails right. But we have twenty, and a good setting has to work for all of them.

Let’s set them by hand first, to get a feel for what the machine will have to do. On the graph, each dot is an email: orange diamonds are spam, blue circles aren’t, and the orange area covers the emails the neuron calls spam. The goal is to get every diamond inside the orange area and every circle outside. To begin with, the neuron only looks at links, and gets five emails wrong. There’s no single right answer: several settings score twenty out of twenty.

You probably did what everyone does: move a slider, look at the score, and keep going the same way as long as it climbs. Along the way you can see that the two weights rotate the boundary, while the bias shifts it without changing its tilt. Training a network means automating that gesture.

You just set 3 knobs by hand. It takes 2,410 to read a digit, and billions for something like ChatGPT. Tuning that many knobs is what takes so much computing power.

When you get down to it, a neural network is a pretty dumb thing: you separate points in a space, adjusting knobs until the good ones land on one side and the bad ones on the other.

The neuron learns to tune itself

We show the neuron the emails one at a time, and adjust its three knobs whenever it gets one wrong.

The trouble is that a program can’t “look at the score”. It needs a mechanical rule.

The one we’ll use is nearly seventy years old, and it couldn’t be simpler: show the neuron an email, and compare its answer with the truth. There are three possible cases.

  1. Either it’s right, and we leave everything alone.
  2. Or it let spam through: its total was too low, so we nudge all three knobs up.
  3. Or it flagged a normal email: its total was too high, so we nudge them down.

How big is a nudge? Here, each weight moves by a tenth of its input. An email with ten links weighed ten times more in the total than an email with one, so its weight gets ten times the correction. And an input of zero can’t have contributed to the mistake: its weight stays put.

Click “Next mistake” two or three times to watch a correction up close. The neuron jumps to the next email it gets wrong, and the boundary moves. After that, “Train” does the rest on its own.

Showing the twenty emails once isn’t enough. When we reach the end of the list, we go back to the first email, and each full lap is called a pass. It takes eleven of them before the neuron stops making mistakes. And the error count doesn’t glide down: 13, 7, 7, 7, 6, 7, 9… That’s normal. Fixing one email sometimes breaks another.

Now for the code: the same training, in Python. First the data, and a neuron whose three knobs are all at zero.

Eleven errors. No surprise there: every knob is at 0.0, so the neuron answers 0 to everything. Eleven of the twenty emails are spam, and it only gets the other nine right.

On to the training loop. It’s actually two for loops, one inside the other. The inner one shows the twenty emails one by one: that’s a pass. The outer one, for epoch in range(1, 51), repeats the pass up to fifty times, and we leave it as soon as a pass ends without an error. The variable is called epoch because that’s the usual name for a pass, the one you’ll meet in all the docs.

The three cases from earlier boil down to a subtraction: error is 0 when the answer is right, 1 when the neuron let spam through, and −1 for a false alarm.

It’s your turn again, with the three lines that adjust the knobs. They all follow the same formula, knob += step * error * input. Once the code is complete, click “Explain line by line” and we’ll go through it together.

This program has a name, the perceptron, and it dates back to the late 1950s (we owe it to Frank Rosenblatt). The docs have a name for the step variable too: the learning rate.

The easiest way to understand what a line is for is to delete it and see what breaks. Let’s try that twice.

First, delete bias += step * error and run it again. The training goes through its fifty passes and never gets there. Without a bias, the boundary has to go through the bottom left corner of the graph, and all it can do is pivot around that point.

Next, put the line back, go up one block and change (1, 1, 0) to (1, 1, 1). You’ve just told the neuron that an email with hardly any links or capitals is spam. Run the training again: fifty passes, and still nothing. A single mislabeled example out of twenty is enough to block everything. Training is said to converge when the knobs end up settling on values that work. Here it no longer converges: the knobs keep moving at every pass and never settle. That’s why, with real data, people spend more time cleaning examples than writing code. Remember to click Restore before you move on.

With the original data, training stops at 0.1, 0.6 and −2.8. Remember neuron, the three-line function from the beginning? It hasn’t changed. We just pass it those three values instead of 0.5, 0.5 and −6. When people talk about a model, that’s all they mean: this function, and the three numbers training came up with. Notice that the weight on capitals is six times the weight on links, though nothing in the code suggests it. Don’t read too much into that: several lines separate these twenty points, and the neuron kept the first one that worked.

We can now show it emails it has never seen.

Still 3 knobs, but this time the machine set them alone, from twenty examples.

One neuron isn’t enough

We give the neuron a more realistic problem, and it fails. Let’s see why.

OK, I cheated a little. I picked those twenty emails so that a straight line could separate them. A real inbox is messier. A newsletter can hold ten links and be perfectly legitimate. An enthusiastic uncle can write everything in capitals without a single link. Neither of them is spam: you need both signs at once.

So I prepared forty emails that follow this rule: all the spam sits in the top right corner of the graph. Let’s run the same neuron on them.

Thirty passes, and no progress. A thousand wouldn’t change anything. A neuron can only draw a straight line, and fencing off a corner takes two. Wherever it puts its line, some emails end up on the wrong side.

This limit has been known for a long time. Marvin Minsky and Seymour Papert proved it in 1969 in a book, Perceptrons, which often gets the blame for the long loss of interest in neural networks that followed. Yet the solution is there on the graph: to draw two lines, you need two neurons.

3 knobs aren’t enough for this problem. It takes several neurons, and therefore more knobs.

The neuron learns to doubt

We replace the neuron’s yes or no with a confidence between 0 and 1, and watch it walk down, step by step, to the right setting.

Before we connect neurons together, we need to fix a flaw I skipped over. Our neuron answers 0 or 1, with nothing in between. Whether it was off by a hair or by a mile, it gets the same correction. On its own, it copes. But several neurons in a row learn nothing that way.

So instead of a flat yes or no, the neuron will give a score between 0 and 1, like a percentage of certainty. Near 1, it’s almost sure the email is spam. Near 0, almost sure it isn’t.

To do that, we replace the if with a small function that squeezes any total between 0 and 1. Its name is scarier than what it does: it’s the sigmoid, so called because its curve is shaped like an S.

10 0.01"definitely not" 0.5"I don't know" 0.99"definitely" total −5total 0total 5 the total computed by the neuron →
The sigmoid turns the neuron's total into an answer between 0 and 1.

Read the curve from left to right. A very negative total gives an answer close to 0, a very positive one gives an answer close to 1, and in between it climbs smoothly. When the total is zero, the answer is 0.5, which you can read as “I don’t know”.

In Python, the sigmoid is a one-liner. I promise it’s the only math formula we’ll take apart.

You don’t have to memorize that line, but you can read it without doing any math. It computes “1 divided by 1 plus something”. That something is math.exp(-score): a number that’s always positive, shrinks when the score goes up, and swells when it goes down. Its size decides everything.

  • For a score of 5, it’s 0.007, next to nothing. We compute 1 / 1.007, which gives 0.99.
  • For a score of 0, it’s exactly 1. We compute 1 / 2, which gives 0.5.
  • For a score of −5, it’s 148. We compute 1 / 149, which gives 0.01.

Those are the three values the block prints, and the three dots on the diagram.

The neuron now answers with a confidence: it says spam, and tells you whether it’s 99% sure or 55% sure. Be careful, though: it can be 99% sure and still be wrong.

What about the training loop? It stays the same. The only difference is that error is no longer a whole number.

When the neuron says 0.9 for an email that really is spam, the error is 0.1 and the knobs barely move. When it says 0.1 for that same email, the error is 0.9 and the correction is nine times stronger. The bigger the error, the stronger the correction.

This way of tuning the knobs has a scary name, gradient descent. Forget the name for a minute, and picture yourself walking down a hill in the fog. You can’t see the valley, but your feet can feel which way the ground slopes. You take a step down, and start again. Where it’s steep, you take a big step. Where it’s nearly flat, a small one, because the bottom isn’t far.

Training does exactly that. The hill is the neuron’s error: high when it’s badly wrong, low when it’s nearly right. To draw it, we keep a single knob, the weight on capitals, and plot the total error over the twenty emails for each value that knob can take. In the docs, this total error is called the loss.

The ball is the knob. It rolls down at each step, and the steeper the slope, the further it goes. “Gradient” is just the fancy word for that slope, and “gradient descent” means “going down by following the slope”.

In the code, the line s2 += step * error * nb_caps works out that slope without having to plot the curve. There’s a mathematical proof behind the formula, and this is the one place in the article where I’m asking you to take my word for it (as I did myself).

Try the three step sizes. With the smallest, the ball still hasn’t reached the bottom after sixty steps. With the largest, it jumps over the dip and bounces from one side to the other without ever settling. On a real network, you find the right size by trial and error, and I know of no method that spares you from it.

A real network has millions of knobs. Each one has its own slope, and they all go down at the same time.

We still have only three knobs. What changed is the answer: instead of yes or no, the neuron gives a confidence between 0 and 1. That’s what we were missing to connect several neurons together.

Connecting neurons together

We link neurons into a network, and watch that network fold its boundary.

Back to our corner. Take one neuron that lights up when an email has a lot of links, and another that lights up when it has a lot of capitals. A third neuron receives their two answers, and says spam when both are lit.

Those three neurons are already a network. The first two form the hidden layer. The word is misleading, because there’s nothing secret about their answers: a print is all it takes to read them. What’s missing is the answer key. For each email, the data says “spam” or “not spam”, and that’s the right answer for the output neuron. No column says what the two in the middle should have answered.

hidden layer links capitals lotsof links? lotsofcapitals? bothat once? spam? provided by the data8 links, 9 capitals no answer keynothing says which answer is right answer key provided"this email is spam"
Three neurons connected together: two in the hidden layer, one at the output.

Hidden neurons use a function that’s even simpler than the sigmoid, max(0, total). If the total is negative, the neuron returns zero, and we say it’s off. Otherwise it returns its total. Libraries call this function ReLU, short for rectified linear unit. That’s a fancy name for a max.

Each hidden neuron still draws a straight line. The output neuron combines those lines, and the final boundary folds along each of them, like a sheet of paper. Start the training to see the folds appear.

This is the most important graph on the page. Take your time and play with it.

With a single hidden neuron, we’re back to a straight line and the failure we just saw. With two, the network can cut out the corner, but doesn’t always manage to. Click “New draw” a few times: the knobs start from random values, and some draws lead nowhere. In particular, a neuron can end up off for every email. From then on it gets no corrections at all, and stays off until the end. That’s called a dead neuron.

This is why you always plan for more neurons than strictly necessary. With four or eight, enough of them stay active even if one dies.

Here, you can read the bare minimum off the graph: a corner is two straight lines, so two hidden neurons. On a real problem there’s nothing left to draw, and nobody can work that number out in advance. You experiment: put plenty in, see if the network learns, and adjust.

Try the other datasets too. Circling an island or cutting up a checkerboard takes more folds: compare four hidden neurons with sixteen.

Before we get to the code, let’s count the knobs in a network with four hidden neurons. A neuron is still the function from step 1: it receives numbers, multiplies each by a weight, adds everything up and adds its bias. So it needs one weight per number it receives. A hidden neuron receives two numbers, the links and the capitals. The output neuron receives four, the answers of the four hidden neurons.

2 inputsjust numbers4 hidden neuronseach repeats the step 1 calculation1 output neuronthe same calculation linkscapitalsneuronneuronneuronneuronneuronspam? 8 weights8 wires 4 biases4 neurons 4 weights4 wires 1 bias1 neuron +++ = 17 one weight, on each wireone bias, in each neuron
Each circle is a neuron. It has one weight per incoming wire, and one bias. The output receives four wires, so it has four weights.

We’re up to 17 knobs. Now we need the code that tunes them.

When the network is wrong, who’s to blame?

We share the error out among the neurons, and write a complete network in Python, with no library.

We still have to train this network. The output neuron is easy: we know the right answer. We compute its error and apply the usual rule, with the hidden neurons’ answers as its inputs.

For the hidden neurons, we don’t know the right answer. And with no right answer there’s no error to compute, so no correction.

The trick is to share the output’s error out among them. Think of a team after a bad decision. The output neuron decided by listening to each of its colleagues more or less closely, and how closely is exactly what the weight says. A hidden neuron it listened to a lot takes a large share of the error, one it barely listened to takes a small share, and one that was off, and said nothing, takes none.

loudweight 0.9share 0.54quietweight 0.2share 0.12offweight 0.7share 0 error 0.6 output neuron share = error × weight, or zero if the neuron was off
The output's error is shared out among the hidden neurons.

In Python, a hidden neuron’s share looks like this:

blame = error * w_out[j] if hidden[j] > 0 else 0

Once we know that share, we correct the hidden neuron with the rule we’ve used from the start, and each of its knobs moves by step * blame * input.

The error travels backwards, along the same connections, multiplied by the same weights. This technique is called backpropagation, and it’s what brought the field back to life in the mid-1980s. In a network with ten layers, you share the error out ten times, from the output back to the input.

Here are the forty emails, and a network with four hidden neurons, hence seventeen knobs. The block is longer than the previous ones, but don’t panic, there’s nothing new in it: lists, for loops, and the calculation from our very first neuron, repeated for each one. Here too, “Explain line by line” walks you through it.

Three lines deserve a word.

  • random.uniform(-1, 1): the knobs start from random values. If they were all zero, the four hidden neurons would be off, and none of their knobs would ever move.
  • random.seed(1): a computer doesn’t really draw at random, it unrolls a sequence of numbers from a starting point called the seed. By setting it to 1, you get the same draw as me, and so the same results as in the article.
  • / 10: the inputs are divided by 10, because a network learns better with numbers between 0 and 1.

Now the training. You get to place the error sharing: there are three blanks to fill in.

The network cuts out the corner in twelve passes, with no library at all. The graph is drawn by calling your own predict function, and it updates if you change the code.

Those twelve passes hang by a thread, as three experiments will show. Go up one block, set HIDDEN to 1 and run the training again. It goes through two hundred passes for nothing, since we’re back to a straight line.

Set it back to 4, then change random.seed(1) to random.seed(4). A different seed means a different random draw for the knobs. With seed 4, the network runs its two hundred passes and still gets four emails wrong. Neither the code nor the data moved: only the starting point changed. It’s the “New draw” button from step 5, and the article uses seed 1 for one reason: it works.

Finally, go back to random.seed(1) and remove both / 10 in forward. The network stops learning altogether. With inputs ten times larger, the first corrections are ten times too strong, and switch the hidden neurons off for good.

All 17 knobs are tuned by Python you completed yourself. What comes next uses the same code, with more neurons.

The network reads your digits

We scale up the same network, train it on 1,500 handwritten digits, and it reads yours.

So far we’ve had two inputs, because two fit on a graph. But the network works just as well with 64. An image of 8 by 8 pixels in shades of gray is 64 numbers, and we can feed them in as they are.

The examples come from a dataset put together in 1998 by E. Alpaydin and C. Kaynak, and released under the CC BY 4.0 license. I use 1,797 handwritten digits from it, each with the digit the person meant to write. Here are twenty of them.

These images are blurry, and yet you read them without thinking. Now try to imagine the function that would tell a 3 from an 8 out of 64 shades of gray, one if at a time. For this kind of problem, it’s easier to supply examples than to write rules.

With 64 inputs and dozens of neurons, hand-written loops become long and slow. So we’ll use numpy, a library that does the same multiplications and additions on whole arrays. The next block loads the data and shows one image the way the network receives it.

The network keeps the same shape, with one hidden layer between the inputs and the output. It has 64 inputs, 32 hidden neurons and 10 outputs. Add up the weights and the biases, and you get the 2,410 knobs from the beginning.

Only one thing changes compared with the email network: the output. Until now the network answered a yes or no question, spam or not, and one output neuron was enough. Here it has to choose between ten digits. It needs ten output neurons, one per digit, each giving its confidence.

If we kept a sigmoid on each of them, every neuron would answer in its own corner. The network could say “a 3, 90%” and “an 8, 85%” for the same image, even though there’s only one digit in it.

So we replace the ten sigmoids with a split: the ten neurons share 100% of confidence between them. The highest total takes the biggest share, and the others split what’s left. The answer becomes readable, for example “a 3 at 92%, an 8 at 5%”, and that’s what the black box at the top of the page displays. This split is called softmax, and it takes two lines of code.

The rest is what you wrote in step 6, in a more compact form. Four bits of notation are new.

  • x @ W1: the at sign is a Python operator that numpy uses to do, for all the neurons at once, the “multiply each input by its weight, then add everything up”. It replaces your for loops. W1 is the array that holds all the weights of the hidden layer.
  • np.maximum(0, ...): the hidden neurons’ max(0, total), applied to a whole array.
  • blame: the error sharing, computed for all the hidden neurons at once.
  • / 20: the network corrects its knobs after each bundle of 20 images, called a batch, rather than after every image. The corrections are smoother.

The code is split into four blocks, to run in order. Each one has its “Explain line by line” button.

First we set 297 images aside. The network won’t see them during training: they’re there to grade it, to check that what we built also works on these images.

Then we create the knobs, stored in four arrays and drawn at random, as in step 6.

Next come the functions that make the network answer. It hasn’t learned anything yet, so it’s guessing: with ten possible digits, it’s right about one time in ten.

And finally, the training. It’s the loop from step 6, in bundles of 20 images.

The last line shows two scores: 99% on the images the network has seen thirty times, 90% on those it’s discovering. It loses nine points, and there are two possible reasons.

The first is that it learned by heart some details of its 1,500 training images that are useless anywhere else. That’s called overfitting. It’s the student who knows all the past exam papers by heart, and freezes in front of a new question.

The second is that the images we set aside don’t quite look like the others. I took the last 297 in the file, without shuffling. To see what difference it makes, replace the first two lines of the “We set 297 images aside” block with the ones below, which pick images at random, then run the training again.

order = np.random.default_rng(0).permutation(1797)
train_x, train_y = images[order[:1500]], labels[order[:1500]]
test_x, test_y = images[order[1500:]], labels[order[1500:]]

The score on unseen images goes up to 98%. The code is the same, and the network still has 1,500 images to learn from. So in our case, the second reason does most of the damage. I think the images in the file are sorted by person, so that at the end the network runs into handwriting it has never met, but I haven’t checked. I kept the split that gives 90%, since it’s closer to what awaits you with your own handwriting. Click Restore before you move on.

The only score that matters is the one you measure on data the model has never seen. That’s what the 297 images were for.

One harder test remains: your own handwriting, which the network has never come across. The box below is the one from the top of the page, this time wired to the network you just trained.

Your drawing is shrunk to 64 numbers, then handed to the forward function from the block above. Change the number of hidden neurons or the number of passes, run it again, and draw another one.

The complete code for this step, ready to copy and paste
import numpy as np

data = np.loadtxt("digits.csv", delimiter=",")
images = data[:, :64] / 16        # 64 pixels per image, scaled to between 0 and 1
labels = data[:, 64].astype(int)  # the expected digit

train_x, train_y = images[:1500], labels[:1500]
test_x, test_y = images[1500:], labels[1500:]

rng = np.random.default_rng(0)
W1 = rng.normal(0, 0.1, (64, 32))   # from 64 pixels to 32 hidden neurons
b1 = np.zeros(32)
W2 = rng.normal(0, 0.1, (32, 10))   # from 32 hidden neurons to 10 outputs
b2 = np.zeros(10)

def softmax(scores):
    exp = np.exp(scores - scores.max(axis=1, keepdims=True))
    return exp / exp.sum(axis=1, keepdims=True)

def forward(x):
    hidden = np.maximum(0, x @ W1 + b1)   # the hidden layer
    probs = softmax(hidden @ W2 + b2)     # ten percentages per image
    return hidden, probs

def accuracy(x, y):
    guesses = forward(x)[1].argmax(axis=1)   # the most likely digit
    return round(100 * (guesses == y).mean())

step = 0.3

for epoch in range(1, 31):
    for start in range(0, 1500, 20):
        x = train_x[start:start + 20]
        y = train_y[start:start + 20]
        hidden, probs = forward(x)

        expected = np.eye(10)[y]             # a 1 in the slot of the right digit
        error = expected - probs
        blame = (error @ W2.T) * (hidden > 0)

        W2 += step * hidden.T @ error / 20
        b2 += step * error.mean(axis=0)
        W1 += step * x.T @ blame / 20
        b1 += step * blame.mean(axis=0)
    if epoch % 5 == 0:
        print("Pass", epoch, ":", accuracy(train_x, train_y), "% on seen images,",
              accuracy(test_x, test_y), "% on the others")

To run it on your machine, you need numpy (pip install numpy) and the file digits.csv in the same folder.

You’ll find that it makes more mistakes than the one at the top of the page. Yet both have the same code and the same number of knobs. The one at the top has seen more examples: each image was shown to it several times, slightly shifted or slightly tilted. The code is the same, there are just more examples, and that’s enough to make the network more tolerant of unfamiliar handwriting.

When it gets one wrong, look at the little 8 by 8 image next to its answer. That’s all it receives, and quite often you’d hesitate too.

Some handwriting gives it trouble whatever you do. A 1 with a bar at the bottom is often taken for a 2, probably because the people who supplied the examples didn’t write it that way. The network only knows what its examples contain.

2,410 knobs, tuned by thirty lines of Python, can now read your handwriting.

Making it all simpler with a library

We rewrite the digit network with PyTorch, and find everything we did by hand inside its few lines.

Until now you’ve written everything by hand: the multiplications, the error sharing, the knob corrections. That was on purpose, to see what each line does. In real life, nobody does that. You leave those calculations to a library, usually PyTorch, and keep only the decisions: how many neurons, how many passes, what step size.

The four blocks below don’t run on this page, because PyTorch is too heavy for a browser. Put end to end, they form a complete script for the network from step 7, which you can run on your machine. Let’s read them one at a time.

The first block loads the data. It’s the same digits.csv as in step 7: 1,797 lines, each with 64 pixels followed by the expected digit. The only newcomer is torch.tensor: PyTorch doesn’t work on numpy arrays but on its own, called tensors, and needs to be told what type of numbers they hold.

import numpy as np
import torch
from torch import nn

data = np.loadtxt("digits.csv", delimiter=",")
images = torch.tensor(data[:, :64] / 16, dtype=torch.float32)   # 64 pixels per image, between 0 and 1
labels = torch.tensor(data[:, 64], dtype=torch.long)            # the expected digit

train_x, train_y = images[:1500], labels[:1500]   # 1,500 images for training
test_x, test_y = images[1500:], labels[1500:]     # 297 images set aside

The second block builds the network.

torch.manual_seed(0)   # the seed, like random.seed in step 6

model = nn.Sequential(
    nn.Linear(64, 32),
    nn.ReLU(),
    nn.Linear(32, 10),
)

nn.Sequential chains stages together, in the order the numbers go through them.

  • nn.Linear(64, 32): a layer of 32 neurons, each receiving 64 inputs. It creates and stores the 64 × 32 weights and 32 biases for you, the ones we called W1 and b1, and starts them at random values.
  • nn.ReLU(): the hidden neurons’ max(0, total).
  • nn.Linear(32, 10): the output layer, ten neurons listening to the 32 hidden ones. Those are our W2 and b2.

One question remains: where do the 64, the 32 and the 10 come from, and how would you find them for another problem? Two of these numbers are dictated by the data, and only one is up to you.

  • 64: dictated. An image is 8 by 8 pixels, so 64 input numbers.
  • 10: dictated. There are ten possible digits, so ten outputs.
  • 32: your choice. It’s the number of hidden neurons. The only constraint is that it has to be the same on both lines, since what comes out of the first layer goes into the second.

Does it matter if you get one wrong? With a dictated number, you’ll know right away: write 60 instead of 64, or let the two 32s differ, and PyTorch stops with a dimension error. With the number you choose, nothing breaks, the network just learns more or less well. The one from step 7 recognizes 79% of unseen images with 4 hidden neurons, 90% with 32 and 91% with 64. You try, you look at the score, and you keep what works.

Those three lines replace the creation of the knobs and the forward function. Softmax is missing, but it’s waiting in the next block.

The third block trains the network, on the train_x and train_y from the first block.

loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.3)

for epoch in range(30):
    for start in range(0, 1500, 20):
        x = train_x[start:start + 20]
        y = train_y[start:start + 20]

        loss = loss_fn(model(x), y)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

The two for loops are yours: thirty passes, in bundles of twenty images. Everything else fits in four lines.

The diagram takes up this block. The two loops are the two frames, and each line sits across from what you had written by hand.

for epoch in range(30):↻ 30 passes over the 1,500 images for start in range(0, 1500, 20):↻ 75 bundles of 20 images per pass x = train_x[start:start + 20] y = train_y[start:start + 20]We take the next 20 images, and their 20 right digits. loss = loss_fn(model(x), y)The network answers, and we measure its error.by hand, it wasforward(x), then expected - probs optimizer.zero_grad()We clear the sharing from the previous bundle. loss.backward()We share the error among all the knobs.by hand, it wasblame = (error @ W2.T) * (hidden > 0) optimizer.step()We turn each knob a little.by hand, it wasW1 += step * x.T @ blame / 20 30 passes × 75 bundles = 2,250 corrections of the 2,410 knobs
The training block: two loops, and five lines inside.
  • loss = loss_fn(model(x), y): model(x) makes the network answer, it’s our forward. loss_fn compares its answers with the right digits and boils them down to a single number, the error for that bundle. It’s the loss from step 4, the height of the hill. CrossEntropyLoss also applies softmax, which is why it was missing from the previous block.
  • loss.backward(): the error sharing from step 6. PyTorch goes back through the network from output to input and works out, for each knob, which way to turn it and by how much.
  • optimizer.step(): the correction. Each knob moves by lr times what backward just computed. lr, for learning rate, is our step, and SGD is the name libraries give to gradient descent.
  • optimizer.zero_grad(): PyTorch remembers the calculations from the previous bundle. This line clears them before moving on to the next.

Same question for the numbers in this block. Again, only one is dictated.

  • 1500: dictated, it’s the number of images we have for training.
  • 20: the bundle size, your choice. With small bundles the network corrects itself more often, but each correction is rougher. You’ll often see 16, 32 or 64.
  • 30: the number of passes, your choice. You watch the score on unseen images, and stop when it no longer climbs. In step 7 it was 85% after 5 passes, 89% after 20 and 90% after 30.
  • lr=0.3: the step size, your choice. It’s the ball from step 4: too small and it doesn’t reach the bottom, too large and it bounces.

These numbers you choose have a name, hyperparameters. Nobody calculates them: you start from a common value, run the training, look at the score, and adjust. Getting it wrong costs you one more training run, so a few seconds here. On a large model, the same trial and error is counted in hours of graphics card, which is why people start small.

I took a shortcut here: I compared settings on the 297 images, the very ones that give the final grade. If you keep picking the setting that suits them best, the grade ends up too flattering. Normally you cut the data in three: one part to learn from, one to choose the settings (the validation set), and a last one you look at only once, at the very end.

The last block grades the network on the 297 images it has never seen, as in step 7.

guesses = model(test_x).argmax(dim=1)   # for each image, the most likely digit
score = (guesses == test_y).float().mean().item()
print(round(100 * score), "% on unseen images")

On my machine it prints 90%, the same score as the hand-written code.

To run it on yours, you need Python, then three steps.

  1. Install both libraries with pip install torch numpy. PyTorch is big, so the download takes a few minutes.
  2. Download digits.csv and the complete script, and put them in the same folder.
  3. In that folder, run python network_pytorch.py.

The whole point of the library is backward(). You wrote the error sharing by hand, for a single hidden layer. PyTorch works it out on its own, for two layers or two hundred, and can run it on a graphics card.

Still 2,410 knobs, but you only write the decisions now. The library does the calculations.

So what about ChatGPT?

We look at what changes, and what doesn’t, when you go up to billions of knobs.

The model behind ChatGPT has billions of knobs instead of 2,410, and its neurons are wired according to a more elaborate plan, called the transformer. Its examples are texts, cut into pieces of words.

Its output, though, looks like that of our digit network (at least from what I’ve read: I’m a long way from understanding how it all works). We had ten output neurons, one per digit. It has something like a hundred thousand, one for each possible piece of a word, and softmax shares 100% of confidence between them. It picks the next piece, adds it to the text, and starts again.

The training loop is the one you wrote: the model predicts the next word, we compare with the real one, share out the error, and nudge every knob. What’s expensive is the repetition. There are billions of knobs to correct, over billions of examples, and that’s what the warehouses full of graphics cards are for.

3 knobs, then 17, then 2,410, then billions. Every time, the same loop tunes them.

Scroll back to the top of the page, and draw a digit in the black box. You now know what goes on behind it: 64 numbers go in, 2,410 knobs multiply and add them up, and ten confidences come out.

The best way to keep going is to change the code. Give the email network eight hidden neurons. Cut the digit network down to four, and see which digits it mixes up first. Then swap my data for yours: two columns of a spreadsheet and a third one to predict are enough to get started.

If you want to go further, here are four references.

What’s next

This post is the first of a series. I’m working on the others, and I’ll publish them if this one was useful to you. Here’s the plan.

  • Day 2. The model file. The 2,410 knobs vanish when you close the tab. How to save them to a file, load them back, and use them from another program.
  • Day 3. Checking a model’s quality. A score of 90% doesn’t tell you which answers are wrong. What to measure, and how to know whether a model is usable.
  • Day 4. PyTorch. This article’s network rewritten with the library, then trained on larger images, with a graphics card.
  • Day 5. Hugging Face. How to publish a model there, and how to pick up one that’s already trained and adapt it to your needs.
  • Day 6. Distillation. Training a small network to imitate a big one, to get a lighter model.
  • Day 7. From digits to text. What changes when the network has to predict words: cutting up the text, and the transformer architecture.

And well done. You wrote a neuron, trained it, connected several of them and taught them to read digits, with a single correction rule and a lot of for loops. A year and a half ago, I didn’t even know a developer could do that. You can, and you just did.

© Jean-François Lépine, 2010 - 2026 · RSS feed