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.

Intermediate 4 min readLesson 2 of 14

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.

x=[120315](area, bedrooms, age)\mathbf{x} = \begin{bmatrix} 120 \\ 3 \\ 15 \end{bmatrix} \quad \text{(area, bedrooms, age)}

The dot product multiplies matching entries and sums them:

w⋅x=∑iwixi=∥w∥ ∥x∥cos⁡θ\mathbf{w} \cdot \mathbf{x} = \sum_i w_i x_i = \lVert \mathbf{w} \rVert \, \lVert \mathbf{x} \rVert \cos\theta

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) ∥x∥2=∑xi2\lVert \mathbf{x} \rVert_2 = \sqrt{\sum x_i^2} and L1 ∑∣xi∣\sum |x_i| — 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:

y=Wx+b\mathbf{y} = W\mathbf{x} + \mathbf{b}

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).

Python
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 direction

Other useful ideas: the transpose A⊤A^\top; 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 f(w)=w2f(w) = w^2, f′(w)=2wf'(w) = 2w: at w=3w = 3, increasing w slightly increases f about 6 times as much.

With many parameters, the gradient collects all partial derivatives into a vector:

∇L(w)=[∂L∂w1,∂L∂w2,…,∂L∂wn]\nabla L(\mathbf{w}) = \left[ \frac{\partial L}{\partial w_1}, \frac{\partial L}{\partial w_2}, \ldots, \frac{\partial L}{\partial w_n} \right]

It points in the direction of steepest increase of the loss L. Training moves the weights in the opposite direction — gradient descent:

w←w−η ∇L(w)\mathbf{w} \leftarrow \mathbf{w} - \eta \, \nabla L(\mathbf{w})

The chain rule

Neural networks are compositions of functions. The chain rule gives the derivative of a composition:

ddxf(g(x))=f′(g(x))⋅g′(x)\frac{d}{dx} f(g(x)) = f'(g(x)) \cdot g'(x)

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.

FunctionDerivative
xnx^nnxn−1n x^{n-1}
exe^xexe^x
ln⁡x\ln x1/x1/x
sigmoid σ(x)=1/(1+e−x)\sigma(x) = 1/(1+e^{-x})σ(x)(1−σ(x))\sigma(x)(1-\sigma(x))
ReLU max⁡(0,x)\max(0, x)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

DistributionModelsExample
BernoulliOne yes/no trial with probability pWill this user click?
CategoricalOne of K outcomesNext token among 100k vocabulary entries
Gaussian (normal)Continuous values clustering around a mean μ with spread σMeasurement noise, heights
UniformAll values equally likelyRandom initialisation

Expectation (mean) E[X]=∑xx P(x)\mathbb{E}[X] = \sum_x x \, P(x) is the average outcome; variance Var(X)=E[(X−μ)2]\mathrm{Var}(X) = \mathbb{E}[(X-\mu)^2] measures spread; the standard deviation σ is its square root.

Conditional probability and Bayes' theorem

P(A∣B)=P(B∣A) P(A)P(B)P(A \mid B) = \frac{P(B \mid A)\, P(A)}{P(B)}

Example: a disease affects 1% of people; a test is 95% sensitive and has a 5% false-positive rate. If you test positive:

P(sick∣+)=0.95×0.010.95×0.01+0.05×0.99≈16%P(\text{sick} \mid +) = \frac{0.95 \times 0.01}{0.95 \times 0.01 + 0.05 \times 0.99} \approx 16\%

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:
L=−∑kyklog⁡p^kL = -\sum_{k} y_k \log \hat{p}_k

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.
Key takeaways
  • 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.