electronics engineering
Course handbook · Fourth year
Machine Learning and Neural Networks
Machine learning and neural networks: regression and gradient descent, multilayer networks and backpropagation, optimisers, convolutional and recurrent networks, transformers, training in practice, NumPy and PyTorch.
- 8Topics
- 0Solved exercises
- 15Formula sheet
Free handbook generated from the lessons of the site and updated often, every time a lesson or an exercise changes: the latest version is always at www.electronics-engineering.com/handbook/machine-learning. Links work in the PDF too.
1Regression and gradient descent
Machine learning builds models that learn from data instead of being programmed rule by rule: one chooses a family of functions with parameters, defines an error measuring how far predictions are from the data, and looks for the parameters that minimise it. All neural networks, even the largest, work this way. This first lesson presents the ingredients with the simplest models: linear regression (with the exact solution and the iterative one of gradient descent, whose convergence is proved), logistic regression for classification, and the central problem of the whole course, overfitting.
The supervised learning problem
There are
examples
: an input (a sensor’s measurements, an image’s pixels) and the right answer (a temperature, a digit). We want a function
that predicts
also for new inputs. A loss
is chosen and its average over the data is minimised:
![Rendered by QuickLaTeX.com \[ J(\mathbf w) = \frac{1}{n}\sum_{i=1}^n\ell\big(f_{\mathbf w}(\mathbf x_i),\ y_i\big) \]](https://www.electronics-engineering.com/wp-content/ql-cache/quicklatex.com-32be25159b3745567926c0e846e04f93_l3.png)
The real goal however is not to do well on the data at hand, but on the data that will come: this is why some examples are set aside (validation set and test set), not used for training and only used to measure.
Linear regression and the normal equations
With
(adding a constant component 1 to
, the first weight acts as the intercept) and the squared error, putting the examples in the rows of a matrix
:
![]()
Theorem. If
is invertible, the minimum is
(normal equations).
Proof.
is a convex quadratic function; the gradient is
and vanishes for
. The Hessian
is positive definite (if the columns of
are independent), so the stationary point is the only minimum. Geometrically,
is the orthogonal projection of
onto the space spanned by the columns of
: the residual
is perpendicular to all columns. ∎
Gradient descent
For more complicated models there is no closed formula. One starts from any
and takes small steps in the direction in which the error decreases fastest, the opposite of the gradient:
![]()
with
the learning rate. It is the algorithm that trains all neural networks.
Theorem (convergence on a quadratic). For a quadratic
with positive definite Hessian
, with eigenvalues
, gradient descent converges to
from any starting point if and only if
.
Proof. For a quadratic
, so the error
evolves as
. In the eigenvectors of
each component is multiplied at every step by
, and tends to zero if and only if
, i.e.
. The strictest condition is that of the largest eigenvalue,
. ∎
The speed depends on the condition number
: with the best step the reduction factor per step is
, close to 1 when the eigenvalues are very different. This is why inputs are normalised (same scale for all variables) and why the optimisers of lesson 4 exist.
Numerical example. With 50 points
noise, the normal equations give
. For these data
: gradient descent with
,
and
converges to the same result (with
213 steps are needed for an error of
), while with
, just beyond the limit, it diverges to values of
.
Classification: logistic regression
To predict a class (yes or no, fault or no fault) the sigmoid
is used, which turns any number into a probability:
.
Theorem. Maximising the likelihood of the data is equivalent to minimising the cross-entropy
, with
, and the gradient is
.
Proof. The probability of observing
is
; for independent examples the likelihood is the product, and its logarithm with changed sign and divided by
is
. For the gradient one uses
:
. ∎
The gradient has the same form as in linear regression: (prediction − truth) × input. With several classes the sigmoid becomes the softmax
and the gradient with respect to
is still
: it is the last layer of almost all classification networks.
Overfitting
A model that is too flexible also learns the noise in the data. With 15 points of
plus noise, polynomials of increasing degree are fitted and the mean squared error is measured on the training data and on 200 new points:
| degree | training error | error on new data |
|---|---|---|
| 1 | 0.252 | 0.259 |
| 3 | 0.013 | 0.095 |
| 9 | 0.007 | 0.808 |
| 14 | 0.002 | 50.2 |

The training error always decreases, the error on new data first decreases and then explodes. Degree 1 underfits (too simple: high bias), degree 14 overfits (too flexible: high variance). This is the bias-variance trade-off: the expected error on a new point decomposes into squared bias, plus the model’s variance as the data change, plus irreducible noise.
Regularisation penalises large weights:
(ridge, or weight decay in networks), with solution
(same proof as the normal equations). On the degree-14 polynomial with
the error on new data drops from 50.2 to 0.069, better even than degree 3. The value of
is chosen by looking at the validation set, never at the test set.
The code
import numpy as np
rng = np.random.default_rng(0)
x = rng.uniform(0, 1, 50)
y = 2 + 3 * x + rng.normal(0, 0.3, 50)
X = np.c_[np.ones(50), x] # column of 1s for the intercept
w_exact = np.linalg.solve(X.T @ X, X.T @ y) # normal equations
L = 2 * np.linalg.eigvalsh(X.T @ X / 50).max() # largest eigenvalue of the Hessian
print("normal equations:", np.round(w_exact, 4), " step limit 2/L =", round(2 / L, 3))
for eta in (0.5, 0.9 * 2 / L, 1.1 * 2 / L):
w = np.zeros(2)
for k in range(2000):
w -= eta * 2 / 50 * X.T @ (X @ w - y) # gradient descent
print(f"eta = {eta:.3f}:", np.round(w, 4) if np.all(np.isfinite(w)) else "diverges")
# overfitting: polynomials on 15 points, error on 200 new points
f = lambda t: np.sin(2 * np.pi * t)
xa = np.sort(rng.uniform(0, 1, 15)); ya = f(xa) + rng.normal(0, 0.2, 15)
xn = rng.uniform(0, 1, 200); yn = f(xn) + rng.normal(0, 0.2, 200)
def fit(degree, lam=0.0):
A = np.vander(xa, degree + 1, increasing=True)
return np.linalg.solve(A.T @ A + lam * np.eye(degree + 1), A.T @ ya) # ridge if lam > 0
def error(c, xs, ys):
return np.mean((np.vander(xs, len(c), increasing=True) @ c - ys) ** 2)
for degree, lam in ((1, 0), (3, 0), (9, 0), (14, 0), (14, 1e-3)):
c = fit(degree, lam)
print(f"degree {degree:2d}, lambda {lam:g}: training {error(c, xa, ya):.4f}, new data {error(c, xn, yn):.4f}")Running it reproduces the numbers in the text. The following lessons replace the linear model with neural networks, which are still trained by gradient descent and suffer from the same overfitting problems.
2Perceptron and multilayer networks
A neural network is a function built by composing many simple functions, the neurons: each computes a weighted sum of its inputs and passes it through a non-linear function. This lesson starts from the simplest neuron, Rosenblatt’s perceptron (1958), proves that it learns in a finite number of steps when the classes can be separated by a line, shows why a single layer is not enough (the XOR problem) and introduces multilayer networks, with the universal approximation theorem and an experiment showing how much the size of the network matters.
The perceptron
The perceptron classifies an input
into two classes,
and
, with the sign of a weighted sum:
. Geometrically, the boundary between the classes is the hyperplane
(a line in two dimensions). The learning algorithm is very simple: go through the examples and, when one is misclassified, move the weight vector towards it,
![]()
(the intercept
is included in
by adding a constant component 1 to
).
Theorem (Novikoff, 1962). If there is a unit vector
that separates the data with margin
, i.e.
for every
, and
, the perceptron makes at most
corrections.
Proof. Follow two quantities after
corrections, starting from
. The projection on
grows by at least
at each correction:
, so
. The norm instead grows little:
, because the correction happens only if
; so
. By the Cauchy-Schwarz inequality
, i.e.
. ∎
The bound depends neither on the number of examples nor on the dimension of the space, only on how “far apart” the classes are compared with their extent. In an experiment with 167 points separable with margin 0.15, the perceptron made 11 corrections in 3 passes over the data; Novikoff’s bound was 421: the theorem is a worst case, practice usually does much better.

The limit of one layer: XOR
The perceptron finds a line, but many problems cannot be separated by a line. The simplest is XOR (exclusive or): the output is 1 if exactly one of the two inputs is 1. The points (0, 1) and (1, 0) must be on one side, (0, 0) and (1, 1) on the other: no line can do it. Minsky and Papert pointed this out in 1969, and research on neural networks slowed down for years.
The solution is to add a hidden layer: the hidden neurons turn the inputs into new variables in which the problem becomes separable. Two hidden neurons are enough: one can compute “at least one is 1” (OR), the other “both are 1” (AND), and the output “OR but not AND”.

Multilayer networks
A multilayer network (multilayer perceptron, MLP) applies linear transformations and non-linearities in sequence:
![]()
The activation function
is essential: without it, the composition of linear transformations is still linear and the network would be no more powerful than a single layer. The most used:
- sigmoid
and hyperbolic tangent
: smooth, but they “saturate” for large
, where the derivative is almost zero; - ReLU
: very simple, derivative 1 for
, does not saturate in one direction. It has been the default choice since 2012; - smooth variants such as GELU and SiLU, used in transformers.
Universal approximation theorem (Cybenko 1989, Hornik 1991). A network with a single hidden layer and a non-polynomial activation can approximate with arbitrarily small error any continuous function on a closed and bounded set, provided it has enough neurons.
Proof idea (for one variable, with the sigmoid). A very steep sigmoid
is almost a step at
; the difference of two steps is a “rectangle” between
and
. A continuous function can be approximated by a step function (sums of rectangles) with error as small as desired, by narrowing the steps; each rectangle costs two neurons. ∎
The theorem says the network can represent the function, not that gradient descent will find it, nor how many neurons are needed (they can be very many). In practice deep networks, with many layers of moderate width, represent useful functions with far fewer parameters than a wide shallow network: each layer builds more abstract features from those of the previous layer.
An experiment: how big must the network be
XOR is trained with gradient descent starting from random weights, repeating with 100 different seeds, and counting how many times the network really learns the function:
| hidden neurons | XOR solved |
|---|---|
| 2 | 49 times out of 100 |
| 3 | 92 times out of 100 |
| 4 | 98 times out of 100 |
With two hidden neurons the solution exists, but half of the time gradient descent stops in a local minimum (for example with output 0.5 on two of the four cases). Adding neurons, the error landscape becomes easier to travel and almost every starting point leads to a solution. It is one of the reasons why modern networks have many more parameters than would be needed in theory.
import numpy as np
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], float)
y = np.array([0, 1, 1, 0], float) # XOR
sig = lambda z: 1 / (1 + np.exp(-z))
def train(hidden, seed, steps=10000, eta=0.5):
g = np.random.default_rng(seed)
W1, b1 = g.normal(0, 1, (2, hidden)), np.zeros(hidden)
W2, b2 = g.normal(0, 1, hidden), 0.0
for _ in range(steps):
h = np.tanh(X @ W1 + b1) # hidden layer
out = sig(h @ W2 + b2)
d2 = out - y # gradient of cross-entropy + sigmoid
dh = np.outer(d2, W2) * (1 - h ** 2) # derivative of tanh
W2 -= eta * h.T @ d2; b2 -= eta * d2.sum()
W1 -= eta * X.T @ dh; b1 -= eta * dh.sum(0)
return sig(np.tanh(X @ W1 + b1) @ W2 + b2)
for hidden in (2, 3, 4):
solved = sum(np.all(np.abs(train(hidden, s) - y) < 0.1) for s in range(100))
print(f"{hidden} hidden neurons: XOR solved {solved} times out of 100")
print("example with 3 neurons:", np.round(train(3, 0), 3))The gradient computation written by hand here, for one hidden layer, generalises to any number of layers with backpropagation, the subject of the next lesson.
3Backpropagation
To train a network with gradient descent the derivative of the loss with respect to every weight is needed: millions, or billions, of derivatives at each step. Computing them one by one would be impossible. Backpropagation (popularised by Rumelhart, Hinton and Williams in 1986) computes them all at a cost of the same order as evaluating the network (about three times in total), applying the chain rule backwards, from the output towards the input. This lesson derives it in matrix form for a multilayer network, explains why it is so efficient, implements it from scratch in NumPy and checks it with the numerical gradient check.
The computational graph and the chain rule
A network is a composition of functions:
. By the chain rule, the derivative with respect to a parameter of an inner layer is the product of the derivatives of all the layers that follow it. The key observation is that these products have common factors: the derivative with respect to the output of layer
is needed for the parameters of layer
and also, multiplied by one more factor, for all previous layers. Computing it only once, starting from the end, avoids repeating work. It is the same principle as dynamic programming.
Backpropagation for a multilayer network
For a network with layers
,
(with
), the layer error is defined as
.
Theorem (the backpropagation equations).
![]()
where
is the element-wise product.
Proof. Component
of
depends on
through
. By the chain rule
, which in vector form is the second equation. For the weights:
, so
and
. ∎
The last layer. With softmax and cross-entropy (lesson 1),
: the predicted probability minus the true one (encoded “one-hot”, 1 in the right class and 0 elsewhere). With a mini-batch of
examples,
and
become matrices with one example per row, and the formulas become
(averaged over the batch): matrix products, exactly what GPUs are very fast at.
The cost. The forward pass costs one matrix-vector product per layer; the backward pass two (one for
, one for the weight gradient). In total about three times the forward pass alone, regardless of the number of parameters. Computing derivatives with finite differences would instead require one forward pass for every parameter.

Automatic differentiation
Modern libraries (PyTorch, JAX, TensorFlow) do not ask you to write these formulas. During the forward pass they record every operation in a computational graph; calling backward() they traverse it backwards applying to each operation its known derivative. This is reverse-mode automatic differentiation: backpropagation generalised to any program, including conditions and loops. It is not a numerical approximation: the derivatives are exact, up to rounding.
The numerical gradient check
When backpropagation (or a new layer) is written by hand, it is checked with central differences: for a weight
,
, with an error of order
(the odd orders of the Taylor expansion cancel). With
and double-precision computations, a correct implementation gives a relative error around
–
; even a small mistake in the formula gives values of order
or more.
import numpy as np
def initialise(sizes, seed=0):
g = np.random.default_rng(seed)
return [(g.normal(0, np.sqrt(2 / a), (a, b)), np.zeros(b)) for a, b in zip(sizes[:-1], sizes[1:])]
def forward(params, X):
activations = [X]
for i, (W, b) in enumerate(params):
z = activations[-1] @ W + b
activations.append(np.maximum(z, 0) if i < len(params) - 1 else z) # ReLU, last layer linear
return activations
def loss_and_gradients(params, X, Y):
act = forward(params, X)
z = act[-1] - act[-1].max(1, keepdims=True)
p = np.exp(z); p /= p.sum(1, keepdims=True) # softmax
N = len(X)
loss = -np.log(p[np.arange(N), Y]).mean() # cross-entropy
delta = p.copy(); delta[np.arange(N), Y] -= 1; delta /= N # delta of the last layer: p - y
gradients = []
for i in range(len(params) - 1, -1, -1):
W, b = params[i]
gradients.append((act[i].T @ delta, delta.sum(0))) # dL/dW = h^T delta
if i > 0:
delta = (delta @ W.T) * (act[i] > 0) # delta backwards, ReLU derivative
return loss, gradients[::-1]
rng = np.random.default_rng(1)
X = rng.normal(0, 1, (8, 5)); Y = rng.integers(0, 3, 8) # 8 examples, 5 inputs, 3 classes
par = initialise([5, 7, 3])
_, grad = loss_and_gradients(par, X, Y)
eps, numerical = 1e-6, np.zeros_like(par[0][0])
for i in range(5):
for j in range(7):
par[0][0][i, j] += eps; Lp, _ = loss_and_gradients(par, X, Y)
par[0][0][i, j] -= 2 * eps; Lm, _ = loss_and_gradients(par, X, Y)
par[0][0][i, j] += eps
numerical[i, j] = (Lp - Lm) / (2 * eps) # central differences
error = np.abs(numerical - grad[0][0]).max() / np.abs(numerical).max()
print(f"relative error between backpropagation and central differences: {error:.1e}")Running it gives a relative error of about
–
: backpropagation is correct. The same two functions, with a gradient descent loop, are enough to train a real network: it is the project of the last lesson of the course, which recognises handwritten digits with 98 % accuracy.
4Optimisers
The gradient descent of lesson 1 works, but on neural networks it is slow: the error surface has narrow, long valleys, flat regions and millions of dimensions with very different curvatures. Modern optimisers modify the update rule to go faster and more stably. This lesson presents mini-batch stochastic gradient descent, momentum, RMSProp and Adam (the most used optimiser), proves why Adam needs the “bias correction”, discusses the choice of step size over time, and compares the methods on the Rosenbrock function, a curved valley that is the classic test bench.
Stochastic gradient descent
The gradient of the loss is an average over all
examples. With millions of examples, computing it entirely at each step is a waste. Stochastic gradient descent (SGD) uses at each step a mini-batch
of a few tens or hundreds of examples drawn at random:
![Rendered by QuickLaTeX.com \[ \mathbf g_k = \frac{1}{|B|}\sum_{i\in B}\nabla\ell_i(\mathbf w_k),\qquad \mathbf w_{k+1} = \mathbf w_k - \eta\,\mathbf g_k \]](https://www.electronics-engineering.com/wp-content/ql-cache/quicklatex.com-4d362c725b113ecb648d4d3d149b9930_l3.png)
is an unbiased estimate of the true gradient (the mean of a random sample has the population mean as its expectation), with a variance that decreases as
. The noise is not only a defect: it helps to escape flat regions and, according to many studies, leads to “wider” minima that generalise better. A complete pass over the data is called an epoch.
Momentum
In a narrow valley the gradient points mostly towards the walls: descent bounces from side to side and advances slowly along the bottom. Momentum (Polyak, 1964: the “heavy ball method”) accumulates a velocity:
![]()
with
. The gradient components that change sign at every step (across the valley) cancel in the average; those that always have the same sign (along the valley) add up. If the gradient were constant, the velocity would tend to
: with
a step ten times longer in the good direction.
RMSProp and Adam: one step size per parameter
Different parameters can have gradients of very different scales (for example the weights of the first layers and those of the last). RMSProp (Hinton, 2012) divides each parameter’s step by a moving average of the root of its squared gradient: those with large gradients take shorter steps, those with small ones longer steps. Adam (Kingma and Ba, 2014) combines this idea with momentum:
![]()
![]()
with the default values
,
,
. The effective step is almost independent of the gradient’s scale: it is about
in the direction of the sign of the average gradient.
Theorem (bias correction). If the gradients have constant mean
and
, then
; so
has mean exactly
.
Proof. Unrolling the recursion,
. Taking the mean,
. The same holds for
with
. ∎
Without correction, in the first steps
and
would be very close to zero (they start from zero) and, especially with
, the denominator would be underestimated: the first steps would be huge. After a few thousand steps
and the correction no longer matters. AdamW (2017) separates the weight penalty (weight decay) from the adaptive step, and is today the default choice for transformers.
The step size over time
A large constant step advances quickly but at the end “dances” around the minimum; a small one is precise but slow. This is why the step size is varied during training:
- warm-up: for a few hundred or thousand steps the step grows from zero to its full value, while Adam’s estimates settle and the network leaves the chaotic initial phase;
- decay: linear, stepwise, or cosine (the step follows half a cosine period down to almost zero). It was also seen in the PPO of the reinforcement learning course: the step decreasing to zero stabilised the final policy.
The comparison on the Rosenbrock function
The function
has its minimum at (1, 1) at the bottom of a narrow, curved, banana-shaped valley: at the bottom of the valley the gradient is almost zero, on the walls huge. Starting from (−1.5, 2), we count how many steps are needed to reach
:
| method | step | steps for |
|---|---|---|
| gradient descent | 0.001 | 15,681 |
| momentum ( | 0.001 | 1,484 |
| Adam | 0.02 | 2,286 |

Momentum is about ten times faster than plain descent (15,681 / 1,484 = 10.6), as predicted by the factor
. Adam, with a step that does not depend on the gradient’s scale, arrives in a similar number of steps. On real neural networks the differences are often less clear-cut and depend on the problem: SGD with momentum is still widely used for convolutional networks, Adam and AdamW for transformers and recurrent networks. The choice of step size almost always matters more than the choice of optimiser.
import numpy as np
f = lambda p: (1 - p[0]) ** 2 + 100 * (p[1] - p[0] ** 2) ** 2
grad = lambda p: np.array([-2 * (1 - p[0]) - 400 * p[0] * (p[1] - p[0] ** 2), 200 * (p[1] - p[0] ** 2)])
def optimise(method, eta, steps=20000):
p, v, m, s = np.array([-1.5, 2.0]), np.zeros(2), np.zeros(2), np.zeros(2)
for k in range(1, steps + 1):
g = grad(p)
if method == "gradient":
p = p - eta * g
elif method == "momentum":
v = 0.9 * v + g
p = p - eta * v
else: # Adam
m = 0.9 * m + 0.1 * g
s = 0.999 * s + 0.001 * g * g
m_hat, s_hat = m / (1 - 0.9 ** k), s / (1 - 0.999 ** k) # bias correction
p = p - eta * m_hat / (np.sqrt(s_hat) + 1e-8)
if f(p) < 1e-6:
return k
return None
for method, eta in (("gradient", 1e-3), ("momentum", 1e-3), ("adam", 2e-2)):
print(f"{method:9s}: f < 1e-6 after {optimise(method, eta)} steps")5Convolutional networks
A one-megapixel colour image has three million values: a dense network with a thousand neurons in the first layer would have three billion weights there alone, and would have to learn separately that a cat at the top left and a cat at the bottom right are the same thing. Convolutional networks (CNNs) solve both problems with two ideas taken from signal processing: the weights are local (each neuron looks only at a small area) and shared (the same filter slides over the whole image). This lesson defines convolution, proves the property that makes CNNs suited to images (translation equivariance), derives the size formulas, and compares a CNN with a dense network on handwritten digits.
Convolution
A convolutional layer applies a small filter (kernel)
, for example 3×3, at every position of the image
:
![]()
(neural networks use this form, which strictly speaking is a correlation; true convolution has the filter flipped, but since the filter is learned the difference does not matter). It is the same FIR filter of digital signal processing, in two dimensions. With several input channels (the three colours, or the outputs of the previous layer) the filter has one channel for each and the contributions are summed; with several filters several output feature maps are obtained.
A 3×3 filter with values
on every row, for example, responds to vertical edges. The network is not given hand-written filters: it learns them with backpropagation, and in the first layers of a trained CNN edge and colour-blob detectors appear; in the following layers, increasingly complex combinations (corners, textures, object parts).

Why it works: translation equivariance
Theorem. Convolution commutes with translations: if the image is shifted, the output map shifts by the same amount. With
the translation
:
.
Proof.
. ∎
An eye detector learned in a corner of the image automatically works everywhere: it need not be learned again for every position. This inductive bias (prior knowledge about the problem, built into the network’s structure) greatly reduces the parameters and data needed. To also obtain partial invariance (same response even if the object moves) pooling is added: 2×2 max-pooling replaces each 2×2 block of values with the maximum, halving the size and making the network insensitive to small shifts.
Sizes
For an input of side
, filter of side
, padding
(border of zeros added) and stride
, the output side is
![]()
(the filter starts at position 0 and can make
moves). With
,
,
the output has the same size as the input. A layer with
input channels and
filters has
parameters, independently of the image size. The receptive field (the input area influencing a neuron) grows by
pixels for every 3×3 layer and doubles with every pooling: stacking layers, deep neurons “see” the whole image.
Historical architectures show the evolution: LeNet (1998) read postcodes; AlexNet (2012) won the ImageNet competition by a huge margin using GPUs and ReLU, starting the deep learning era; ResNet (2015) added residual connections
, which let the gradient cross hundreds of layers without vanishing.
The experiment: dense network versus convolutional network
On scikit-learn’s 1797 8×8 handwritten digits (1347 for training, 450 for testing), two networks trained with Adam for 60 epochs:
- dense network: 64 inputs → 64 ReLU neurons → 10 outputs;
- CNN: two 3×3 convolutional layers (8 and 16 filters) with ReLU, a 2×2 max-pooling, a final dense layer.
| network | parameters | test accuracy | with the image shifted by 1 pixel |
|---|---|---|---|
| dense | 4,810 | 96.9 % | 42.9 % |
| convolutional | 3,818 | 98.2 % | 65.1 % |
The CNN is more accurate with fewer parameters, because the convolutional structure already tells it that neighbouring pixels must be looked at together. Shifting all test images one pixel to the right (a minimal change for a human eye), the dense network collapses to 43 %: it has learned “this pixel lit means 7”, not the shape. The CNN holds up better but still loses a lot, because on 8×8 images one pixel is more than 10 % of the width and pooling gives only a little invariance. In practice data augmentation is added: training also on shifted, rotated, scaled copies of the images.
import numpy as np, torch, torch.nn as nn
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
d = load_digits()
Xa, Xp, ya, yp = train_test_split(d.data / 16.0, d.target, test_size=0.25, random_state=0, stratify=d.target)
Xa, Xp = torch.tensor(Xa, dtype=torch.float32), torch.tensor(Xp, dtype=torch.float32)
ya, yp = torch.tensor(ya), torch.tensor(yp)
def train(model, epochs=60):
torch.manual_seed(0)
opt = torch.optim.Adam(model.parameters(), lr=1e-3)
for _ in range(epochs):
perm = torch.randperm(len(Xa))
for i in range(0, len(Xa), 64):
idx = perm[i:i + 64]
loss = nn.functional.cross_entropy(model(Xa[idx]), ya[idx])
opt.zero_grad(); loss.backward(); opt.step()
return model
def accuracy(model, X):
with torch.no_grad():
return float((model(X).argmax(1) == yp).float().mean())
torch.manual_seed(0)
dense = nn.Sequential(nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, 10))
torch.manual_seed(0)
cnn = nn.Sequential(nn.Unflatten(1, (1, 8, 8)), # from 64 values to a 1x8x8 image
nn.Conv2d(1, 8, 3, padding=1), nn.ReLU(), # 8 filters 3x3
nn.Conv2d(8, 16, 3, padding=1), nn.ReLU(), # 16 filters 3x3x8
nn.MaxPool2d(2), # 8x8 -> 4x4
nn.Flatten(), nn.Linear(16 * 4 * 4, 10))
train(dense); train(cnn)
shifted = torch.roll(Xp.view(-1, 8, 8), 1, dims=2) # all digits one pixel to the right
shifted[:, :, 0] = 0
shifted = shifted.view(-1, 64)
for name, m in (("dense", dense), ("convolutional", cnn)):
n = sum(p.numel() for p in m.parameters())
print(f"{name:15s}: {n} parameters, test {accuracy(m, Xp):.4f}, shifted {accuracy(m, shifted):.4f}")6Recurrent networks and transformers
Texts, audio signals, sensor time series, trajectories: many data are sequences, in which order matters and length varies. This lesson presents the two families of networks for sequences. Recurrent networks (RNNs) read one element at a time and carry a state with them; it is proved why their gradient vanishes on long sequences and how LSTMs avoid this. Transformers (2017) look at the whole sequence together with the attention mechanism; it is proved why the dot product must be divided by
. Transformers are today the basis of language models and are increasingly used for images and signals too.
Recurrent networks
An RNN updates a hidden state
at each element
of the sequence, with the same weights at every step:
![]()
It is a non-linear discrete-time dynamical system, like those of Systems Theory, with learned parameters. To train it the network is “unrolled” in time (one copy per step) and backpropagation is applied: this is backpropagation through time (BPTT).
Theorem (vanishing or exploding gradient).
, so
.
Proof. By the chain rule
, and differentiating
with
gives
. The norm of a product is at most the product of the norms, and
. ∎
If
the gradient decreases exponentially with distance: the network cannot learn that an input far in the past determines today’s output. If it is greater than 1 it can explode (it is limited by clipping the gradient norm, as in PPO).
The LSTM
The LSTM (long short-term memory, Hochreiter and Schmidhuber, 1997) adds a memory cell
controlled by three gates (values between 0 and 1 given by sigmoids):
![]()
The forget gate
decides how much of the memory to keep, the input gate
how much to write into it, the output gate
how much of it to show. The key point is that the cell is updated by addition:
, with no multiplications by
or derivatives of saturating functions. If the network learns
, the gradient crosses many steps almost intact. The GRU (2014) is a simpler variant with two gates.
The measurement. For freshly initialised networks (32-neuron state, average over 10 initialisations) automatic differentiation computes how much the output at the last step depends on the first input:
| length | RNN | LSTM |
|---|---|---|
| 1 | ||
| 10 | ||
| 20 | ||
| 50 | ||
| 100 |

In the RNN the signal shrinks by a factor of about 0.6 at each step (the straight line on a logarithmic scale); after 100 steps it is
times weaker than in the LSTM.
Attention
Even the LSTM struggles beyond a few hundred steps, and above all it works sequentially: step
waits for step
, and it cannot be parallelised on the GPU. Attention directly connects every position with all the others. Each element produces three vectors: a query
, a key
and a value
, with learned weight matrices. The output for a position is an average of the values of all positions, weighted by how much its query “resembles” each key:
![]()
where the rows of
are the queries, keys and values of the
positions, and
is the key dimension.
Theorem (why divide by
). If the components of
and
are independent with mean 0 and variance 1, the dot product
has mean 0 and variance
.
Proof.
. Each term has mean
and variance
; the terms are independent, so the variances add:
. ∎
With
the scores would have a standard deviation of about 23: the softmax of such large numbers is almost “one only, all the others zero”, and its gradient is almost zero. Dividing by
brings the variance back to 1. In simulation (code at the end): variance 4.0, 64.0 and 509 for
, and 1.00, 1.00, 0.99 after the division.

The transformer
The transformer (Vaswani et al., 2017, “Attention is all you need”) stacks identical blocks, each with:
- multi-head attention: several attentions in parallel, with different matrices, which can specialise (one follows syntax, another references);
- a small dense network applied to each position separately;
- residual connections and normalisation (layer norm) around both, as in ResNets.
Attention knows nothing about order (permuting the positions permutes the outputs in the same way), so a positional encoding is added to the inputs: in the original work sinusoids of different frequencies, today often rotations (RoPE). The cost of attention grows as
with the sequence length
, and it is the main limit of long-context models. In exchange all positions are computed in parallel, and this, more than anything else, is what made it possible to train models with hundreds of billions of parameters. To generate text a causal mask is used: each position can only look at the previous ones, and the model learns to predict the next word.
The code
import numpy as np
import torch, torch.nn as nn
# 1) attention in NumPy
def attention(Q, K, V):
scores = Q @ K.T / np.sqrt(K.shape[1])
weights = np.exp(scores - scores.max(1, keepdims=True))
weights /= weights.sum(1, keepdims=True) # row-wise softmax
return weights @ V, weights
g = np.random.default_rng(0)
X = g.normal(0, 1, (6, 16)) # 6 positions, 16 dimensions
Wq, Wk, Wv = (g.normal(0, 0.25, (16, 8)) for _ in range(3))
output, weights = attention(X @ Wq, X @ Wk, X @ Wv)
print("output", output.shape, "- the weight rows sum to", np.round(weights.sum(1), 6))
# 2) variance of the dot product before and after dividing by sqrt(d_k)
for dk in (4, 64, 512):
q, k = g.normal(0, 1, (20000, dk)), g.normal(0, 1, (20000, dk))
s = (q * k).sum(1)
print(f"d_k = {dk:3d}: variance {s.var():6.1f}, after division {(s / np.sqrt(dk)).var():.3f}")
# 3) sensitivity of the last output to the first input, freshly initialised RNN versus LSTM
def sensitivity(kind, T, H=32, inits=10):
values = []
for s in range(inits):
torch.manual_seed(s)
net = (nn.RNN if kind == "rnn" else nn.LSTM)(1, H, batch_first=True)
if kind == "lstm": # forget gate initially open (bias 1)
for name, p in net.named_parameters():
if "bias_ih" in name:
p.data[H:2 * H] = 1.0
x = torch.randn(1, T, 1, requires_grad=True)
outputs, _ = net(x)
outputs[0, -1].sum().backward()
values.append(x.grad[0, 0].abs().item())
return sum(values) / len(values)
for T in (1, 10, 20, 50, 100):
print(f"T = {T:3d}: RNN {sensitivity('rnn', T):.1e}, LSTM {sensitivity('lstm', T):.1e}")7Training in practice
Between the theory of the previous lessons and a network that really works there are many practical choices: how to split the data, how to initialise the weights, how to normalise, how to avoid overfitting, how to measure the result. This lesson presents them with their mathematical reasons and with measured experiments, including those that do not confirm expectations: in network training many “tricks” work on some problems and not on others, and the only way to know is to measure.
Splitting the data
The data are split into three parts: training (for the weights), validation (for the choices: network size, step size, regularisation, when to stop) and test, used only once at the end to estimate performance on new data. If choices are made by looking at the test set, the test becomes a second validation and the estimate is optimistic. With little data cross-validation is used: the set is split into
parts, training is done
times leaving out a different one, and the results are averaged. Two practical warnings: the split must be done before any normalisation (mean and variance are computed on the training set only), and for data in time (sensor series) the test must come after the training data, not mixed in.
Weight initialisation
If the initial weights are too small the activations (and gradients) fade out layer after layer; if they are too large they explode. The right initialisation keeps the variance constant.
Theorem (He initialisation, 2015). In a network with ReLU activations, independent zero-mean weights and
inputs per neuron, the variance of the weighted sums stays constant from one layer to the next if
.
Proof. For a neuron
with
independent of
and zero mean,
. With
and
symmetric about zero, ReLU lets half of the distribution through:
. So
, which stays the same if
. ∎
For symmetric activations such as tanh the factor 1/2 is absent and one gets
(Xavier or Glorot, 2010). Experiment: 20 layers of 256 ReLU neurons, standard deviation of the activations:
| weights | after 1 layer | after 5 | after 10 | after 20 |
|---|---|---|---|---|
| 0.094 | ||||
| 9.35 | ||||
| Xavier, | 0.58 | 0.15 | 0.028 | 0.00067 |
| He, | 0.83 | 0.86 | 0.80 | 0.76 |
With ReLU only He initialisation preserves the signal; Xavier’s halves it (in variance) at each layer, exactly the factor 1/2 of the proof.

Normalisation
Batch normalisation (2015) normalises the weighted sums of each neuron over the mini-batch (mean 0, variance 1) and then rescales them with two learned parameters. It makes training much less sensitive to initialisation and step size, and allows larger steps. In transformers layer normalisation is used, which normalises over the components of a single example instead of over the batch, and works even with small batches and sequences of variable length. The inputs too must be normalised: variables with very different scales (a temperature in kelvin and a voltage in millivolts) worsen the conditioning (lesson 1).
Against overfitting
- More data: the most effective remedy of all, as the experiment below shows.
- Data augmentation: new copies of the examples transformed in ways that do not change the answer (shifts, rotations, noise, lighting changes).
- Weight decay: the penalty
of lesson 1. - Dropout (Srivastava et al., 2014): during training each neuron is switched off at random with probability
, and the remaining ones are multiplied by
. In this way the expected value of each output is the same with and without dropout:
, and in use the whole network is used without corrections. The idea is to prevent neurons from “leaning” on each other. - Early stopping: the validation error is monitored during training and training stops when it starts to rise.
The experiments. Dense network 64 → 1024 → 1024 → 10 on the 8×8 digits, trained for 300 steps on subsets of increasing size, accuracy on the 450 test digits (average over 3 seeds):
| training examples | 50 | 100 | 200 | 400 | 1347 |
|---|---|---|---|---|---|
| test accuracy | 76.4 % | 89.5 % | 91.9 % | 95.5 % | 97.0 % |
Dropout (p = 0.5), on the same network with 100 examples, gave 89.5 % against 89.1 % without (average over 5 seeds): no measurable difference; with 50 examples 77.8 % against 77.9 %. Weight decay with
made it slightly worse (86.0 %). On this problem, small and already easy, regularisation matters little and the amount of data matters a lot. On very large networks and harder problems (ImageNet images, language models) dropout and weight decay instead give measurable benefits. The moral is the lesson’s: techniques must be tried on your own problem, with honest validation.
Metrics
Accuracy (fraction of right answers) is misleading when classes are unbalanced: if a fault happens in 1 % of cases, a classifier that always says “no fault” has 99 % accuracy and is useless. For a “positive” class, with TP, FP, FN the true positives, false positives and false negatives:
![]()
Precision says how many of the alarms are true, recall how many of the true cases are found. Moving the decision threshold trades one for the other; which matters more depends on the application (in an emergency braking system a false negative is much more serious than a false positive, in a spam filter the opposite). The confusion matrix, used in the last lesson, shows all errors class by class.
Choosing hyperparameters
Step size, sizes, regularisation, batch size are hyperparameters: they are not learned by the gradient, they are chosen by comparing results on the validation set. Random search (Bergstra and Bengio, 2012) is usually better than grid search: if only a few hyperparameters really matter, trying random values explores many more different values of the important ones. The step size is searched on a logarithmic scale (
,
,
, …).
import numpy as np, torch, torch.nn as nn
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
# 1) initialisation: standard deviation of the activations through 20 ReLU layers
g = np.random.default_rng(0)
h0 = g.normal(0, 1, (1000, 256))
for name, std in (("N(0, 0.01^2)", lambda n: 0.01), ("N(0, 1)", lambda n: 1.0),
("Xavier 1/n", lambda n: np.sqrt(1 / n)), ("He 2/n", lambda n: np.sqrt(2 / n))):
h, values = h0.copy(), []
for layer in range(20):
h = np.maximum(h @ g.normal(0, std(256), (256, 256)), 0)
values.append(h.std())
print(f"{name:13s}: after 1, 5, 10, 20 layers {values[0]:.3g}, {values[4]:.3g}, {values[9]:.3g}, {values[19]:.3g}")
# 2) amount of data: the same network trained on larger and larger subsets
d = load_digits()
Xa, Xp, ya, yp = train_test_split(d.data / 16.0, d.target, test_size=0.25, random_state=0, stratify=d.target)
Xa, Xp = torch.tensor(Xa, dtype=torch.float32), torch.tensor(Xp, dtype=torch.float32)
ya, yp = torch.tensor(ya), torch.tensor(yp)
def trial(n, seed, dropout=0.0):
torch.manual_seed(seed)
layers = [nn.Linear(64, 1024), nn.ReLU()] + ([nn.Dropout(dropout)] if dropout else []) \
+ [nn.Linear(1024, 1024), nn.ReLU()] + ([nn.Dropout(dropout)] if dropout else []) + [nn.Linear(1024, 10)]
net = nn.Sequential(*layers)
opt = torch.optim.Adam(net.parameters(), lr=1e-3)
idx = torch.randperm(len(Xa), generator=torch.Generator().manual_seed(seed))[:n]
for _ in range(300): # 300 steps on the whole subset
net.train()
loss = nn.functional.cross_entropy(net(Xa[idx]), ya[idx])
opt.zero_grad(); loss.backward(); opt.step()
net.eval() # dropout is off in use
with torch.no_grad():
return float((net(Xp).argmax(1) == yp).float().mean())
for n in (50, 100, 200, 400, 1347):
print(f"{n:4d} examples: test accuracy {np.mean([trial(n, s) for s in range(3)]):.3f}")8Project: NumPy, PyTorch, ONNX
This lesson puts the whole course together in a complete, working project: recognising handwritten digits. The network is first written from scratch in NumPy, with the backpropagation of lesson 3, then the same network in PyTorch, where the gradients are computed by automatic differentiation; the result is evaluated with the confusion matrix and the errors are examined; finally the model is prepared for use outside Python (ONNX format) and for a microcontroller, with 8-bit weight quantisation. All the numbers reported come from running the code at the bottom of the page.
The data
The scikit-learn collection contains 1797 digits handwritten by 43 people, reduced to 8×8 pixel images with 17 grey levels (from 0 to 16): small enough to train a network in a second on a laptop, but a real problem, with different handwriting. The values are divided by 16 (inputs between 0 and 1, lesson 7) and the data are split into 1347 training examples and 450 test examples, stratified (each digit in the same proportion in the two sets) and with a fixed seed, so that the result is reproducible.

The network in NumPy
Architecture 64 → 64 → 10: 64 inputs (the pixels), one hidden layer of 64 ReLU neurons, 10 outputs with softmax. Weights initialised with He’s rule (lesson 7), cross-entropy, stochastic gradient descent with batches of 32 examples and step 0.1 for 100 epochs. The training loop is the direct translation of the backpropagation equations:
, last-layer gradients
,
, first-layer gradients
. Result: 98.0 % test accuracy, in 0.3-0.4 seconds.
The same network in PyTorch
In PyTorch the network is declared as a sequence of layers, and the gradient is computed by loss.backward(). With the same architecture, the same optimiser and the same hyperparameters one gets 97.8 %: the small difference (one example out of 450) comes from the different random initialisation (PyTorch uses a scaled uniform distribution by default) and from the batch order. For such a small network PyTorch is even slower than NumPy (1.6 s): the real advantage comes with large networks, on the GPU, and with complicated architectures whose derivatives nobody would want to write by hand.
The confusion matrix
Rows: true digit; columns: digit predicted by the PyTorch network. On the diagonal the right answers:
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | |
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 45 | |||||||||
| 1 | 45 | 1 | ||||||||
| 2 | 1 | 43 | ||||||||
| 3 | 46 | |||||||||
| 4 | 1 | 43 | 1 | |||||||
| 5 | 1 | 1 | 44 | |||||||
| 6 | 1 | 44 | ||||||||
| 7 | 45 | |||||||||
| 8 | 2 | 41 | ||||||||
| 9 | 1 | 44 |

Ten errors out of 450, and half end up in the column of 1: at 8×8 pixels a slightly thick vertical stroke is enough to make an 8, a 4 or a 6 look like a 1. Looking at where a model goes wrong is the most useful step to improve it: here it would suggest higher-resolution images, a CNN (lesson 5), or more examples of the confused pairs.
From model to product
- Saving:
torch.savesaves the weights; to reload them the same network code is needed. - ONNX (Open Neural Network Exchange):
torch.onnx.exportsaves network and weights in a standard format, which runs with ONNX Runtime in C++, C#, Java or JavaScript, on servers, phones or in the browser, without Python. - Microcontrollers: a network can also run on a microcontroller with a few hundred kilobytes of memory (TensorFlow Lite for Microcontrollers, or C code generated by tools such as STM32Cube.AI). The decisive step is quantisation: weights become 8-bit integers,
with
between −127 and 127 and one scale
per matrix. Weight memory shrinks fourfold and computations become integer operations, much faster and cheaper in energy. On the digit network weight memory drops from 18,944 to 4,736 bytes and accuracy does not change (97.8 %). On larger networks the loss is usually a few tenths of a point; when it is too much, the network is trained taking quantisation into account (quantisation-aware training).
The complete code
import time
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
# data: 1797 handwritten digits, 8x8 pixels with values 0..16
d = load_digits()
Xtr, Xte, ytr, yte = train_test_split(d.data / 16.0, d.target, test_size=0.25, random_state=0, stratify=d.target)
# ---------------- network from scratch in NumPy: 64 -> 64 (ReLU) -> 10 (softmax) ----------------
rng = np.random.default_rng(0)
W1 = rng.normal(0, np.sqrt(2 / 64), (64, 64)); b1 = np.zeros(64) # He initialisation
W2 = rng.normal(0, np.sqrt(2 / 64), (64, 10)); b2 = np.zeros(10)
def forward(X):
z1 = X @ W1 + b1
h = np.maximum(z1, 0)
z2 = h @ W2 + b2
p = np.exp(z2 - z2.max(1, keepdims=True))
return h, p / p.sum(1, keepdims=True)
t0 = time.time()
LR, EPOCHS, BATCH = 0.1, 100, 32
for epoch in range(EPOCHS):
perm = rng.permutation(len(Xtr))
for i in range(0, len(Xtr), BATCH):
idx = perm[i:i + BATCH]
X, y = Xtr[idx], ytr[idx]
h, p = forward(X)
d2 = p.copy(); d2[np.arange(len(y)), y] -= 1; d2 /= len(y) # gradient of softmax + cross-entropy
gW2, gb2 = h.T @ d2, d2.sum(0)
d1 = (d2 @ W2.T) * (h > 0) # backpropagation through the ReLU
gW1, gb1 = X.T @ d1, d1.sum(0)
W1 -= LR * gW1; b1 -= LR * gb1; W2 -= LR * gW2; b2 -= LR * gb2
acc_np = (forward(Xte)[1].argmax(1) == yte).mean()
print(f"NumPy: test accuracy {acc_np:.4f} in {time.time() - t0:.1f} s")
# ---------------- the same network in PyTorch ----------------
import torch
import torch.nn as nn
torch.manual_seed(0)
model = nn.Sequential(nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, 10))
opt = torch.optim.SGD(model.parameters(), lr=LR)
Xt, yt = torch.tensor(Xtr, dtype=torch.float32), torch.tensor(ytr)
t0 = time.time()
for epoch in range(EPOCHS):
perm = torch.randperm(len(Xt))
for i in range(0, len(Xt), BATCH):
idx = perm[i:i + BATCH]
loss = nn.functional.cross_entropy(model(Xt[idx]), yt[idx]) # autograd computes the gradient
opt.zero_grad(); loss.backward(); opt.step()
with torch.no_grad():
pred = model(torch.tensor(Xte, dtype=torch.float32)).argmax(1).numpy()
print(f"PyTorch: test accuracy {(pred == yte).mean():.4f} in {time.time() - t0:.1f} s")
# confusion matrix: rows = true digit, columns = predicted digit
conf = np.zeros((10, 10), int)
for t, q in zip(yte, pred):
conf[t, q] += 1
print(conf)
# 8-bit weight quantisation (symmetric, one scale per matrix), as on microcontrollers
qmodel = nn.Sequential(nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, 10))
qmodel.load_state_dict(model.state_dict())
with torch.no_grad():
for layer in (qmodel[0], qmodel[2]):
scale = layer.weight.abs().max() / 127 # the largest weight becomes 127
q = torch.round(layer.weight / scale).clamp(-127, 127) # integers from -127 to 127
layer.weight.copy_(q * scale) # values the network actually sees
qpred = qmodel(torch.tensor(Xte, dtype=torch.float32)).argmax(1).numpy()
print(f"8-bit weights: test accuracy {(qpred == yte).mean():.4f}, weight memory {sum(p.numel() for p in model.parameters() if p.dim() == 2)} bytes instead of {4 * sum(p.numel() for p in model.parameters() if p.dim() == 2)}")
torch.save(model.state_dict(), "digits.pt")
torch.onnx.export(model, torch.zeros(1, 64), "digits.onnx") # to use it outside PythonWhat comes next
The course has built all the pieces: gradient descent, multilayer networks, backpropagation, optimisers, convolutions, sequences and attention, training practice. The same ideas, scaled up by many orders of magnitude, are those of vision models and language models. The reinforcement learning course shows how networks learn to decide instead of recognise, with an environment in place of labelled data.
∑Formula sheet
Regression and gradient descent
The supervised learning problem
![Rendered by QuickLaTeX.com \[ J(\mathbf w) = \frac{1}{n}\sum_{i=1}^n\ell\big(f_{\mathbf w}(\mathbf x_i),\ y_i\big) \]](https://www.electronics-engineering.com/wp-content/ql-cache/quicklatex.com-32be25159b3745567926c0e846e04f93_l3.png)
Linear regression and the normal equations
![]()
Gradient descent
![]()
Perceptron and multilayer networks
The perceptron
![]()
Multilayer networks
![]()
Optimisers
Stochastic gradient descent
![Rendered by QuickLaTeX.com \[ \mathbf g_k = \frac{1}{|B|}\sum_{i\in B}\nabla\ell_i(\mathbf w_k),\qquad \mathbf w_{k+1} = \mathbf w_k - \eta\,\mathbf g_k \]](https://www.electronics-engineering.com/wp-content/ql-cache/quicklatex.com-4d362c725b113ecb648d4d3d149b9930_l3.png)
Momentum
![]()
RMSProp and Adam: one step size per parameter
![]()
![]()
Convolutional networks
Convolution
![]()
Sizes
![]()
Recurrent networks and transformers
Recurrent networks
![]()
The LSTM
![]()
Attention
![]()
Training in practice
Metrics
![]()