Neural Networks
From a single neuron to deep networks — perceptrons, layers, activation functions (ReLU, GELU, sigmoid, softmax), why depth and non-linearity matter, the universal approximation theorem, initialisation, normalisation, dropout, and building and training an MLP in PyTorch.
A neural network is a function built from many simple units — neurons — organised in layers. Each layer transforms its input a little; stacked together, they can learn remarkably complex mappings: pixels → "cat", audio → text, a prompt → an essay.
The neuron
A neuron computes a weighted sum of its inputs plus a bias, then applies a non-linear activation function:
With a sigmoid activation, one neuron is logistic regression. The power comes from connecting many of them.
Layers: the multilayer perceptron
- Input layer: the features.
- Hidden layers: each computes — a matrix multiplication plus an activation.
- Output layer: shaped for the task — one linear unit for regression, a sigmoid for binary classification, a softmax over K units for multi-class.
A network with these fully connected (dense) layers is a multilayer perceptron (MLP). "Deep" learning simply means many layers. Every parameter — each weight and bias — is learned.
Why non-linearity?
Without activation functions, stacking layers is pointless: — still one linear transformation. Non-linear activations let each layer bend and fold the space, so the network can represent curved decision boundaries and complex functions.
The universal approximation theorem says a network with one sufficiently wide hidden layer can approximate any continuous function. In practice, deep networks are far more efficient: each layer builds on the previous one's features — edges → textures → parts → objects in vision; characters → words → syntax → meaning in language. This hierarchical representation learning replaces hand-crafted features.
Activation functions
| Function | Formula | Where used | Notes |
|---|---|---|---|
| ReLU | Default for hidden layers (CNNs, MLPs) | Cheap; no saturation for x > 0; "dead" neurons if stuck below 0 | |
| Leaky ReLU | Hidden layers | Avoids dead neurons | |
| GELU / SiLU (Swish) | smooth ReLU-like curves | Transformers (GPT, BERT, LLaMA's SwiGLU) | Smooth gradients |
| Sigmoid | Binary outputs, gates in LSTMs | Saturates → vanishing gradients in deep stacks | |
| Tanh | RNNs | Zero-centred; also saturates | |
| Softmax | Multi-class output | Produces a probability distribution |
Training
Training follows the same loop as any model (Gradient descent):
- Forward pass: compute predictions layer by layer.
- Loss: compare predictions to labels (cross-entropy, MSE).
- Backward pass: compute the gradient of the loss with respect to every weight via backpropagation.
- Update: an optimiser (AdamW, SGD + momentum) adjusts the weights.
A complete example in PyTorch
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
train = datasets.MNIST("data", train=True, download=True, transform=transforms.ToTensor())
test = datasets.MNIST("data", train=False, transform=transforms.ToTensor())
train_dl = DataLoader(train, batch_size=128, shuffle=True)
test_dl = DataLoader(test, batch_size=512)
model = nn.Sequential( # 784 → 256 → 128 → 10
nn.Flatten(),
nn.Linear(28 * 28, 256), nn.ReLU(), nn.Dropout(0.2),
nn.Linear(256, 128), nn.ReLU(), nn.Dropout(0.2),
nn.Linear(128, 10), # raw scores (logits); softmax is inside the loss
)
loss_fn = nn.CrossEntropyLoss()
opt = torch.optim.AdamW(model.parameters(), lr=1e-3)
for epoch in range(5):
model.train()
for x, y in train_dl:
loss = loss_fn(model(x), y) # forward + loss
opt.zero_grad()
loss.backward() # backprop
opt.step() # update
model.eval()
with torch.no_grad():
correct = sum((model(x).argmax(1) == y).sum().item() for x, y in test_dl)
print(f"epoch {epoch}: test accuracy {correct / len(test):.3%}") # ≈ 98%This 235k-parameter network recognises handwritten digits with about 98% accuracy.
Making deep networks trainable
| Technique | Problem solved |
|---|---|
| Careful initialisation (Xavier/Glorot, He/Kaiming) | Keeps activation and gradient magnitudes stable across layers at the start |
| Batch normalisation | Normalises each layer's inputs over the batch — faster, more stable training (CNNs) |
| Layer normalisation (and RMSNorm) | Normalises per example — used in transformers and RNNs |
| Residual connections | — gradients flow through the shortcut, enabling 100+ layer networks (ResNet, every transformer) |
| Dropout | Randomly zero activations during training — prevents co-adaptation; regularises |
| Weight decay | L2-style penalty on weights |
| Data augmentation | Random crops, flips, noise — more varied training data |
| Early stopping | Stop when validation loss rises |
Architectures for different data
The MLP treats inputs as an unordered vector. Specialised architectures build in structure:
| Data | Architecture | Built-in assumption |
|---|---|---|
| Images | CNNs | Local patterns, translation invariance |
| Sequences (older) | RNNs and LSTMs | Order; processed step by step |
| Sequences, text, and now almost everything | Transformers | Attention between all positions |
| Graphs | Graph neural networks | Message passing between neighbours |
| Generating images | Diffusion models | Iterative denoising |
When to use neural networks
| Use deep learning | Prefer classical ML |
|---|---|
| Images, audio, video, natural language | Tabular data with meaningful columns |
| Very large datasets | Small datasets (hundreds to tens of thousands of rows) |
| Pretrained models are available to fine-tune | Interpretability is required |
| GPU compute is available | Fast, cheap training and inference matter |
- A neuron computes an activation of a weighted sum; layers are matrix multiplications followed by non-linearities.
- Non-linear activations make depth meaningful; deep networks learn hierarchical features.
- ReLU/GELU in hidden layers; sigmoid or softmax at the output for classification.
- Training: forward pass, loss, backpropagation, optimiser step.
- Initialisation, normalisation, residual connections, dropout and augmentation make deep networks trainable and generalisable.
- Choose architectures that match the data: CNNs for images, transformers for sequences.