◆ AI All-in-One

Level 3 In-Depth AI · Deep Learning

Neural Networks

Stack layers of simple neurons and you get a machine that can learn almost any pattern. Each layer is a matrix multiply followed by a squashing function, and a network that reads handwritten digits fits in twenty lines of code.

Level
●●●●● Easy
Reading
14 min
To learn it well
1 hour to read, an afternoon to practise
↗ Plan a path here

Read first

The PerceptronLogistic RegressionMatrices and Matrix Multiplication

This leads to

Activation FunctionsBackpropagationConvolutional Neural NetworksDropout and Regularizing Neural NetworksGraph Neural NetworksRecurrent Neural NetworksSelf-Supervised LearningWord EmbeddingsAutoencodersWhat Generative Models DoQuantizationMonte Carlo Tree Search and AlphaGoDeep Q-NetworksModel-Based RL and World ModelsPolicy GradientsAdversarial ExamplesInterpretability and Explainability
The full path from zero — 13 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. How Machines Learn
  6. Partial Derivatives and Gradients
  7. Matrices and Matrix Multiplication
  8. Supervised, Unsupervised and Reinforcement Learning
  9. Gradient Descent
  10. Supervised Learning
  11. Linear Regression
  12. The Perceptron
  13. Logistic Regression
  14. Neural Networks

Read them roughly in this order. See it on the concept map →

Why it matters

A single The Perceptron can only draw one straight line through its inputs. That is enough to tell AND from not-AND, but not enough for XOR, let alone for telling a cat from a dog. A neural network gets past that limit by wiring many artificial neurons together in layers, so that the outputs of one layer become the inputs of the next.

That one idea, layers of simple units, is the core of nearly every AI system you have heard of. Image classifiers, speech recognisers, Transformers and the large language models built on them are all neural networks. They differ in how the layers are connected and how big they are, but each is made of the same pieces this chapter introduces: weights, biases, matrix multiplies and a nonlinear function between them. GPT-3, for example, has 175 billion weights. The little network at the end of this chapter has 2,410. They work the same way.

The intuition

Think of an assembly line in a factory. The first station does something simple with the raw material, the next station works on what the first one produced, and so on. No single station builds a car, but the line as a whole does.

A neural network is an assembly line for information. Raw inputs, such as the pixel brightnesses of a photo, enter the first layer. Each neuron in that layer computes a weighted sum of the inputs, adds a bias, and passes the result through a squashing function. Together the outputs of a layer form a new list of numbers, a new description of the input. The next layer works on that description, not on the raw pixels.

Each layer can detect patterns in the previous layer's patterns. In a network trained on photos, early neurons respond to simple things like edges at certain angles, middle neurons to combinations of edges such as corners and textures, and late neurons to whole parts like eyes or wheels. Nobody programs these detectors. They emerge during training because they help reduce the error.

The layers between the input and the output are called hidden layers, since you never see their values directly. They are where the network invents its own features. That is the big shift from classical machine learning, where people designed the features by hand (see Feature Engineering).

Key idea A neural network is layers of neurons. Each layer computes activation(Wx+b)\text{activation}(\mathbf{W}\mathbf{x} + \mathbf{b}): a matrix multiply, plus a bias, through a nonlinear function. Hidden layers learn their own features, which is what lets the network solve problems a single neuron can't.

How it works

From one neuron to a layer

A single neuron, as in Logistic Regression, takes an input vector x\mathbf{x}, computes z=w⋅x+bz = \mathbf{w} \cdot \mathbf{x} + b, and outputs σ(z)\sigma(z). Here σ\sigma ("sigma") is the sigmoid function, σ(z)=1/(1+e−z)\sigma(z) = 1/(1 + e^{-z}), a smooth S-curve that squashes any number into the range 0 to 1. It replaces the perceptron's hard step, which matters because smooth functions have slopes that Gradient Descent can follow. The output of a neuron after its squashing function is called its activation.

Now put several neurons side by side, all reading the same input. Each has its own weight vector and its own bias. Stack the weight vectors as the rows of a matrix W\mathbf{W} and the biases into a vector b\mathbf{b}. Then the whole layer is one line:

h=σ(Wx+b)\mathbf{h} = \sigma(\mathbf{W}\mathbf{x} + \mathbf{b})

Read it right to left. Multiply the input vector by the weight matrix, which computes every neuron's weighted sum at once. Add the bias vector. Apply σ\sigma to each entry separately. The result h\mathbf{h} holds one activation per neuron.

Shapes are where people trip up, so name them. If the layer reads ninn_{\text{in}} numbers and has noutn_{\text{out}} neurons:

  • x\mathbf{x} has ninn_{\text{in}} entries,
  • W\mathbf{W} has noutn_{\text{out}} rows and ninn_{\text{in}} columns, so nout×ninn_{\text{out}} \times n_{\text{in}} weights,
  • b\mathbf{b} and h\mathbf{h} have noutn_{\text{out}} entries.

Because every input connects to every neuron, this is called a fully connected layer (also a dense or linear layer).

Stacking layers: the forward pass

A multilayer perceptron (MLP) is a stack of fully connected layers. With one hidden layer:

h=σ(W1x+b1),y^=output(W2h+b2)\mathbf{h} = \sigma(\mathbf{W}_1 \mathbf{x} + \mathbf{b}_1), \qquad \hat{\mathbf{y}} = \text{output}(\mathbf{W}_2 \mathbf{h} + \mathbf{b}_2)

Computing the output from the input, layer by layer, is the forward pass. The number of layers is the network's depth, and the number of neurons in a layer is its width. "Deep learning" just means networks with many layers.

The output layer's function depends on the task:

  • Regression (predict a number): no squashing at all, just W2h+b2\mathbf{W}_2\mathbf{h} + \mathbf{b}_2.
  • Yes/no classification: one output neuron with a sigmoid, read as the probability of "yes".
  • Choosing one of KK classes: KK output neurons. Their raw scores, called logits, go through softmax, which turns them into KK probabilities that add up to 1. The Activation Functions chapter explains softmax in detail.
⋮ ⋮ ⋮ input x 64 pixel values shape (64,) hidden h 32 neurons shape (32,) output 10 scores, one per digit shape (10,) W₁: 32 × 64 b₁: 32 · 2,080 parameters W₂: 10 × 32 b₂: 10 · 330 parameters h = sigmoid(W₁x + b₁) scores = W₂h + b₂ → softmax total: 2,410 learnable numbers
Fig. 1 A small network that reads 8×8 images of handwritten digits. 64 pixel values feed 32 hidden neurons, which feed 10 output scores, one per digit. The weight matrices hold 2,080 and 330 numbers.

Count the parameters in the digit network above. The first layer has a 32×6432 \times 64 weight matrix (2,048 numbers) and 32 biases, so 2,080 in total. The second has 10×32=32010 \times 32 = 320 weights and 10 biases, so 330. That's 2,410 learnable numbers. The classic MNIST version of this task uses 28×28 images, which is 784 pixels. A 784–128–10 network has 784×128+128+128×10+10=101,770784 \times 128 + 128 + 128 \times 10 + 10 = 101{,}770 parameters. Fully connected layers grow fast.

Why the nonlinearity is essential

What if you left out σ\sigma and just stacked matrix multiplies? Then W2(W1x+b1)+b2=(W2W1)x+(W2b1+b2)\mathbf{W}_2(\mathbf{W}_1\mathbf{x} + \mathbf{b}_1) + \mathbf{b}_2 = (\mathbf{W}_2\mathbf{W}_1)\mathbf{x} + (\mathbf{W}_2\mathbf{b}_1 + \mathbf{b}_2). That is a single matrix times x\mathbf{x} plus a single bias: one layer in disguise. A hundred linear layers collapse into one, and one layer can only draw straight lines. The nonlinear function between layers is what lets depth add power. Activation Functions covers the modern choices, such as ReLU.

A worked example: XOR with two hidden neurons

The perceptron chapter showed that XOR can't be solved by one straight line. Here is a network with two hidden neurons that solves it, with weights set by hand so you can follow every number. Write σ\sigma for the sigmoid. The idea: hidden neuron h1h_1 acts like OR, hidden neuron h2h_2 acts like AND, and the output computes "OR but not AND".

W1=(20202020),b1=(−10−30),w2=(20,−20),b2=−10\mathbf{W}_1 = \begin{pmatrix} 20 & 20 \\ 20 & 20 \end{pmatrix}, \quad \mathbf{b}_1 = \begin{pmatrix} -10 \\ -30 \end{pmatrix}, \quad \mathbf{w}_2 = (20, -20), \quad b_2 = -10

The weights are large so that the sigmoid behaves almost like a step: σ(10)≈0.99995\sigma(10) \approx 0.99995 and σ(−10)≈0.00005\sigma(-10) \approx 0.00005.

Take the input x=(0,1)\mathbf{x} = (0, 1):

  1. Hidden weighted sums: W1x+b1=(20⋅0+20⋅1−10,  20⋅0+20⋅1−30)=(10,−10)\mathbf{W}_1\mathbf{x} + \mathbf{b}_1 = (20 \cdot 0 + 20 \cdot 1 - 10,\; 20 \cdot 0 + 20 \cdot 1 - 30) = (10, -10).
  2. Hidden activations: h=(σ(10),σ(−10))≈(1.000,0.000)\mathbf{h} = (\sigma(10), \sigma(-10)) \approx (1.000, 0.000). OR is on, AND is off.
  3. Output sum: 20⋅1.000−20⋅0.000−10≈1020 \cdot 1.000 - 20 \cdot 0.000 - 10 \approx 10, so y^=σ(10)≈1.000\hat{y} = \sigma(10) \approx 1.000. Correct.

All four inputs:

x\mathbf{x} hidden sums h\mathbf{h} (rounded) output sum y^\hat{y} XOR
(0, 0) (−10, −30) (0, 0) −10.0 0.000 0
(0, 1) (10, −10) (1, 0) 10.0 1.000 1
(1, 0) (10, −10) (1, 0) 10.0 1.000 1
(1, 1) (30, 10) (1, 1) −10.0 0.000 0

Here is what the hidden layer did geometrically. It moved the four points into a new space where (0, 1) and (1, 0) land on the same spot, and that new arrangement is separable by a straight line.

x₁ x₂ Input space XOR: not separable h₁ (OR) h₂ (AND) Hidden space now one line works h₁ h₂ from (0,0) from (0,1) and (1,0) from (1,1) hidden layer h = sigmoid(W₁x + b₁) XOR = 1 XOR = 0 output neuron's line
Fig. 2 Left: in the original input space no line separates the XOR classes, but each hidden neuron draws its own line. Right: the hidden layer maps the four inputs to new coordinates (h₁, h₂), where a single line from the output neuron separates them.

This is the deepest idea in the chapter. Each layer changes the representation of the data until the final problem becomes easy. For XOR, one bend is enough. For recognising faces, it takes dozens of layers of bending.

Learning the weights

Setting weights by hand works for XOR but not for 2,410 weights, let alone billions. Instead:

  1. Start with small random weights.
  2. Run the forward pass on a batch of training examples.
  3. Measure the error with a loss function, such as cross-entropy for classification.
  4. Compute how the loss changes with every weight. This is the gradient, and Backpropagation computes it efficiently.
  5. Nudge every weight a little against its gradient: Gradient Descent.
  6. Repeat thousands of times.

Why random and not zero? If every weight starts equal, every hidden neuron computes the same thing and receives the same update, so they stay identical forever. Random starting values break that symmetry. Weight Initialization explains how to choose their size.

Batches as matrices

In practice you push many examples through at once. Stack NN input vectors as the rows of a matrix X\mathbf{X} with shape N×ninN \times n_{\text{in}}. Then the whole layer for the whole batch is a single matrix multiply, H=σ(XW⊤+b)\mathbf{H} = \sigma(\mathbf{X}\mathbf{W}^\top + \mathbf{b}), where W⊤\mathbf{W}^\top is the transpose of W\mathbf{W} and the bias is added to every row. One big matrix multiply is exactly the kind of work GPUs do extremely fast. That match between neural networks and graphics hardware is a large part of why deep learning took off around 2012.

In code

First, an MLP in plain NumPy that learns XOR from random weights. It uses four hidden neurons, sigmoid activations, cross-entropy loss and gradient descent. The backward pass is written out in four lines. Don't worry about where they come from yet; Backpropagation derives them.

import numpy as np

X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=float)   # shape (4, 2)
y = np.array([[0], [1], [1], [0]], dtype=float)               # XOR, shape (4, 1)

rng = np.random.default_rng(0)
W1 = rng.normal(0, 1, (2, 4)); b1 = np.zeros(4)   # layer 1: 2 inputs -> 4 hidden
W2 = rng.normal(0, 1, (4, 1)); b2 = np.zeros(1)   # layer 2: 4 hidden -> 1 output
sigmoid = lambda z: 1 / (1 + np.exp(-z))
lr = 1.0

for step in range(5001):
    # forward pass: two matrix multiplies, each followed by a sigmoid
    H = sigmoid(X @ W1 + b1)          # (4, 4) hidden activations
    p = sigmoid(H @ W2 + b2)          # (4, 1) predicted probability of 1
    loss = -np.mean(y * np.log(p) + (1 - y) * np.log(1 - p))   # cross-entropy
    # backward pass (backpropagation, explained in its own chapter)
    dZ2 = (p - y) / len(X)
    dW2 = H.T @ dZ2;  db2 = dZ2.sum(0)
    dZ1 = (dZ2 @ W2.T) * H * (1 - H)
    dW1 = X.T @ dZ1;  db1 = dZ1.sum(0)
    for param, grad in [(W1, dW1), (b1, db1), (W2, dW2), (b2, db2)]:
        param -= lr * grad            # gradient descent step
    if step % 1000 == 0:
        print(f"step {step:4d}  loss {loss:.4f}")

print("predictions:", p.ravel().round(3))

# step    0  loss 0.9258
# step 1000  loss 0.0198
# ...
# step 5000  loss 0.0024
# predictions: [0.    0.997 0.997 0.004]

In code, weight matrices are usually stored with shape (inputs, outputs) and inputs as rows, so the layer reads X @ W1 + b1. It is the same computation as Wx+b\mathbf{W}\mathbf{x} + \mathbf{b}, just transposed.

Now a network that reads handwritten digits, in PyTorch. It uses scikit-learn's built-in digits dataset (1,797 images of 8×8 pixels), so it needs no download. nn.Linear is a fully connected layer, and nn.CrossEntropyLoss applies softmax and cross-entropy together.

import torch
from torch import nn
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split

digits = load_digits()                       # 1,797 handwritten digits, 8x8 pixels
X = torch.tensor(digits.data, dtype=torch.float32) / 16   # pixels 0..16 -> 0..1
y = torch.tensor(digits.target)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=0)

torch.manual_seed(0)
model = nn.Sequential(
    nn.Linear(64, 32),    # 64 pixels -> 32 hidden neurons
    nn.Sigmoid(),
    nn.Linear(32, 10),    # 32 hidden -> 10 scores, one per digit
)
opt = torch.optim.Adam(model.parameters(), lr=0.01)
loss_fn = nn.CrossEntropyLoss()

for epoch in range(100):
    loss = loss_fn(model(X_tr), y_tr)
    opt.zero_grad(); loss.backward(); opt.step()

acc = (model(X_te).argmax(1) == y_te).float().mean()
print(f"parameters: {sum(p.numel() for p in model.parameters())}")
print(f"final train loss {loss.item():.3f}, test accuracy {acc:.3f}")

# parameters: 2410
# final train loss 0.142, test accuracy 0.956

After 100 full-batch steps, which take about a second on a laptop, the network reads 95.6% of digits it has never seen correctly. The optimizer here is Adam, an improved form of gradient descent covered in Optimizers: SGD, Momentum and Adam.

Common pitfalls

  • Shape mismatches. The most common bug by far. Write the shape of every tensor as a comment, as in the NumPy example, and check that the inner dimensions of each matrix multiply agree. See Tensors and Shapes.
  • Forgetting the nonlinearity. A stack of nn.Linear layers without activations between them is just one linear layer. It will train, but it can only learn straight-line boundaries.
  • Applying softmax twice. nn.CrossEntropyLoss expects raw logits and applies softmax itself. If your model already ends in a softmax, training still runs but learns slowly and badly.
  • Unscaled inputs. Pixel values of 0–255 instead of 0–1 push sigmoids into their flat regions, where gradients vanish. Scale or standardise inputs.
  • Too big too soon. A network with far more parameters than training examples can memorise the training set. Watch the test accuracy, not just the training loss, and see Overfitting and the Bias–Variance Tradeoff and Dropout and Regularizing Neural Networks.

Watch out A network that fits the training data perfectly can still be useless on new data. With 2,410 parameters and only 1,347 training images, our digit network could in principle memorise them. Always hold out a test set and judge the model on it. See Training, Validation and Test Sets.

Where it leads

The MLP is the starting point for everything in deep learning:

A bit of history

Multi-layer networks of perceptron-like units were discussed from the start, including by Frank Rosenblatt in the early 1960s, but nobody had a practical way to train the hidden layers. In 1986, David Rumelhart, Geoffrey Hinton and Ronald Williams showed in Nature that Backpropagation could train them and that hidden units learned useful internal representations. Others, including Paul Werbos in 1974, had described the method earlier.

In 1989, Yann LeCun and colleagues at Bell Labs trained a network to read handwritten ZIP codes, and their later systems read a sizeable share of the cheques in the United States in the late 1990s. The MNIST dataset of 70,000 handwritten digits, released by LeCun and colleagues in 1998, became the "hello world" of the field. Neural networks then fell out of fashion for a decade, overtaken by methods such as support vector machines, until faster GPUs, bigger datasets and better tricks brought them back in 2012 with AlexNet. See A Short History of AI.

Try it

  1. In the NumPy XOR code, change the hidden layer to 2 neurons (W1 of shape (2, 2), W2 of shape (2, 1)). Does it still learn? Try seeds 0 to 30 in default_rng. Most succeed, but some (seed 6, for example) get stuck with two predictions at 0.5. Why might fewer neurons make training easier to derail, even though two are enough in principle?
  2. In the PyTorch digits network, remove the nn.Sigmoid() line. What test accuracy do you get now? (We got 96.7%, slightly better: these small digit images are almost linearly separable, so this easy dataset doesn't need the hidden layer. Harder data does.)
  3. Change the hidden size from 32 to 8 and then to 128. Count the parameters each time by hand, then check with the code.

Hint for 3: parameters = 64×H+H+H×10+1064 \times H + H + H \times 10 + 10 for hidden size HH.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. A fully connected layer reads 64 numbers and has 32 neurons. How many learnable parameters does it have?

  2. A colleague builds a 10-layer network from nn.Linear layers with no activation functions between them. What can it learn?

  3. In the hand-built XOR network, what did the hidden layer actually do?

  4. Why are a network's weights started at small random values rather than all zeros?

  5. Your model ends in a softmax layer and you train it with PyTorch's nn.CrossEntropyLoss. Training runs but learns slowly and badly. Why?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Video

Neural Networks (video series)

3Blue1Brown · Beginner · Free

Gorgeous animated explanations of neural nets, gradient descent, backprop, Transformers and attention.

Book

Neural Networks and Deep Learning

Michael Nielsen · 2015 · Beginner · Free

A free online book that builds a handwritten-digit classifier from scratch in Python, explaining every step of perceptrons, sigmoid neurons, backpropagation and training tricks with great clarity.

Interactive

TensorFlow Playground

Google · Beginner · Free

Train a small neural network in your browser and watch it learn decision boundaries live.

Book

Dive into Deep Learning

Zhang, Lipton, Li & Smola · Intermediate · Free

An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.

Video

Neural Networks: Zero to Hero

Andrej Karpathy · Intermediate · Free

A video series that builds backprop, language models and finally GPT from an empty file. Many people consider it the best way to really understand LLMs.

Book

Understanding Deep Learning

Simon J. D. Prince · 2023 · Intermediate · Free

A modern, beautifully illustrated textbook covering everything from basics to Transformers and diffusion, with notebooks.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/dl/neural-networks.md