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
- Builds on
- 13 concepts →
- Quiz
- 5 questions ↓
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 ExplainabilityThe full path from zero — 13 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Supervised Learning
- Linear Regression
- The Perceptron
- Logistic Regression
- 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 : 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 , computes , and outputs . Here ("sigma") is the sigmoid function, , 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 and the biases into a vector . Then the whole layer is one line:
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 to each entry separately. The result holds one activation per neuron.
Shapes are where people trip up, so name them. If the layer reads numbers and has neurons:
- has entries,
- has rows and columns, so weights,
- and have 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:
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 .
- Yes/no classification: one output neuron with a sigmoid, read as the probability of "yes".
- Choosing one of classes: output neurons. Their raw scores, called logits, go through softmax, which turns them into probabilities that add up to 1. The Activation Functions chapter explains softmax in detail.
Count the parameters in the digit network above. The first layer has a weight matrix (2,048 numbers) and 32 biases, so 2,080 in total. The second has 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 parameters. Fully connected layers grow fast.
Why the nonlinearity is essential
What if you left out and just stacked matrix multiplies? Then . That is a single matrix times 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 for the sigmoid. The idea: hidden neuron acts like OR, hidden neuron acts like AND, and the output computes "OR but not AND".
The weights are large so that the sigmoid behaves almost like a step: and .
Take the input :
- Hidden weighted sums: .
- Hidden activations: . OR is on, AND is off.
- Output sum: , so . Correct.
All four inputs:
| hidden sums | (rounded) | output sum | 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.
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:
- Start with small random weights.
- Run the forward pass on a batch of training examples.
- Measure the error with a loss function, such as cross-entropy for classification.
- Compute how the loss changes with every weight. This is the gradient, and Backpropagation computes it efficiently.
- Nudge every weight a little against its gradient: Gradient Descent.
- 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 input vectors as the rows of a matrix with shape . Then the whole layer for the whole batch is a single matrix multiply, , where is the transpose of 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 , 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.Linearlayers without activations between them is just one linear layer. It will train, but it can only learn straight-line boundaries. - Applying softmax twice.
nn.CrossEntropyLossexpects 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:
- Activation Functions: sigmoid is historical. Modern networks mostly use ReLU and its relatives, and you'll see why.
- Why Neural Networks Work: why a network with enough hidden neurons can approximate any reasonable function, and why depth helps.
- Backpropagation: how the gradients for every weight are computed in one backward pass.
- Training Neural Networks in Practice: the practical recipe for getting a network to train well.
- Specialised architectures change how layers connect. Convolutional networks share weights across image positions, recurrent networks reuse a layer along a sequence, and Transformers let positions exchange information through Attention. Inside each Transformer block, though, sits a plain two-layer MLP just like this one.
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
- In the NumPy XOR code, change the hidden layer to 2 neurons (
W1of shape (2, 2),W2of shape (2, 1)). Does it still learn? Try seeds 0 to 30 indefault_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?- 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.)- 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 = for hidden size .
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Neural Networks (video series)
Gorgeous animated explanations of neural nets, gradient descent, backprop, Transformers and attention.
Neural Networks and Deep Learning
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.
TensorFlow Playground
Train a small neural network in your browser and watch it learn decision boundaries live.
Dive into Deep Learning
An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.
Neural Networks: Zero to Hero
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.
Understanding Deep Learning
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