Chapter 14 // Neural Networks

A Single Neuron.

What is the simplest part of a neural network, and what can it do on its own?

Reading time
14 min
Data

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 has a reputation for mystery. Its parts are not mysterious at all. The smallest part is one you have already met twice without the name.

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 does three things.

  1. It multiplies each input by its own .
  2. It adds the results together.
  3. It adds one more number, the bias.
output=w1x1+w2x2+⋯+wdxd+b\text{output} = w_1 x_1 + w_2 x_2 + \dots + w_d x_d + b

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.

ExampleOne neuron, three inputs

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.

5×4  +  2×7  +  0.5×60  +  10  =  20+14+30+10  =  745 \times 4 \;+\; 2 \times 7 \;+\; 0.5 \times 60 \;+\; 10 \;=\; 20 + 14 + 30 + 10 \;=\; 74
Figure

A neuron is a weighted sum

x₁× w₁x₂× w₂x₃× w₃add up+ boutput
InputValue× Weight= Adds
Hours studied45.020.0
Hours slept72.014.0
Last test score600.5030.0
Bias10.0
Sum of the three products
64.0
Plus the bias
10.0
Output of the neuron
74.0
5.0
2.0
0.50
10
The inputs are fixed. Each row shows what one input contributes once it is multiplied by its weight. Try it: set a weight to zero and watch that input stop mattering. Then make one negative, and see the bias shift everything without touching the inputs.

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, w⋅x+bw \cdot x + b. 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.

Figure

One neuron draws one straight line

5.5 h study, 7.9 h sleep, passed5.3 h study, 8.3 h sleep, passed6 h study, 7.2 h sleep, passed5.6 h study, 9.2 h sleep, passed5.9 h study, 8.2 h sleep, passed2.3 h study, 8.8 h sleep, passed7.2 h study, 4.2 h sleep, passed8.6 h study, 9.3 h sleep, passed5.1 h study, 4.8 h sleep, passed7.9 h study, 4.1 h sleep, passed6.2 h study, 6 h sleep, passed6.4 h study, 4 h sleep, passed4.8 h study, 8.8 h sleep, passed6.4 h study, 7.6 h sleep, passed3.8 h study, 8 h sleep, passed3.1 h study, 4 h sleep, failed1.9 h study, 3.6 h sleep, failed3.4 h study, 6.6 h sleep, failed3.2 h study, 8.9 h sleep, failed2.6 h study, 4.3 h sleep, failed2.9 h study, 5.3 h sleep, failed3.6 h study, 5 h sleep, failed2 h study, 3.6 h sleep, failed1.8 h study, 4.1 h sleep, failed1.8 h study, 5.8 h sleep, failed1.1 h study, 7.9 h sleep, failed4.2 h study, 3.9 h sleep, failed0.8 h study, 7.1 h sleep, failed4.3 h study, 4.6 h sleep, failed1.1 h study, 5 h sleep, failed4.9 h study, 5.3 h sleep, failed5.1 h study, 4.8 h sleep, failed1 h study, 5.7 h sleep, failed2.1 h study, 7.8 h sleep, failed1.7 h study, 7 h sleep, failed2.2 h study, 4.7 h sleep, failed1.5 h study, 4 h sleep, failed1.1 h study, 3.5 h sleep, failed3.4 h study, 5.9 h sleep, failed1.3 h study, 6.1 h sleep, failed
  • 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
1.0
1.0
-8.0
Each dot is a student. The shaded side is where the neuron's output is positive. Try it: adjust the weights and bias so that the shaded area covers the passes and not the fails. Then try to get all forty right.

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.

Checkpoint

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.

Figure

Three neurons, the same inputs

w on studyw on sleepw on scorebiasoutput
Neuron 1520.51074.0
Neuron 2160-2026.0
Neuron 3-201052.0
Inputs (one student)
[4, 7, 60]
Outputs (one per neuron)
[74.0, 26.0, 52.0]
Shapes
3 inputs → 3 outputs
4.0
7.0
60
Each row is one neuron with its own weights and bias. All three read the same three inputs. Try it: raise the hours slept and see which output reacts most. Then find inputs that make the third neuron's output negative.

When every neuron is connected to every input, as here, the layer is called a . It is the standard building block.

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 WW and their biases into a vector bb. Then the whole layer is one line:

outputs=Wx+b\text{outputs} = W x + b

Each row of WW takes a dot product with xx, 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 XX. Such a group is a .

What goes inShapeWhat comes outShape
One student, 3 features3One output per neuron3
A batch of 32 students32 × 3One row of outputs per student32 × 3
The same batch into a layer of 5 neurons32 × 332 × 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 showed, a gradient estimated from a batch is steadier than one from a single example.

Checkpoint

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.
You can now
  • 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.

Exerciseby hand

A neuron has weights [0.5, 2, −1][0.5,\ 2,\ -1] and a bias of 1. What does it output for the inputs [3, −1, 2][3,\ -1,\ 2]?

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:

0.5×3+2×(−1)+(−1)×2+1=1.5−2−2+1=−1.50.5 \times 3 + 2 \times (-1) + (-1) \times 2 + 1 = 1.5 - 2 - 2 + 1 = -1.5

Exerciseby hand

A layer of three neurons reads the inputs [1, 2][1,\ 2]. The neurons have weights [1, −1][1,\ -1], [0.5, 0.5][0.5,\ 0.5] and [−2, 1][-2,\ 1], 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:

  • 1×1+(−1)×2+0=−11 \times 1 + (-1) \times 2 + 0 = -1
  • 0.5×1+0.5×2+1=2.50.5 \times 1 + 0.5 \times 2 + 1 = 2.5
  • (−2)×1+1×2+3=3(-2) \times 1 + 1 \times 2 + 3 = 3

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.

Exercisethink

A neuron has weights [1, 1][1,\ 1] 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 x1+x2=3x_1 + x_2 = 3. 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.

Exercisein code

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.

Exercisewith the figure

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 dd inputs and mm neurons has d×md \times m weights and mm 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

Last updated Spotted a mistake? Suggest an editWhat changed

In this chapter
  1. Top of the chapter
  2. 14.1Borrowed from biology, loosely
  3. 14.2One neuron: a weighted sum
  4. 14.3What one neuron can decide
  5. 14.4Many neurons, one layer
  6. 14.5Many examples at once
  7. 14.6In code
  8. Exercises
Search

    The Book of Machine Learning
    Search
    Reading settings
    Text size
    Colours

    Saved in this browser only.

    Keyboard shortcuts
    /
    Search the book
    ← →
    Previous and next chapter
    g
    Glossary
    c
    Table of contents
    e
    Jump to the exercises
    t
    Reading settings
    ?
    Show this list
    Esc
    Close a window or pop-in