This part of the book builds a neural network from nothing. Each chapter adds one piece, and by the end you will have a complete network that learns to recognise images, with no step taken on trust.
A
Borrowed from biology, loosely
The name comes from the brain. A biological neuron receives signals from many others, and if the combined signal is strong enough it sends a signal of its own onward.
The artificial version keeps that outline and nothing else. It takes several numbers in, combines them, and puts one number out. It is a small piece of arithmetic. The comparison with the brain is a useful picture for remembering the shape, and it should not be pushed further than that.
What makes networks powerful is not any single neuron. It is what happens when thousands of them are connected, which the next chapters build up to. First, one neuron on its own.
One neuron: a weighted sum
A
- It multiplies each input by its own
. - It adds the results together.
- It adds one more number, the bias.
output = (each input × its weight, added up) + bias
A weight says how much the neuron cares about an input and in which direction. A large positive weight means “more of this pushes my output up”. A negative weight means the opposite. A weight near zero means the input is ignored. The bias shifts the output up or down whatever the inputs are.
A student studied 4 hours, slept 7, and scored 60 on the last test. The neuron has weights 5, 2 and 0.5, and a bias of 10.
A neuron is a weighted sum
| Input | Value | × Weight | = Adds |
|---|---|---|---|
| Hours studied | 4 | 5.0 | 20.0 |
| Hours slept | 7 | 2.0 | 14.0 |
| Last test score | 60 | 0.50 | 30.0 |
| Bias | 10.0 |
- Sum of the three products
- 64.0
- Plus the bias
- 10.0
- Output of the neuron
- 74.0
If this looks familiar, it should. It is the prediction of linear regression, and the score inside logistic regression. Written with vectors it is a dot product plus a bias, . A neuron is the same calculation, given a new name because of what we are about to do with it.
What one neuron can decide
The output of a neuron is just a number. To see what that number can express, give the neuron two inputs and colour the plane by whether its output is above or below zero.
One neuron draws one straight line
- Shaded: output above zero
- Line: output exactly zero
- Passed (filled) / failed (hollow)
- Output for 4 h study, 7 h sleep
- 3.0
- Students with positive output
- 27 of 40
- Matches pass / fail for
- 28 of 40
However you set the three numbers, the boundary is a straight line. The two weights set its direction, and the bias slides it back and forth. You can get most of the forty students on the correct side, and about 37 is the best possible, but never all of them, because the passes and fails overlap.
This is the limit of a single neuron. It can make any decision that a straight cut can make, and no other kind. Data shaped like a ring or a spiral is beyond it.
A neuron has weights [2, −1] and bias 3. What is its output for the input [4, 5]?
Many neurons, one layer
One neuron gives one number. Put several neurons side by side, show them all the same inputs, and you get several numbers. That group is a
Each neuron in the layer has its own weights and its own bias, so each one responds to something different. In the figure, the first neuron cares mostly about study, the second mostly about sleep, and the third about the last test score.
Three neurons, the same inputs
| w on study | w on sleep | w on score | bias | output | |
|---|---|---|---|---|---|
| Neuron 1 | 5 | 2 | 0.5 | 10 | 74.0 |
| Neuron 2 | 1 | 6 | 0 | -20 | 26.0 |
| Neuron 3 | -2 | 0 | 1 | 0 | 52.0 |
- Inputs (one student)
- [4, 7, 60]
- Outputs (one per neuron)
- [74.0, 26.0, 52.0]
- Shapes
- 3 inputs → 3 outputs
When every neuron is connected to every input, as here, the layer is called a
Writing out each neuron separately gets tedious, and there is a compact way to say the same thing. Stack the neurons’ weights as the rows of a matrix and their biases into a vector . Then the whole layer is one line:
Each row of takes a dot product with , exactly as in the toolkit chapter on vectors and matrices. A layer of a thousand neurons is still that one line.
Many examples at once
So far the layer has processed one student. In practice we push many examples through together, as the rows of a matrix . Such a group is a
| What goes in | Shape | What comes out | Shape |
|---|---|---|---|
| One student, 3 features | 3 | One output per neuron | 3 |
| A batch of 32 students | 32 × 3 | One row of outputs per student | 32 × 3 |
| The same batch into a layer of 5 neurons | 32 × 3 | 32 × 5 |
The rule is easy to remember. The number of rows stays the same: one row in, one row out, per example. The number of columns changes from the number of inputs to the number of neurons.
Batches matter for two reasons. Computers multiply whole matrices far faster than they loop over rows. And, as
A batch of 64 images, each flattened to 784 numbers, goes into a dense layer of 128 neurons. What is the shape of the output?
In code
Here is the chapter in NumPy: a neuron longhand, then as a dot product, then a whole layer on a whole batch. The full file is code/ch14_neuron.py (run it in Colab) in the book’s repository.
import numpy as np
inputs = [4, 7, 60] # hours studied, hours slept, last test score
weights = [5, 2, 0.5]
bias = 10
print(np.dot(inputs, weights) + bias) # 74.0 one neuron
layer_weights = np.array([[5, 2, 0.5], # one row of weights per neuron
[1, 6, 0.0],
[-2, 0, 1.0]])
layer_biases = np.array([10, -20, 0])
print(layer_weights @ inputs + layer_biases) # [74. 26. 52.] a layer
batch = np.array([[4, 7, 60], # one row per student
[1, 5, 40],
[8, 8, 75]])
print(batch @ layer_weights.T + layer_biases) # a layer on a batch: shape (3, 3)
class Layer_Dense:
def __init__(self, n_inputs, n_neurons, rng):
self.weights = 0.01 * rng.standard_normal((n_inputs, n_neurons))
self.biases = np.zeros((1, n_neurons))
def forward(self, inputs):
self.output = inputs @ self.weights + self.biases
The class at the end is the first piece of the network we will keep building. It starts with small random weights, because a layer whose neurons all began identical would stay identical for ever. The next chapters add to it one method at a time.
Key Takeaways
- A neuron multiplies each input by a weight, adds them up, and adds a bias. It is a dot product plus a number.
- On its own a neuron can only make a straight-line decision, the same as logistic regression.
- A layer is several neurons reading the same inputs, each with its own weights.
- A whole layer is one matrix calculation: outputs = W x + b.
- A batch passes many examples through at once: rows stay, columns become the number of neurons.
- Work out the output of a neuron by hand.
- Say what a single neuron can decide, and give an example of something it cannot.
- Compute the outputs of a whole layer as one matrix calculation.
- Predict the shape of the output when a batch goes through a layer.
Exercises
Try each one before opening its solution. Getting stuck for a few minutes is where most of the learning happens.
A neuron has weights and a bias of 1. What does it output for the inputs ?
Hint
Multiply each input by its weight, add the three products, then add the bias.
Solution
Multiply each input by its weight, add them up, and add the bias:
A layer of three neurons reads the inputs . The neurons have weights , and , and biases 0, 1 and 3. What are the three outputs?
Hint
Do the previous exercise three times, once for each neuron.
Solution
One dot product per neuron, plus that neuron’s bias:
The layer turns two numbers into three. As a matrix calculation, a (3 × 2) table of weights times a vector of 2 inputs gives 3 outputs.
A neuron has weights and a bias of −3, and answers “yes” when its output is above zero. Describe its decision boundary. Then explain why no single neuron can answer “yes” for the inputs (0, 1) and (1, 0) but “no” for (0, 0) and (1, 1).
Hint
The boundary is where the output is exactly zero. For the second part, draw the four points.
Solution
The output is zero where . That is a straight line through (3, 0) and (0, 3). Points above and to the right of it get “yes”.
For the second part, plot the four points. The two “yes” points sit on one diagonal of a square and the two “no” points on the other. Any straight line that puts (0, 1) and (1, 0) on the same side must also put at least one of the other two corners there. A single neuron draws one straight line, so it cannot do it. This is the famous XOR problem. A network with a hidden layer, built in the next chapter, can solve it.
Make a batch of 4 examples with 3 features each, and pass it through a layer of 5 neurons using NumPy. What shapes do the weights, the biases and the output have?
Hint
The weights need one row per input and one column per neuron.
Solution
import numpy as np
rng = np.random.default_rng(0)
X = rng.standard_normal((4, 3)) # 4 examples, 3 features
weights = 0.01 * rng.standard_normal((3, 5)) # 3 inputs, 5 neurons
biases = np.zeros(5)
outputs = X @ weights + biases
print(outputs.shape) # (4, 5)The weights are (3 × 5), the biases are (5) and the output is (4 × 5): one row per example, one column per neuron. NumPy adds the five biases to every row.
In the figure “One neuron draws one straight line”, get as many of the forty students on the correct side as you can. Then try to beat 37. What stops you?
Hint
Look for a pass sitting among the fails, or a fail among the passes.
Solution
About 37 out of 40 is the best possible. The remaining students are on the wrong side of any straight line that gets the others right: a few who passed sit among those who failed, and the reverse.
No setting of two weights and a bias changes the shape of the boundary. The weights turn it and the bias slides it, and it stays a straight line. To do better the model itself has to change, which is the subject of the next chapter.
Going further
Why random starting weights
If every neuron in a layer started with the same weights, each would compute the same output, receive the same correction during training, and remain a copy of the others for ever. Starting from small random values breaks the tie, so the neurons can grow to respond to different things.
How many weights is that?
A dense layer with inputs and neurons has weights and biases. A layer from 784 inputs to 128 neurons already has 100,480 numbers to learn. The size of modern networks comes from stacking many such layers, not from any one of them being complicated.
References and further reading
- H. Kinsley and D. Kukieła, Neural Networks from Scratch in Python, chapters 1 and 2, nnfs.io. This part of the book follows their order of construction.
- M. Nielsen, Neural Networks and Deep Learning, chapter 1, neuralnetworksanddeeplearning.com.
- G. Sanderson, But what is a neural network?, 3Blue1Brown.