Math for Machine Learning
The essential maths behind ML — vectors, matrices and matrix multiplication, dot products and similarity, derivatives, gradients and the chain rule, probability distributions, Bayes' theorem, expectation and variance, and maximum likelihood — with NumPy examples.
You can train models without deep maths, but understanding why they work — and debugging them when they don't — needs three areas: linear algebra (how data and models are represented), calculus (how models learn) and probability (how we reason about uncertainty).
Linear algebra
Vectors
A vector is an ordered list of numbers — a point or direction in space. In ML, each example is a feature vector; each word in an LLM is an embedding vector with hundreds or thousands of dimensions.
The dot product multiplies matching entries and sums them:
It's everywhere: a linear model's prediction is a dot product of weights and features; attention scores in transformers are dot products (Attention). Cosine similarity — the dot product of normalised vectors — measures how aligned two vectors are, the basis of semantic search (Embeddings and RAG).
Norms measure length: L2 (Euclidean) and L1 — also used as regularisation penalties.
Matrices
A matrix is a 2-D grid of numbers. A dataset of n examples with d features is an n × d matrix X. A neural network layer is a matrix W transforming input vectors:
Matrix multiplication (A is m×k, B is k×n → C is m×n) computes every dot product of A's rows with B's columns. It's the operation GPUs are built to do fast (GPUs and accelerators).
import numpy as np
X = np.array([[120, 3, 15], # 4 houses × 3 features
[80, 2, 30],
[200, 4, 5],
[95, 2, 20]], dtype=float)
w = np.array([0.5, 10.0, -0.3]) # weights
b = 20.0
predictions = X @ w + b # all 4 predictions in one matrix-vector product
print(predictions) # [105.5 51. 140.5 61.5]
# Cosine similarity
a, c = np.array([1, 2, 3]), np.array([2, 4, 6.5])
print(a @ c / (np.linalg.norm(a) * np.linalg.norm(c))) # ≈ 0.9998 — nearly the same directionOther useful ideas: the transpose ; the identity and inverse; eigenvectors (directions a matrix only stretches — the basis of PCA); and tensors, which generalise matrices to more dimensions (a batch of RGB images is a 4-D tensor: batch × height × width × channels).
Calculus
Derivatives and gradients
A derivative measures how a function's output changes as its input changes — the slope. For , : at , increasing w slightly increases f about 6 times as much.
With many parameters, the gradient collects all partial derivatives into a vector:
It points in the direction of steepest increase of the loss L. Training moves the weights in the opposite direction — gradient descent:
The chain rule
Neural networks are compositions of functions. The chain rule gives the derivative of a composition:
Applied systematically backwards through a network, layer by layer, this is backpropagation (Backpropagation) — the algorithm that computes gradients for millions or billions of weights efficiently.
| Function | Derivative |
|---|---|
| sigmoid | |
| ReLU | 1 if x > 0, else 0 |
Probability and statistics
ML models handle uncertainty: a classifier outputs probabilities; an LLM samples the next token from a probability distribution.
Distributions
| Distribution | Models | Example |
|---|---|---|
| Bernoulli | One yes/no trial with probability p | Will this user click? |
| Categorical | One of K outcomes | Next token among 100k vocabulary entries |
| Gaussian (normal) | Continuous values clustering around a mean μ with spread σ | Measurement noise, heights |
| Uniform | All values equally likely | Random initialisation |
Expectation (mean) is the average outcome; variance measures spread; the standard deviation σ is its square root.
Conditional probability and Bayes' theorem
Example: a disease affects 1% of people; a test is 95% sensitive and has a 5% false-positive rate. If you test positive:
The low prior dominates — a lesson for interpreting any classifier on rare events (fraud, disease). Naive Bayes classifiers apply this theorem directly. See Probability for more.
Maximum likelihood and loss functions
Most training objectives come from maximum likelihood estimation: choose parameters that make the observed data most probable. Taking the negative log turns this into a loss to minimise:
- Assuming Gaussian noise on regression targets → mean squared error.
- For classification with predicted probabilities → cross-entropy loss:
which heavily penalises confident wrong predictions. LLMs are trained by minimising cross-entropy on the next token.
Statistics you'll use
- Mean, median, standard deviation, percentiles to understand features.
- Correlation — not causation.
- Sampling, confidence intervals and significance tests for comparing models and A/B tests.
- Normalisation: rescale features to mean 0 and standard deviation 1 (z-scores) so no feature dominates by scale.
- Data are vectors and matrices; predictions are dot products and matrix multiplications; GPUs accelerate exactly this.
- Cosine similarity of embedding vectors measures semantic similarity.
- The gradient points uphill on the loss; gradient descent steps the other way.
- The chain rule, applied backwards through layers, is backpropagation.
- Probability distributions model uncertainty; Bayes' theorem updates beliefs — mind the base rate.
- Maximum likelihood gives the standard losses: MSE for regression, cross-entropy for classification.