Math essentials for ML
The four math tools behind every model: vectors and the dot product, matrices and tensors, derivatives and gradients, and probability — with an interactive vector playground.
You do not need a maths degree to understand modern AI, but four tools appear everywhere: vectors and matrices (how data and weights are stored and combined), derivatives and gradients (how models learn), and probability (how models express uncertainty). This lesson builds intuition for each, with just enough notation to read the formulas in later lessons[1][2].
Vectors
A [[vector]] is an ordered list of n numbers. Each input example in ML is a feature vector x, each word in an LLM becomes an Embedding vector, and a layer's weights for one neuron form a weight vector w. The length (Euclidean norm) of a vector measures its size, and the distance between two vectors is the length of their difference.
- a
- a Vector (bold or plain a): e.g. one example's features or a word Embedding
- [a₁, a₂, …, aₙ]
- the components in order; square brackets mean “a list”
- a₁
- the 1st component (the subscript is the position, not a power)
- aₙ
- the last component; n = dimension (2 for a point on paper, 768+ for embeddings)
- |a|
- the length (Euclidean norm) of a, also written ‖a‖. Always ≥ 0
- √
- square root
- a₁²
- the 1st component squared (times itself), so negative components count positively
- dist(a, b)
- Euclidean distance between a and b (straight-line distance)
- |a − b|
- length of the difference vector: subtract component by component, then take the length
- b
- a second vector with the same n
▸Worked example
The dot product — the most important operation in ML
The [[dot-product|dot product]] multiplies two vectors element by element and adds the results. Geometrically it equals the product of their lengths times the cosine of the angle between them, so it measures how much two vectors point the same way. A neuron computes exactly this: w·x + b. Example: a = [2, 1], b = [1, 3] → a·b = 2·1 + 1·3 = 5.
- a·b
- the Dot product of vectors a and b: a single number, not a vector
- Σᵢ
- sigma — “sum over i”: add the term for i = 1, 2, …, n
- aᵢbᵢ
- the i-th component of a times the i-th component of b
- |a|
- length of a: √(a₁² + … + aₙ²)
- |b|
- length of b
- cos
- cosine: turns an angle into a number from −1 to 1 (cos 0° = 1, cos 90° = 0, cos 180° = −1)
- θ
- theta — here the angle between the two vectors (not the model parameters)
- /
- division: removes the effect of the lengths, so long and short vectors are compared fairly
▸Worked example
Cosine similarity is how search engines and RAG systems compare text embeddings: two sentences with similar meaning have embedding vectors pointing in similar directions. The projection of a onto b, (a·b)/|b|, tells you how far a reaches along b's direction.
- Add mode: move a and b and watch a + b form the diagonal of a parallelogram — vector addition is ‘walk a, then walk b’.
- Dot mode: point a and b the same way → a·b is large and positive, cosine ≈ 1.
- Make them perpendicular (90°) → a·b = 0 and the projection collapses to a point.
- Point them in opposite directions → a·b becomes negative, cosine ≈ −1.
- Keep the angle fixed but make a twice as long: a·b doubles, cosine similarity does not change. That is why embeddings are compared with cosine, not raw dot products, when lengths vary.
Matrices and tensors
A [[matrix]] is a rectangular grid of numbers with m rows and n columns. A whole dataset is a matrix X (one row per example, one column per feature). Multiplying a matrix by a vector performs many dot products at once — one per row. A neural network layer is exactly y = Wx + b: each row of W holds one neuron's weights. The rule to remember: inner dimensions must match.
- (Wx)ᵢ
- the i-th entry of the product W times x (e.g. the output of neuron i)
- Σⱼ
- sum over j: walk along the columns of row i
- Wᵢⱼ
- the entry of Matrix W in row i, column j (row first, then column)
- xⱼ
- the j-th component of the input Vector x
- (m×n)
- shape of the first matrix: m rows, n columns
- ·
- matrix multiplication
- (n×p)
- shape of the second matrix: its row count n must equal the first one's column count (a vector is n×1)
- →
- “gives a result of shape”
- (m×p)
- shape of the result: the outer sizes
▸Worked example
A [[tensor]] generalises this to any number of axes. Deep learning frameworks (PyTorch, TensorFlow, JAX) store everything as tensors, and most bugs are shape bugs, so get used to reading shapes.
| Object | Axes | Example shape | Meaning |
|---|---|---|---|
| Scalar | 0 | () | a single loss value |
| Vector | 1 | (768,) | one token embedding |
| Matrix | 2 | (1000, 20) | 1000 examples × 20 features |
| 3-D tensor | 3 | (8, 512, 768) | batch × tokens × embedding dim |
| 4-D tensor | 4 | (32, 3, 224, 224) | batch of 32 RGB images, 224×224 px |
Derivatives and gradients
A [[derivative]] is the slope of a function at a point: how much the output changes for a tiny change in the input. For f(x) = x², f′(x) = 2x, so at x = 3 the slope is 6 — nudging x up by 0.01 raises f by about 0.06. When a function has many inputs, each partial derivative ∂f/∂xᵢ is the slope along one input with the others held fixed. Collecting all of them gives the [[gradient]] ∇f, a vector that points in the direction of steepest increase[3].
- f′(x)
- “f prime of x”: the derivative of f at x (the slope there)
- lim_{h→0}
- “the limit as h goes to 0”: the value the expression approaches as h gets ever smaller (h never actually equals 0)
- f(x+h)
- the function value a tiny step h to the right
- f(x)
- the function value at x
- h
- a tiny step in the input, e.g. 0.001
- ∇f
- “nabla f” or “grad f”: the Gradient, a vector of all partial derivatives
- ∂f/∂x₁
- partial derivative: slope of f along x₁ only, other inputs frozen. The curly ∂ means “partial”
- ∂f/∂xₙ
- the slope along the last input; the gradient has n entries, one per input (one per parameter in training)
▸Worked example
Why this matters: training minimises a loss L(θ). The gradient ∇L tells us which way is ‘uphill’, so stepping in the opposite direction lowers the loss — that is gradient descent, the subject of a later lesson. To get gradients through many stacked functions (layers), we use the chain rule, which is exactly what Backpropagation automates.
- d/dx
- “the derivative with respect to x” of whatever follows
- f(g(x))
- a composition: first compute g(x), then feed the result into f (like stacked layers)
- f′(g(x))
- the derivative of the outer function f, evaluated at the inner value g(x)
- ·
- ordinary multiplication
- g′(x)
- the derivative of the inner function g at x
▸Worked example
Probability
A [[probability-distribution|probability distribution]] assigns how likely each possible outcome is; the probabilities of all outcomes sum (or integrate) to 1. Classifiers output a distribution over classes (e.g. cat 0.85, dog 0.12, fox 0.03, produced by Softmax); LLMs output a distribution over the next token. Key ideas: the mean (expected value) and variance (spread); the normal (Gaussian) distribution, which models noise and is used to initialise weights; and conditional probability P(A | B), the probability of A given that B happened, linked by Bayes' rule[4].
- Σₖ
- sum over all possible outcomes k (all classes, all tokens…)
- p(k)
- probability of outcome k, between 0 and 1 (a Probability distribution)
- N(x; μ, σ²)
- the normal (Gaussian) density at value x, for a distribution with mean μ and variance σ²
- μ
- mu — the mean (centre of the bell)
- σ²
- sigma squared — the variance (spread); σ is the standard deviation
- √(2πσ²)
- normalising constant: makes the total area under the bell exactly 1
- π
- pi ≈ 3.14159
- e^
- e (≈ 2.718) raised to the power that follows; the same as exp(…)
- (x−μ)²
- squared distance from the mean: the further away, the more negative the exponent, the lower the density
- 2σ²
- scales the distance by the spread: a wide bell (big σ) falls off slowly
- P(A | B)
- conditional probability: probability of A given that B happened (the | reads “given”)
- P(B | A)
- the reverse: probability of B given A (often easy to measure)
- P(A)
- prior: probability of A before seeing B
- P(B)
- total probability of the evidence B, over all cases
▸Worked example
import numpy as np
a = np.array([2.0, 1.0])
b = np.array([1.0, 3.0])
print(a @ b) # dot product = 5.0
print(np.linalg.norm(a)) # length |a| ≈ 2.236
cos = a @ b / (np.linalg.norm(a) * np.linalg.norm(b))
print(cos) # cosine similarity ≈ 0.707
W = np.random.randn(3, 4) # 3 neurons, 4 inputs
x = np.random.randn(4)
print((W @ x).shape) # (3,) — three dot products at once
print(a * b) # element-wise product [2., 3.] (NOT a dot product)
f = lambda x: x ** 2
h = 1e-5
print((f(3 + h) - f(3)) / h) # numerical derivative ≈ 6.0
logits = np.array([2.0, 0.1, -1.5])
p = np.exp(logits) / np.exp(logits).sum() # softmax -> probability distribution
print(p, p.sum()) # sums to 1.0* vs @:** in NumPy/PyTorch a * b is element-wise, a @ b is the dot/matrix product. Shape mismatches are the #1 runtime error — print .shape often. Dot vs cosine: raw dot products favour long vectors; normalise first if you care only about direction. log(0): probabilities can underflow to 0; frameworks work with log-probabilities and fused functions (e.g. cross_entropy on logits) for numerical stability.▸Go deeper: norms, eigenvectors and log-likelihood
- L1 norm |a|₁ = Σ|aᵢ| and L2 norm |a|₂ = √Σaᵢ². They reappear as L1 (lasso) and L2 (ridge / weight decay) Regularisation.
- Eigenvectors of a matrix A satisfy Av = λv: A only stretches them. The eigenvectors of a data covariance matrix are the principal components used by PCA.
- Log-likelihood: training a probabilistic model usually means maximising Σ log p(yᵢ | xᵢ). Logs turn products of many small probabilities into sums, which are numerically stable. Minimising Cross-entropy (log loss) is the same thing.
For a rigorous but friendly treatment, *Mathematics for Machine Learning* (Deisenroth, Faisal & Ong) is free online[5].
Quiz
References
- [1]Deep Learning — Chapter 2: Linear AlgebraBookGoodfellow, Bengio & Courville2016deeplearningbook.org
- [2]Dive into Deep Learning — 2.3 Linear AlgebraBookZhang, Lipton, Li & Smolad2l.ai
- [3]Deep Learning — Chapter 4: Numerical ComputationBookGoodfellow, Bengio & Courville2016deeplearningbook.orgGradients and gradient-based optimisation.
- [4]Deep Learning — Chapter 3: Probability and Information TheoryBookGoodfellow, Bengio & Courville2016deeplearningbook.org
- [5]Mathematics for Machine LearningBookDeisenroth, Faisal & Ong2020mml-book.github.io