Neural Networks

How a neural network is built from layers of weighted sums with activation functions, how a forward pass works, and how backpropagation trains it.

14 minLesson 6 of 7
On this page
  1. Why one weighted sum is not enough
  2. How a neuron and a layer work
  3. Tracing a small network by hand
  4. Why the activation function matters
  5. Activation functions, size and architectures
  6. How a network is trained
  7. Pitfalls
  8. What this changes in practice
  9. Try it yourself
  10. Check yourself
  11. What to practise next

A neural network is a function made of layers of simple units. Each unit takes a weighted sum of its inputs and passes it through a nonlinear activation function, and the weights are learned from examples. Networks are used when the relationship between inputs and outputs is too complicated to write by hand, as in images, speech and language, and they are the basis of modern language models.

A single weighted sum, as used in Regression and Classification, can only separate the data with one straight line. Stacking units in layers with a nonlinearity between them removes that limit, because later layers can combine features that earlier layers computed.

Why one weighted sum is not enough

Take a hallway with a light switch at each end, where flipping either switch toggles the light. The light is off when both switches are down, on when exactly one is up, and off again when both are up. A weighted-sum classifier compares a weighted sum of the inputs with a threshold, which geometrically means drawing one straight line through the input space, with "yes" on one side and "no" on the other. No such line can separate the hallway cases.

switch 1 switch 2 0 1 0 1 light on light off Every straight line leaves at least one point on the wrong side.
The four switch positions, where the light is on for one diagonal and off for the other, so no straight line separates the on points from the off points.

The way out is to compute intermediate features first. If the model knows how many switches are up and whether both are up, the answer is the count minus twice the "both" signal, which gives 1 for one switch and 2 − 2 = 0 for two. A network learns intermediate features like these by itself instead of having someone design them.

How a neuron and a layer work

A neuron performs three steps. It multiplies each input by its weight and adds the results, it adds a bias, and it passes the total through an activation function. The first two steps are the weighted sum you already know, and the third adds the nonlinearity.

Neurons are arranged in layers. The inputs feed a hidden layer, whose outputs feed the next layer, and the last layer produces the answer. Every neuron in a layer reads all the outputs of the previous layer, each with its own weight. A network with many hidden layers is called a deep network, which is where the term deep learning comes from.

Tracing a small network by hand

This network has two hidden neurons and solves the hallway problem. The weights are set by hand so that every number can be followed; training could find different weights that also work. The activation is ReLU, which keeps a positive number and replaces a negative one with 0, written max(0, z).

  • h1 = ReLU(s1 + s2) counts how many switches are up.
  • h2 = ReLU(s1 + s2 − 1) is 1 only when both switches are up, because the bias of −1 cancels a single switch.
  • light = h1 − 2 × h2 combines the two features into the answer.
Forward pass through the hallway networkUse the arrows or ← → keys
h1 = relu(1*s1 + 1*s2 + 0)h2 = relu(1*s1 + 1*s2 - 1)light = 1*h1 - 2*h2
  1. 11111-2s11s21h1h2bias −1light
    s1
    1
    s2
    1

    1Both switches are up, and the arrows show the weights.

  2. 11111-2s11s21h12h2bias −1light
    s1
    1
    s2
    1
    h1
    2

    2h1: 1 × 1 + 1 × 1 = 2. The sum is positive, so ReLU keeps it, and h1 counts two switches up.

  3. 11111-2s11s21h12h21light
    s1
    1
    s2
    1
    h1
    2
    h2
    1

    3h2 is 1 + 1 − 1 = 1, which signals that both switches are up.

  4. 11111-2s11s21h12h21light0 (off)
    s1
    1
    s2
    1
    h1
    2
    h2
    1
    light
    0

    4The output is 1 × 2 + (−2) × 1 = 0, so the light is off, which is correct.

  5. 11111-2s11s20h11h2bias −1light
    s1
    1
    s2
    0
    h1
    1

    5Now only switch 1 is up, so h1 = 1 + 0 = 1.

  6. 11111-2s11s20h11h20light
    s1
    1
    s2
    0
    h1
    1
    h2
    0

    6h2 is 1 + 0 − 1 = 0, because the bias of −1 means a single switch is not enough to activate it.

  7. 11111-2s11s20h11h20light1 (on)
    s1
    1
    s2
    0
    h1
    1
    h2
    0
    light
    1

    7The output is 1 × 1 + (−2) × 0 = 1, so the light is on.

  8. 11111-2s10s20h10h20light0 (off)
    s1
    0
    s2
    0
    h1
    0
    h2
    0
    light
    0

    8With both switches down, h1 is 0 and h2 is ReLU(−1) = 0, so the light is off. Without ReLU, h2 would be −1 and the output would be 2.

1 / 8

Switch 2 alone also gives 1, so all four positions are correct. Running the inputs through the layers to get an output is called the forward pass. The same computation in code looks like this.

function relu(z) {
  return Math.max(0, z);
}
 
// Weighted sum of the inputs, plus the bias.
function weightedSum(inputs, weights, bias) {
  let z = bias;
  for (let i = 0; i < inputs.length; i++) z += inputs[i] * weights[i];
  return z;
}
 
// Two switches in, light out (1 = on).
function hallwayLight(s1, s2) {
  const h1 = relu(weightedSum([s1, s2], [1, 1], 0));  // switches up
  const h2 = relu(weightedSum([s1, s2], [1, 1], -1)); // both up?
  return weightedSum([h1, h2], [1, -2], 0);
}
 
hallwayLight(0, 0); // 0
hallwayLight(1, 0); // 1
hallwayLight(1, 1); // 0
def relu(z):
    return max(0, z)
 
def weighted_sum(inputs, weights, bias):
    """Weighted sum of the inputs, plus the bias."""
    return bias + sum(x * w for x, w in zip(inputs, weights))
 
def hallway_light(s1, s2):
    """Two switches in, light out (1 = on)."""
    h1 = relu(weighted_sum([s1, s2], [1, 1], 0))   # switches up
    h2 = relu(weighted_sum([s1, s2], [1, 1], -1))  # both up?
    return weighted_sum([h1, h2], [1, -2], 0)
 
hallway_light(0, 0)  # 0
hallway_light(1, 0)  # 1
hallway_light(1, 1)  # 0

Why the activation function matters

If you remove ReLU from the hallway network, the output becomes (s1 + s2) − 2 × (s1 + s2 − 1), which simplifies to 2 − s1 − s2. That is a single weighted sum again, and it gives 2 when both switches are down, which is wrong. Layers of plain weighted sums always collapse into one weighted sum, however many layers there are, so the activation function is what lets each layer build something new from the previous one.

Activation functions, size and architectures

Activation functions

ReLU is the usual default for hidden layers because it is cheap to compute and its gradient is 1 for positive inputs, so training signals pass through many layers without shrinking. Its weakness is that a neuron whose input is always negative outputs 0 and receives no gradient, so it stops learning. This is called a dead neuron, and it is more likely with a very high learning rate.

The sigmoid function squashes any number into the range 0 to 1, so it suits an output layer that predicts one probability, such as spam or not spam. When the network must choose between several classes, the output layer uses softmax, which turns a list of scores into probabilities that add up to 1. Sigmoid is a poor choice for deep hidden layers because its gradient is close to zero when the input is large in either direction, and repeating that across many layers makes the early layers learn very slowly. This is the vanishing gradient problem.

Depth and width

Width is the number of neurons in a layer and depth is the number of layers. More of either gives the network more capacity to fit complicated patterns, and both cost more computation and memory. A network with too much capacity for its data memorises the training examples and does worse on new ones, which Overfitting and Evaluation covers. Start with a small network, check it can fit the training data, and grow it only if it cannot.

Architectures for different data

The network above is a feedforward network, where every neuron reads every output of the previous layer. It works well for tabular data, but other kinds of data have structure that a better-shaped network can use. Convolutional networks reuse the same small set of weights across every position in an image, so they find a pattern wherever it appears and need far fewer weights. Recurrent networks process a sequence one step at a time and carry a hidden state forward, which suits ordered data but makes long sequences slow to train. Transformers let every position in a sequence look at every other position directly, and they are the architecture behind current language models, covered in Attention and Transformers. All of them are still layers of weighted sums and activations trained by backpropagation.

How a network is trained

Training uses the loop from How Models Learn: compute the loss on the training examples, compute the gradient of the loss with respect to every weight, and move each weight a small step against its gradient. The weights start as small random numbers, not zeros, because identical weights would make every neuron in a layer compute the same thing and receive the same updates. The difficult part is the gradient, because a weight in the first layer affects the output through every later layer.

In practice the loss is not computed over the whole dataset for every step. The training set is split into small batches, each step uses the gradient from one batch, and one pass over all the batches is called an epoch. Batches make each step cheap, and the noise from using a sample is usually harmless. The loss function depends on the task: squared error is common for predicting a number, and cross-entropy, which punishes confident wrong probabilities heavily, is used for classification. A network that overfits can also be helped by early stopping, which halts training when the held-out score stops improving, or by dropout, which switches off a random share of neurons at each training step so the network cannot depend on any single one.

The solution is to multiply the rates of change along the path from the weight to the output. Take the weight from s1 to h2 with both switches up, and increase it by 0.01.

  • The sum going into h2 rises by 0.01 × 1 = 0.01, because s1 is 1.
  • ReLU passes the change through unchanged, because its input of 1 is positive.
  • The output changes by −2 times that amount, so it falls by 0.02.

The rate of change of the output with respect to this weight is therefore 1 × 1 × (−2) = −2, found by multiplying along the path. This is the chain rule from calculus. Multiplying by one more factor, the rate at which the loss changes with the output, gives the gradient of the loss.

Backpropagation computes this for every weight at once. It starts at the output and works backwards, reusing the rates already computed for each layer when it handles the layer before. One backward sweep costs only a small multiple of one forward pass, which is why networks with billions of weights can be trained at all.

Pitfalls

What this changes in practice

Start with the simplest model that could work. If a linear model or a decision tree reaches the accuracy you need, a neural network adds cost and tuning without benefit. Networks pay off on unstructured data such as images, audio and text, where useful features are hard to design by hand, and when you have a lot of examples.

When you do train one, use ReLU in the hidden layers, scale your inputs, and begin with a small network that you check can fit a handful of training examples exactly. If it cannot, the bug is in the code or the learning rate, not in the amount of data. Then evaluate on held-out examples and increase the size only when the held-out score justifies it.

Try it yourself

Try it: Rewire the output

Keep the hidden neurons: h1 counts the switches that are up, and h2 is 1 only when both are up. Choose output weights so that the light is on (a) only when both switches are up, and (b) when at least one switch is up. Check all four positions.

Show a sample answer

(a) Both up: use light = 0 × h1 + 1 × h2. The positions (0,0), (1,0), (0,1) and (1,1) give 0, 0, 0 and 1.

(b) At least one up: use light = 1 × h1 − 1 × h2. The four positions give 0, 1, 1 and 2 − 1 = 1.

Only the last layer changed. Once a network has useful intermediate features, many different answers are only one weighted sum away.

Check yourself

Quick check

A neuron's weighted sum plus bias is −3. What does ReLU output?

You build a 10-layer network but forget every activation function. What can it learn?

What does backpropagation compute?

Your network's loss is very low on the training set but poor on new examples. What is the most likely cause?

What to practise next

The hidden values inside a network are lists of numbers that capture what it learned about its input. Embeddings shows how to use them to place words, documents and products as points where similar things sit close together.