Mathematics and Python for AI
Learning objectives
- Work with vectors, matrices and tensor shapes in NumPy
- Understand derivatives, gradients and the chain rule as used in training
- Implement softmax, cross-entropy and gradient descent from scratch
- Read model code fluently: broadcasting, batching, dtypes
Introduction
Every AI model, from a small classifier to a large language model, is built from a handful of mathematical operations: vectors and matrices to represent data and parameters, derivatives to know how to improve them, and probabilities to express predictions. This chapter teaches exactly the mathematics you need to read and write model code – with NumPy, so every formula becomes a few lines you can run and inspect.
Without the maths, model code is a black box: you cannot tell why a shape mismatch occurs, why training diverges or why a softmax returns NaN. With it, the core of deep learning turns out to be surprisingly small – matrix multiplications, a few non-linear functions and gradient descent. Frameworks like PyTorch automate the derivatives, but they do not choose shapes, losses or learning rates for you.
Vectors, dot products and similarity
A vector is an ordered list of numbers. In AI, almost everything becomes a vector: a pixel image, a customer profile, or a word's embedding with hundreds of dimensions.
The dot product a · b multiplies matching components and sums them. Geometrically it is |a| · |b| · cos(θ): large when vectors point in the same direction. Dividing by both lengths gives the cosine similarity, between −1 and 1 – the standard measure for comparing embeddings (chapter 9).
A neuron computes a dot product of its inputs with its weights plus a bias. Attention (chapter 4) compares a query vector with key vectors – again via dot products.
Matrices, shapes and batches
A matrix multiplication X @ W with X of shape (batch, in) and W of shape (in, out) gives (batch, out): every row of X is mapped by the same layer. This is how a dense neural-network layer processes a whole batch at once.
The inner dimensions must match: (4, 3) @ (3, 2) works, (4, 3) @ (2, 3) does not. Most bugs in model code are shape bugs – write the expected shape next to every tensor operation.
Tensors generalise matrices to more dimensions. A batch of token embeddings in a transformer has shape (batch, sequence, model_dim); attention scores have shape (batch, heads, sequence, sequence).
Broadcasting lets NumPy and PyTorch combine arrays of different shapes by virtually repeating size-1 dimensions: adding a bias of shape (out,) to a result of shape (batch, out) adds it to every row.
Derivatives, gradients and the chain rule
The derivative of a function tells how much its output changes when the input changes a little. For a function of many parameters, the gradient is the vector of all partial derivatives: it points in the direction of steepest increase.
Training minimises a loss L(θ) over parameters θ. Gradient descent repeats θ ← θ − η · ∇L(θ), where η is the learning rate. Too small and training crawls; too large and it overshoots and diverges.
A neural network is a composition of functions: f(g(h(x))). The chain rule multiplies the local derivatives along this chain. Backpropagation (chapter 3) is the chain rule applied systematically from the loss back to every parameter.
For the mean squared error L = mean((w·x + c − y)²), the gradients are ∂L/∂w = 2·mean((w·x + c − y)·x) and ∂L/∂c = 2·mean(w·x + c − y). The code below uses exactly these formulas.
Probabilities, softmax and cross-entropy
Classifiers and language models output logits: arbitrary real numbers, one per class or per vocabulary token. Softmax turns them into probabilities: exp(zᵢ) / Σ exp(zⱼ). All results are positive and sum to 1.
exp overflows for large logits. Subtracting the maximum logit before exponentiating does not change the result (it cancels in the fraction) but keeps the numbers small – the numerically stable softmax.
Cross-entropy measures how much probability the model gives to the correct class: −log p(correct). It is 0 for a perfect, confident prediction and grows without bound for confident mistakes. Language models are trained with cross-entropy on the next token.
Frameworks combine softmax and cross-entropy in one function (log-softmax via the log-sum-exp trick) because computing them separately loses precision.
Python and NumPy for model code
Vectorise: operate on whole arrays instead of Python loops. NumPy executes the loop in optimised C; the difference is often a factor of 100 or more.
Watch dtypes: float32 is the default for training (and halves memory compared with float64); integer arrays silently truncate.
Make randomness reproducible with a seeded generator (np.random.default_rng(seed)) – essential for comparing experiments.
Keep a virtual environment per project (python -m venv) and pin versions: AI libraries change quickly.
Key terminology
- Tensor
- A multi-dimensional array; scalars, vectors and matrices are tensors of rank 0, 1 and 2.
- Shape
- The size of each dimension of a tensor, e.g. (batch, sequence, features).
- Broadcasting
- Automatic expansion of size-1 dimensions so arrays of different shapes can be combined element-wise.
- Gradient
- Vector of partial derivatives of a function with respect to its parameters; points towards steepest increase.
- Learning rate
- Step size of gradient descent; one of the most important training hyperparameters.
- Logits
- Unnormalised scores output by a model before softmax.
- Softmax
- Function turning logits into a probability distribution.
- Cross-entropy
- Loss −log p(correct class); the standard loss for classification and language modelling.
Architecture diagrams
One step of gradient descent
flowchart LR P[Parameters w, c] --> F[Forward: prediction = w·x + c] F --> L[Loss: mean squared error] L --> G[Gradient: dL/dw, dL/dc] G --> U[Update: w = w - lr·dL/dw] U --> P
From logits to a training signal
flowchart LR Z[Logits 2.0, 1.0, 0.1] --> M[Subtract max] M --> E[exp] E --> N[Normalise: divide by sum] N --> P[Probabilities 0.659, 0.242, 0.099] P --> CE[Cross-entropy: -log p of the correct class]
Practical examples
Embedding similarity. A search system turns the query and every document into vectors and ranks documents by cosine similarity – the operation in the first lines of the code below.
Shapes in a language model. A batch of 8 sequences with 512 tokens and a model dimension of 768 is a tensor of shape (8, 512, 768); the output layer maps it to (8, 512, vocabulary_size) logits.
Working code
The maths of model training in NumPy
Tested with: Python 3.13, NumPy 2.5
# pip install numpy
# python ch2_numpy_math.py
"""Chapter 2 – the maths behind every model, in NumPy."""
import numpy as np
rng = np.random.default_rng(0)
# Vectors and similarity: the basis of embeddings and attention.
a, b = np.array([1.0, 2.0, 3.0]), np.array([2.0, 0.5, 1.0])
cosine = a @ b / (np.linalg.norm(a) * np.linalg.norm(b))
print("dot:", a @ b, "cosine:", round(float(cosine), 4))
# Matrix multiplication: a layer maps (batch, in) -> (batch, out).
x = rng.normal(size=(4, 3)) # 4 examples, 3 features
W = rng.normal(size=(3, 2)) # weights of a layer with 2 outputs
print("layer output shape:", (x @ W).shape)
def softmax(z):
z = z - z.max(axis=-1, keepdims=True) # numerically stable
e = np.exp(z)
return e / e.sum(axis=-1, keepdims=True)
logits = np.array([2.0, 1.0, 0.1])
p = softmax(logits)
print("softmax:", p.round(3), "sum:", p.sum().round(6))
print("cross-entropy for true class 0:", round(float(-np.log(p[0])), 4))
# Gradient descent: recover y = 3x + 2 from noisy data.
X = rng.uniform(-1, 1, size=200)
Y = 3 * X + 2 + rng.normal(scale=0.1, size=200)
w, c, lr = 0.0, 0.0, 0.1
for step in range(500):
pred = w * X + c
grad_w = 2 * np.mean((pred - Y) * X) # d(MSE)/dw
grad_c = 2 * np.mean(pred - Y) # d(MSE)/dc
w, c = w - lr * grad_w, c - lr * grad_c
print("learned w, c:", round(w, 2), round(c, 2))
dot: 6.0 cosine: 0.6999 layer output shape: (4, 2) softmax: [0.659 0.242 0.099] sum: 1.0 cross-entropy for true class 0: 0.417 learned w, c: 3.0 1.99
Gradient descent recovers the true parameters (3 and 2) from 200 noisy points using only the two gradient formulas – the same principle trains networks with billions of parameters.
Practice Lab
These exercises train the three skills you will use most: shapes, numerical stability and the learning rate.
A dense layer with bias
BeginnerCreate a bias vector of shape (2,) and add it to x @ W. Print the shape and check that the bias was added to every row.
- Broadcasting repeats the bias for each of the 4 rows.
Show solution
bias = np.array([0.5, -1.0])
out = x @ W + bias # (4, 2) + (2,) -> (4, 2)
print(out.shape, np.allclose(out - x @ W, bias)) # (4, 2) True
Why the stable softmax matters
IntermediateCompute softmax for the logits [1000.0, 999.0] with a naive implementation (no max subtraction) and with the stable one. Explain the difference.
- np.exp(1000) overflows float64.
Show solution
z = np.array([1000.0, 999.0])
naive = np.exp(z) / np.exp(z).sum() # overflow: inf / inf = nan (with a RuntimeWarning)
print(naive) # [nan nan]
print(softmax(z).round(4)) # [0.7311 0.2689]
Find the learning-rate cliff
AdvancedRun the gradient descent with learning rates 0.01, 0.1, 0.5, 1.0 and 1.5 for 500 steps. Which converge, which diverge, and why?
- Gradient descent is stable only while the learning rate stays below 2 divided by the largest curvature of the loss.
Show solution
for lr in (0.01, 0.1, 0.5, 1.0, 1.5):
w = c = 0.0
for _ in range(500):
pred = w * X + c
w -= lr * 2 * np.mean((pred - Y) * X)
c -= lr * 2 * np.mean(pred - Y)
print(lr, round(w, 2), round(c, 2))
# 0.01 is still slightly off after 500 steps (w≈2.92), 0.1 and 0.5 find w≈3, c≈2,
# 1.0 and 1.5 diverge. The largest curvature (eigenvalue of the Hessian) of this loss
# is about 2.01 for this data, so stable steps need lr < 2 / 2.01 ≈ 0.99.
Practise with OOHM
Reinforce the chapter's vocabulary and concepts with dictation, rapid typing and quizzes on this topic.
Please log in to use this AI feature.
Knowledge check
Common mistakes and troubleshooting
Summary
- Vectors and dot products measure similarity; matrix multiplication is the core of every layer.
- Gradient descent follows the negative gradient; the learning rate controls the step.
- Softmax turns logits into probabilities; cross-entropy turns them into a loss.
- Shapes, numerical stability and reproducibility are the everyday engineering skills.
Learning outcomes
- You can predict tensor shapes and fix shape errors.
- You can implement and debug the core training maths without a framework.