How Do Neural Networks Work, and How Do They Learn?
A straight-line rule can never learn that too much sleep hurts an exam score. A few neurons with a simple bend can. This post builds a tiny neural network by hand, shows how it is wired and what people decide versus what training finds, then works out where a gradient comes from and how backpropagation finds one for every weight.
This is the third post in a five-part series on machine learning from zero. The previous post showed how training finds a model's numbers. You don't have to read it first. The next section sums up the facts from the earlier posts that this one needs.
What you need from the earlier posts
- A model is a rule with blanks. Training fills in the blanks from examples with known answers. Prediction uses the filled-in rule on new inputs.
- Weights, bias, parameters. A weight is a learned number multiplied with an input. It shows how much that input matters. A bias is a learned number added on its own. It is the starting value. Together, they are the model's parameters.
- Loss. One number that says how wrong the model is. For number predictions, the loss for one example is the error squared, where error = prediction − real answer.
- Gradient. For each parameter, a number whose sign says which way to move it, and whose size says how strongly. A negative gradient means "go up".
- Learning rate and the update. The learning rate is a small number, such as 0.01, that keeps each step small. Each training step updates every parameter with
new value = old value − learning rate × gradient.
Why do we need neural networks?
The models so far all multiply and add. That turns out to be a hard limit. Some patterns can't be learned that way, however long you train.
This post shows the limit, then the fix. We'll take it in four steps:
- Why one rule isn't enough. The pattern a multiply-and-add rule can never learn.
- Neurons and the bend. A tiny network, built by hand, that learns it.
- Wiring, and who decides what. How the parts connect, and which parts people choose.
- How a network learns. Where a gradient comes from, and how one is found for every weight.
Why one simple rule is not enough
Here is the exam-score rule from the first post. Training found 8 for study, 3 for sleep and 10 for the bias:
score = 8 × study + 3 × sleep + 10
By this rule, more sleep always means a higher score. If a student slept 20 hours, the rule would add 3 × 20 = 60 points. That makes no sense.
In reality, sleep helps up to a point, say about 8 hours. After that, extra sleep doesn't help. It might even hurt, because that time could have gone to study.
The problem is the shape of the rule. A rule that only multiplies and adds can only describe straight-line relationships. As an input goes up, the output goes up (or down) at a constant rate, forever. Such a rule can never say "this helps up to a point, and then it starts to hurt."
Many real-world patterns are not straight lines. To learn them, we need a more flexible kind of model. That is a neural network.
Neurons and the bend
The idea: many small rules instead of one
A neural network doesn't use one big rule. It uses many small rules. Each small rule is called a neuron. The outputs of the neurons are then fed into a final rule, which makes the prediction.
Each neuron does three things:
- It multiplies each input by its own weight.
- It adds the results together, plus its own bias.
- It applies a bend. If the result is negative, it becomes 0. If the result is positive, it stays the same.
The bend is the key ingredient. Its proper name is an activation function. This particular one is called ReLU, short for "Rectified Linear Unit".
Why the bend is needed
Without the bend, stacking many multiply-and-add rules would still only give a straight line. Here is a quick example:
- Rule 1 doubles the input and adds 1.
- Rule 2 takes that result, triples it, and adds 4.
Let's feed in a few inputs:
| Input | After Rule 1 (× 2, + 1) | After Rule 2 (× 3, + 4) |
|---|---|---|
| 1 | 3 | 13 |
| 2 | 5 | 19 |
| 3 | 7 | 25 |
| 4 | 9 | 31 |
Every time the input goes up by 1, the final output goes up by exactly 6. A steady rate like that is what a straight line means. So the two rules together act just like one simple rule: multiply by 6, then add 7. However many rules you stack, the same thing happens.
The bend breaks this, because it treats negative and positive values differently. That is what lets a network learn curves, and "only after this point" behaviour.
Worked example: learning about too much sleep
Let's build a tiny neural network by hand to see this work. In real life, training finds all of these numbers. Here, we choose them ourselves, just to show what a network can do.
Neuron 1: 1 × sleep − 8, then the bend.
| Sleep | 1 × sleep − 8 | After the bend |
|---|---|---|
| 6 hours | −2 | 0 |
| 8 hours | 0 | 0 |
| 12 hours | 4 | 4 |
Look at what this neuron does. It stays at 0 until sleep goes above 8 hours. After that, it counts the extra hours. It works like an oversleeping detector. Its bias, −8, is what sets the threshold at 8 hours.
Neuron 2: 1 × study + 0, then the bend. Study hours are never negative, so this neuron simply passes the study hours through.
Neuron 3: 1 × sleep + 0, then the bend. This neuron simply passes the sleep hours through.
Final rule: it combines the outputs of the three neurons.
score = 8 × (Neuron 2) + 3 × (Neuron 3) − 5 × (Neuron 1) + 10
The −5 means: for every hour of oversleeping, take away 5 points.
Testing the network
Take a student who studied 5 hours, and try different amounts of sleep. Neuron 2 always gives 5:
| Sleep | Neuron 1 | Neuron 3 | Calculation | Score |
|---|---|---|---|---|
| 6 h | 0 | 6 | 8×5 + 3×6 − 5×0 + 10 | 68 |
| 8 h | 0 | 8 | 8×5 + 3×8 − 5×0 + 10 | 74 |
| 12 h | 4 | 12 | 8×5 + 3×12 − 5×4 + 10 | 66 |
The score rises as sleep goes up to 8 hours. Then it falls. For comparison, the straight-line rule gives 86 for 12 hours of sleep.
A single straight-line rule could never do this. A few neurons with a bend can.
The structure
Every input goes to every neuron. Every neuron's output goes to the final rule:
Notice the faint line from study into Neuron 1. Its weight is 0. The next section explains why it is there at all.
Counting the parameters
- Each of the three neurons has 2 weights (one per input) and 1 bias. That's 3 parameters each, so 9 for the three.
- The final rule has 3 weights (one per neuron) and 1 bias. That's 4 parameters.
- Total: 13 parameters.
Neural network words
- Neuron: a small rule that multiplies, adds and bends.
- Layer: a group of neurons that sit side by side and receive the same inputs. The three neurons above form one layer.
- Neural network: layers connected one after another. The outputs of one layer become the inputs of the next.
- Deep neural network, or deep learning: a neural network with many layers.
Large AI models are built from this same idea. They just have thousands of neurons in each layer, and dozens of layers stacked together.
How a neural network is wired
The example raises some natural questions. This section answers them.
Every neuron sees every input
It looked as if Neuron 1 only used sleep, and Neuron 2 only used study. In fact, every neuron receives all the inputs. Neuron 1 really looks like this:
Neuron 1 = 0 × study + 1 × sleep − 8
Its weight for study is 0. Anything multiplied by 0 is 0, so study has no effect on this neuron. The neuron ignores study, but the weight for study still exists. It just happens to be 0.
That's also why each neuron has 3 parameters. One weight for study (even if it's 0), one weight for sleep, and one bias. A weight of 0 still counts as a parameter, because training could have picked any other value for it.
How many weights are there?
- For one neuron: one weight per input. With 5 inputs, each neuron has 5 weights, plus 1 bias.
- For a whole layer: multiply the number of inputs by the number of neurons. With 5 inputs and 3 neurons, the layer has 5 × 3 = 15 weights, plus 3 biases (one per neuron).
The inputs are fixed
The number of inputs, and their order, is decided when the model is designed. After that, every training example and every prediction must give exactly the same inputs, in the same order. A model built for 5 inputs always expects 5 inputs.
Say some information is missing. For example, an applicant didn't give their age. Then the gap must be filled in before the data reaches the model. Common choices are the average value from the dataset, or 0. A neural network can't handle an empty value, and neither can many other models. Post 4 covers some models that can.
Doesn't the bend throw away information?
The bend turns every negative number into 0. For that one neuron, the negative information is indeed lost. But this is on purpose. It's exactly what lets a neuron stay silent until a threshold, like the oversleeping detector.
Nothing important is lost for the network as a whole, for two reasons:
- Other neurons see the same inputs, with different weights. A neuron like
−1 × sleep + 8gives a positive output when sleep is low. That neuron would be an "undersleeping detector". With many neurons, both sides of a pattern get covered. - The final output has no bend. So the network can still predict negative numbers when it needs to, such as a temperature below zero. For yes/no questions, the final output gets a different step instead. Post 4 covers it.
Who decides what: people vs. training
When you build a model, some things are decided by people, and some are learned by training.
| Decided by people (before training) | Learned by training (the numbers) |
|---|---|
| Which inputs to use | Every weight |
| How many layers there are | Every bias |
| How many neurons are in each layer | |
| How the layers connect | |
| The learning rate | |
| The batch size | |
| The number of epochs |
The last three are settings of the training process. The learning rate scales each step. The batch size is how many examples go into one update. The number of epochs is how many times training passes over all the training data.
Some of these choices have a name: hyperparameters. They are the settings people pick before training starts: the number of layers, the number of neurons in each layer, the learning rate, the batch size and the number of epochs. They stay fixed while training runs. The parameters in the right column change on every step.
Think of a sound mixing board with many knobs:
- Hyperparameters are decisions about the board and the process: how many knobs it has, and how quickly the sound engineer turns them.
- Parameters are the positions of the knobs, which the engineer keeps adjusting.
Good hyperparameters are usually found by experiment. You try a few settings, compare the results, and keep the best. Post 4 shows how to compare them fairly.
Nobody tells a neuron what to do
We designed the example network by hand, including the −5 penalty for oversleeping. That was only to show what a network can do. Real training does not work this way. Nobody tells a neuron "you are the oversleeping detector."
Instead, you give the model thousands of real examples. Training keeps adjusting all the weights and biases until the predictions match the real answers as closely as it can. If the data shows that oversleeping lowers scores, training will push some numbers that way. Some neurons may end up acting like an oversleeping penalty. The data shapes the numbers. People don't set them.
Do we know what each neuron does?
Usually, not exactly. Here is what people do control:
- The structure, because they designed it.
- The training process, because they run it.
- Whether the whole model works, because they test it. Post 4 shows how.
What people don't control is the job each neuron ends up doing. After training, you can feed in different inputs and watch which neurons become active. Sometimes a neuron has a clear meaning. Often, it responds to a messy mix of patterns that is hard to describe. The research field that studies what happens inside models is called interpretability.
In practice, people trust a model by testing its outputs carefully, not by understanding every neuron.
Where a gradient comes from
The previous post used gradients without showing where they come from. Here's how, on a rule simple enough to check by hand. It turns out a gradient isn't magic. It only needs multiplication.
You don't need this section to use machine learning. Libraries do it for you. But it is what makes training make sense.
The one question a gradient answers
For each parameter, the gradient answers one question:
"If I raise this parameter by a small amount, how much does the loss change?"
The answer is one number per parameter. That number is its gradient.
The setup
We'll use a model with two inputs and no bias:
prediction = w1 × study + w2 × sleep
One example: study = 2, sleep = 3, real score = 20
Current values: w1 = 2, w2 = 1
prediction = 2 × 2 + 1 × 3 = 7
error = 7 − 20 = −13 (too low by 13)
loss = error² = 169
The slow way: try it and see
The obvious way to answer the question is to nudge each weight slightly, and see what happens to the loss:
| Nudge | New prediction | New loss | Change in loss |
|---|---|---|---|
| w1: 2 → 2.01 | 7.02 | 168.48 | down by 0.52 |
| w2: 1 → 1.01 | 7.03 | 168.22 | down by 0.78 |
Both nudges lower the loss, so both weights should go up. And w2 has the stronger effect.
This works, but it is far too slow for real models. With a million weights, you'd need a million extra predictions just to take one training step.
The fast way: follow the chain of effects
A weight doesn't change the loss directly. There's a chain of effects in between:
w1 → prediction → loss
So we can split the big question into two small ones, one for each arrow.
Question A: if w1 goes up by 1, how much does the prediction change?
w1 = 2: 2 × 2 = 4 → prediction = 7
w1 = 3: 3 × 2 = 6 → prediction = 9
The prediction goes up by 2. That's because w1 is multiplied by the study input, which is 2. So the answer to question A is simply the input value. For w2, it would be the sleep input, which is 3.
Question B: if the prediction goes up by 1, how much does the loss change?
prediction = 7 → error = −13 → loss = 169.00
prediction = 7.01 → error = −12.99 → loss = 168.74
Raising the prediction by 0.01 lowered the loss by 0.26. That's a rate of −26 for each full unit. And −26 is exactly 2 × error = 2 × (−13).
Where does the 2 come from? Picture a square with sides 13 long. Its area is 13 × 13 = 169. Now make each side a tiny bit longer. The area grows by a thin strip along two of its sides, and each strip is 13 long. So the area grows by about 2 × 13 × (the tiny amount). Squaring the error is what creates the "2 × error".
The minus sign appears because the prediction is too low. Raising it makes the error smaller, so the loss goes down.
Connecting the two answers: multiply
Think of gears. Say turning gear A once turns gear B twice. And turning gear B once turns gear C three times. Then turning gear A once turns gear C 2 × 3 = 6 times. Effects along a chain multiply.
The same is true here:
w1 ──(rate: 2)──▶ prediction ──(rate: −26)──▶ loss
gradient for w1 = 2 × (−26) = −52
Compare this with the slow way. A nudge of 0.01 lowered the loss by 0.52, which is 52 per unit. It's the same answer. This time it took two multiplications instead of an experiment.
The formula
Putting the pieces together:
gradient = (2 × error) × (input)
(2 × error)is how the loss reacts to the prediction.(input)is how the prediction reacts to the weight.
For our example:
- w1: 2 × (−13) × 2 = −52
- w2: 2 × (−13) × 3 = −78
What about a bias? This model has none, but most models do. A bias is added on its own, with no input to multiply. Raising the bias by 1 raises the prediction by exactly 1. So its gradient is simply (2 × error) × 1. Here, that would be −26.
This is where the previous post's numbers came from. There, the model was score = w × hours, with one example: 2 hours, real score 20. It started at w = 3, so the prediction was 6 and the error was −14. The formula gives 2 × (−14) × 2 = −56. That was the first gradient in its table.
How to read a gradient
| Gradient | What it means | What to do |
|---|---|---|
| Negative | Raising the weight lowers the loss | Raise the weight |
| Positive | Raising the weight raises the loss | Lower the weight |
| Large (far from 0) | The weight has a strong effect right now | Take a bigger step |
| Near 0 | The weight barely matters right now | Barely change it |
The update
With a learning rate of 0.01:
w1 = 2 − 0.01 × (−52) = 2.52
w2 = 1 − 0.01 × (−78) = 1.78
New prediction: 2.52 × 2 + 1.78 × 3 = 10.38. Before the update, the prediction was 7. After one step, it is much closer to the real answer of 20.
Why the steps must be small
The rates we worked out are only accurate for small changes. As a weight moves, the error changes, so the rates change too. That's why training takes a small step, works everything out again, and then takes another small step. It doesn't jump straight to an answer.
Backpropagation: the same idea through many layers
In a deep neural network, the chain from a weight to the loss is much longer. The signal passes through many neurons and layers:
weight → neuron → bend → next neuron → bend → ... → prediction → loss
But each link in the chain is one of just a few simple types, and each type has a simple rate:
| Type of link | Its rate |
|---|---|
| Multiplying (a weight times an input) | The other number in the multiplication |
| Adding (adding a bias, or adding values together) | 1 |
| The bend (ReLU) | 1 if the value was positive; 0 if it was turned into 0 |
Just like with the gears, you multiply the rates along the chain to get the gradient for any parameter.
Backpropagation, short for "backward propagation of errors", is the efficient way to do this for millions of parameters:
- Start at the loss, at the very end of the network.
- Walk backward through the network, one layer at a time.
- At each step, work out how much each parameter added to the error. Think of it as passing the "blame" for the mistake backward through the network.
- Reuse the parts of the chain that many parameters share, so nothing is worked out twice.
One backward sweep produces the gradient for every parameter in the network. Modern libraries do this for you. In PyTorch, a popular library for neural networks, it is a single line of code: loss.backward(). Post 5 runs it.
New words in this post
| Word | Meaning |
|---|---|
| Neuron | A small rule that multiplies its inputs by weights, adds a bias, and applies a bend |
| Activation function | The fixed shape applied to a neuron's result; here, the bend |
| ReLU | The most common activation function: negatives become 0, positives stay the same |
| Layer | A group of neurons that sit side by side and receive the same inputs |
| Neural network | Layers of neurons connected one after another |
| Deep learning | Machine learning with neural networks that have many layers |
| Hyperparameter | A setting people choose before training, such as the learning rate or the number of layers |
| Interpretability | The study of what is happening inside a trained model |
| Backpropagation | Working out every parameter's gradient by walking backward from the loss and multiplying rates |
Recap
- A multiply-and-add rule can only learn straight-line patterns. Stacking more of them still gives a straight line.
- A neuron multiplies, adds a bias, and applies a bend (ReLU). The bend is what lets a network learn curves, like "sleep helps up to 8 hours, then hurts".
- In a standard layer, every neuron receives every input. A weight of 0 means "ignore this input", but it still counts as a parameter.
- People choose the structure and the hyperparameters. Training finds the weights and biases. What each neuron ends up doing is often hard to interpret.
- A gradient is found by multiplying simple rates along the chain from a parameter to the loss. For one weight and squared error, it is
(2 × error) × (input). - Backpropagation does this for every parameter in one backward sweep, starting from the loss.
Next up: we can now build models and train them. But which kind of model should you use? And how do you know it's any good? How Do You Choose a Model and Know It's Good? answers both.