Home / Learn / AI, explained simply

Neural networks explained simply: neurons, weights and training

New to this? Read from the top. Already know the basics? Jump to Going deeper for intermediate and advanced detail.

A neural network: an input layer, two hidden layers and an output layer, with a close-up of one neuron that multiplies each input by a weight, adds a bias and applies an activation function
Beginner

Every modern AI system, from the face unlock on your phone to the chatbots that write code, is built from neural networks. The name makes them sound like artificial brains. They're much simpler than that: a neural network is a big pile of multiplications and additions, with numbers that are adjusted, bit by bit, until the output comes out right. This guide explains the parts and how the adjusting (training) works, using a network small enough to run on a Raspberry Pi in a fraction of a second.

One artificial neuron

A neuron takes some numbers in, and does three things:

  1. multiplies each input by its own weight, which says how much that input matters,
  2. adds them up, plus one extra number called the bias,
  3. passes the total through an activation function, which decides how strongly the neuron "fires".

output = activation(w1x1 + w2x2 + … + b)

Example: with inputs 1 and 0, weights 0.9 and 0.2 and a bias of −0.3, the sum is 0.9 × 1 + 0.2 × 0 − 0.3 = 0.6. If you know electronics, it's a bit like a summing amplifier where each input has its own gain, followed by a stage that clips or squashes the output.

Without the activation function, stacking neurons would just give one big weighted sum, however many you used. The bend that the activation adds is what lets networks learn curved, complicated relationships. Common choices are the sigmoid (squashes any number into 0 to 1) and ReLU (passes positive numbers, turns negatives into 0).

Layers

A network arranges neurons in layers. The input layer is just the data: pixel brightnesses, sensor readings or, in a language model, numbers representing words. Each hidden layer takes the previous layer's outputs as its inputs. The output layer gives the answer, such as "cat: 0.92, dog: 0.08". "Deep learning" simply means networks with many hidden layers.

The numbers that get learned, all the weights and biases, are called parameters. The tiny network below has 3. GPT-3, released in 2020, had 175 billion. The idea is the same; only the scale is different.

How a network learns

A new network starts with random weights, so its answers are rubbish. Training repeats four steps over and over, across thousands or billions of examples:

  1. Forward pass: feed in an example and get the network's answer.
  2. Loss: measure how wrong the answer was compared with the correct one. This single number is the loss.
  3. Backpropagation: work backwards through the network to find, for every weight, which direction to nudge it to reduce the loss, and by how much. This uses the chain rule from calculus.
  4. Gradient descent: nudge every weight a small step in that direction. The size of the step is the learning rate.

Picture standing on a foggy hillside trying to reach the valley floor: you can't see the bottom, but you can feel which way the ground slopes under your feet, so you take a small step downhill and repeat. The "ground" is the loss, and its slope is the gradient.

A network you can run

This single neuron learns the logical OR function (output 1 if either input is 1). It's plain Python with no libraries, and it follows exactly the four steps above:

# A single neuron that learns the OR function by gradient descent
import math, random

random.seed(1)
w1, w2, b = random.uniform(-1, 1), random.uniform(-1, 1), 0.0
data = [((0, 0), 0), ((0, 1), 1), ((1, 0), 1), ((1, 1), 1)]

def sigmoid(z):
    return 1 / (1 + math.exp(-z))

lr = 0.5
for epoch in range(2000):
    for (x1, x2), target in data:
        out = sigmoid(w1 * x1 + w2 * x2 + b)
        error = out - target            # how wrong we were
        grad = error * out * (1 - out)  # chain rule through the sigmoid
        w1 -= lr * grad * x1
        w2 -= lr * grad * x2
        b -= lr * grad

for (x1, x2), target in data:
    print(x1, x2, "->", round(sigmoid(w1 * x1 + w2 * x2 + b), 3), "target", target)

The real output:

0 0 -> 0.055 target 0
0 1 -> 0.966 target 1
1 0 -> 0.966 target 1
1 1 -> 1.0 target 1

After training, the answers are close to the targets. They're never exactly 0 or 1 because the sigmoid only approaches those values. Nobody told the neuron the rule for OR. It found weights that produce it, purely from the examples. That's the whole trick, scaled up.

Try changing the data to XOR (1 only when the inputs differ: targets 0, 1, 1, 0). A single neuron can't learn it however long you train, because no single straight line separates the 1s from the 0s. Add a hidden layer of two or more neurons and it can. That limitation, and how hidden layers overcome it, is a big part of why networks are built in layers.

Overfitting: learning the answers, not the lesson

A big enough network can simply memorise its training examples, including their noise, and then do badly on anything new. That's overfitting, like a student who memorises past exam papers without understanding them. To catch it, part of the data is kept back as a test set the network never trains on. If it scores well on training data but poorly on the test set, it has overfitted. More data, smaller networks and techniques such as dropout help.

What neural networks are good and bad at

  • Good at: finding patterns in huge amounts of messy data: images, speech, text, sensor signals.
  • Bad at: explaining their answers (the knowledge is spread across millions of weights), exact rules they've seen few examples of, and anything far outside their training data.
  • Confident when wrong: a network always gives an answer, even for an input unlike anything it was trained on. Our guide to why AI makes things up explains how that shows up in chatbots.

Language models are neural networks with a particular design, the transformer; see transformers and attention explained. How the biggest ones are trained is in how AI models are trained.

Intermediate and advanced

Going deeper

The gradient in the example

The loss used is half the squared error, L = ½(out − target)². By the chain rule, ∂L/∂w1 = (out − target) × out × (1 − out) × x1, because the derivative of the sigmoid σ(z) is σ(z)(1 − σ(z)). That's the grad * x1 line. Backpropagation is this same chain rule applied layer by layer, reusing the results from the layer above so the whole network's gradients cost roughly as much as one extra pass.

Why ReLU took over from sigmoid

The sigmoid's slope is at most 0.25 and close to zero for large inputs. Multiply many of those together through a deep network and the gradient reaching the early layers all but vanishes, so they barely learn: the vanishing gradient problem. ReLU has a slope of exactly 1 for positive inputs, which keeps gradients alive and made very deep networks practical.

Batches and optimisers

Real training averages the gradient over a mini-batch of examples rather than updating after each one, which is smoother and suits GPUs. Plain gradient descent is usually replaced by an optimiser such as Adam, which adapts the step size for each weight separately.

Universal approximation

A network with one hidden layer and enough neurons can approximate any continuous function on a bounded range as closely as you like. That says such weights exist, not that training will find them or that the network will be a sensible size, which is why depth and architecture still matter in practice.

Sources

The main references behind this guide. Numbers we worked out ourselves, such as the code outputs, come from running the code.