# Chapter 14: A Single Neuron

> Inputs, weights, and a bias: the smallest piece of a network. Opening question: What is the simplest part of a neural network, and what can it do on its own?

From *The Book of Machine Learning*, a free interactive machine learning textbook. Interactive version, with figures to use: https://thebookofml.com/a-single-neuron/

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

1. It multiplies each input by its own weight.
2. It adds the results together.
3. It adds one more number, the bias.

$$
\text{output} = w_1 x_1 + w_2 x_2 + \dots + w_d x_d + b
$$

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.

**Example: One 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 \times 4 \;+\; 2 \times 7 \;+\; 0.5 \times 60 \;+\; 10 \;=\; 20 + 14 + 30 + 10 \;=\; 74
$$

> **Interactive figure: A neuron is a weighted sum.** 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.
> (Use it at https://thebookofml.com/a-single-neuron/)

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 \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.

> **Interactive figure: One neuron draws one straight line.** 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.
> (Use it at https://thebookofml.com/a-single-neuron/)

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.

**Check your understanding:** A neuron has weights [2, −1] and bias 3. What is its output for the input [4, 5]?

- 6 **(correct)** — 2×4 + (−1)×5 + 3 = 8 − 5 + 3 = 6.
- 3 — That leaves out the bias. The weighted sum is 8 − 5 = 3, and the bias adds 3 more.
- 16 — The second weight is negative, so its term is subtracted: 8 − 5, not 8 + 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 layer.

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.

> **Interactive figure: Three neurons, the same inputs.** 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.
> (Use it at https://thebookofml.com/a-single-neuron/)

When every neuron is connected to every input, as here, the layer is called a dense layer. 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 $W$ and their biases into a vector $b$. Then the whole layer is one line:

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

Each row of $W$ takes a dot product with $x$, exactly as in the toolkit chapter on [vectors and matrices](/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 $X$. Such a group is a batch.

| 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 [the gradient descent chapter](https://thebookofml.com/gradient-descent/) showed, a gradient estimated from a batch is steadier than one from a single example.

**Check your understanding:** 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?

- 64 × 128 **(correct)** — One row per image, one column per neuron. The 784 inputs are used up inside each neuron's weighted sum.
- 784 × 128 — That is the shape of the weights: one weight for every input of every neuron. The output has one row per example.
- 64 × 784 — That is the shape of the input batch. The layer turns each row of 784 numbers into 128.

**Common mistake: A weight matrix the wrong way round**

A layer with 3 inputs and 5 neurons has 15 weights, and they can be stored as a (3 × 5) table or a (5 × 3) one. Both are in use: the formula $Wx + b$ puts one neuron in each row, while the code in this book puts one neuron in each column so that a whole batch can be multiplied in one go. Mixing the two gives either a shape error or, worse, a silent mistake when the layer happens to be square. Write the shapes down. A batch of (n × 3) inputs times a (3 × 5) weight table gives (n × 5) outputs.

## 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 [ch14_neuron.py](https://github.com/kamileren/quickproject/blob/master/code/ch14_neuron.py) in the book's repository.

```python
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.

## What you should now be able to do

- 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

### Exercise (by hand)

A neuron has weights $[0.5,\ 2,\ -1]$ and a bias of 1. What does it output for the inputs $[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 \times 3 + 2 \times (-1) + (-1) \times 2 + 1 = 1.5 - 2 - 2 + 1 = -1.5$

### Exercise (by hand)

A layer of three neurons reads the inputs $[1,\ 2]$. The neurons have weights $[1,\ -1]$, $[0.5,\ 0.5]$ and $[-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 \times 1 + (-1) \times 2 + 0 = -1$
- $0.5 \times 1 + 0.5 \times 2 + 1 = 2.5$
- $(-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.

### Exercise (think)

A neuron has weights $[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 $x_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.

### Exercise (in 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:**

```python
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.

### Exercise (with 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 $d$ inputs and $m$ neurons has $d \times m$ weights and $m$ 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

- H. Kinsley and D. Kukieła, *Neural Networks from Scratch in Python*, chapters 1 and 2, [nnfs.io](https://nnfs.io). This part of the book follows their order of construction.
- M. Nielsen, *Neural Networks and Deep Learning*, chapter 1, [neuralnetworksanddeeplearning.com](http://neuralnetworksanddeeplearning.com/chap1.html).
- G. Sanderson, [But what is a neural network?](https://www.3blue1brown.com/lessons/neural-networks), 3Blue1Brown.

## Next

A layer draws several straight lines at once, and each of them is still straight. The obvious way to get something richer is to feed one layer into another. The next chapter shows why that alone achieves nothing, and the one small addition that changes everything.
