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.

Intermediate 4 min readLesson 7 of 14

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:

a=f(∑iwixi+b)=f(w⊤x+b)a = f\left(\sum_i w_i x_i + b\right) = f(\mathbf{w}^\top \mathbf{x} + b)

With a sigmoid activation, one neuron is logistic regression. The power comes from connecting many of them.

Layers: the multilayer perceptron

x₁x₂x₃h₁h₂h₃h₄ŷ₁ŷ₂
  • Input layer: the features.
  • Hidden layers: each computes h=f(Wx+b)\mathbf{h} = f(W\mathbf{x} + \mathbf{b}) — 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: W2(W1x)=(W2W1)xW_2(W_1\mathbf{x}) = (W_2W_1)\mathbf{x} — 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

FunctionFormulaWhere usedNotes
ReLUmax⁡(0,x)\max(0, x)Default for hidden layers (CNNs, MLPs)Cheap; no saturation for x > 0; "dead" neurons if stuck below 0
Leaky ReLUmax⁡(0.01x,x)\max(0.01x, x)Hidden layersAvoids dead neurons
GELU / SiLU (Swish)smooth ReLU-like curvesTransformers (GPT, BERT, LLaMA's SwiGLU)Smooth gradients
Sigmoid1/(1+e−x)1/(1+e^{-x})Binary outputs, gates in LSTMsSaturates → vanishing gradients in deep stacks
Tanhtanh⁡(x)\tanh(x)RNNsZero-centred; also saturates
Softmaxezk/∑jezje^{z_k} / \sum_j e^{z_j}Multi-class outputProduces a probability distribution

Training

Training follows the same loop as any model (Gradient descent):

  1. Forward pass: compute predictions layer by layer.
  2. Loss: compare predictions to labels (cross-entropy, MSE).
  3. Backward pass: compute the gradient of the loss with respect to every weight via backpropagation.
  4. Update: an optimiser (AdamW, SGD + momentum) adjusts the weights.

A complete example in PyTorch

Python
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

TechniqueProblem solved
Careful initialisation (Xavier/Glorot, He/Kaiming)Keeps activation and gradient magnitudes stable across layers at the start
Batch normalisationNormalises 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 connectionsh+F(h)\mathbf{h} + F(\mathbf{h}) — gradients flow through the shortcut, enabling 100+ layer networks (ResNet, every transformer)
DropoutRandomly zero activations during training — prevents co-adaptation; regularises
Weight decayL2-style penalty on weights
Data augmentationRandom crops, flips, noise — more varied training data
Early stoppingStop when validation loss rises

Architectures for different data

The MLP treats inputs as an unordered vector. Specialised architectures build in structure:

DataArchitectureBuilt-in assumption
ImagesCNNsLocal patterns, translation invariance
Sequences (older)RNNs and LSTMsOrder; processed step by step
Sequences, text, and now almost everythingTransformersAttention between all positions
GraphsGraph neural networksMessage passing between neighbours
Generating imagesDiffusion modelsIterative denoising

When to use neural networks

Use deep learningPrefer classical ML
Images, audio, video, natural languageTabular data with meaningful columns
Very large datasetsSmall datasets (hundreds to tens of thousands of rows)
Pretrained models are available to fine-tuneInterpretability is required
GPU compute is availableFast, cheap training and inference matter
Key takeaways
  • 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.