AILearn AI
LearnGlossarySources
ID/EN
Learn AI — open material for learning AIEvery lesson cites its original sources.
◎AI Foundations
  1. What is AI?
  2. Types of learning
  3. Math essentials for ML
  4. Data and features
Modules
  1. ◎ AI Foundations
  2. ∿ Classical Machine Learning
  3. ⌬ Neural Networks
  4. ↘ Training Results & Evaluation
  5. ▦ Deep Learning Architectures
  6. ✎ Large Language Models
  7. ◐ Image Generation
  8. ♪ Audio & Speech AI
  9. ◈ Multimodal, Video & 3D
  10. ↻ Reinforcement Learning
  11. ⚙ ML Development & MLOps
  12. ★ Advanced & Frontier Topics
Learn/AI Foundations

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.

Beginner~22 min·5 references
Key terms
VectorDot productMatrixTensorDerivativeGradientProbability distributionCosine similarity

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

≈
A vector is a list of attributes
Describe a house as [area = 72, bedrooms = 3, age = 10]. That list of numbers is a vector — and it is also an arrow pointing to a location in a 3-dimensional ‘house space’. Similar houses are arrows pointing to nearby places. Machine learning is largely geometry in such spaces, often with hundreds or thousands of dimensions.

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₁, a₂, …, aₙ] |a| = √(a₁² + a₂² + … + aₙ²) dist(a, b) = |a − b|
In words: A Vector is just a list of n numbers. Its length is Pythagoras generalised: square every component, add them up, take the square root. The distance between two vectors is the length of the arrow from one to the other, i.e. of their difference.
Symbols(hover a symbol in the formula)
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
a = [3, 4] (n = 2) |a| = √(3² + 4²) = √(9 + 16) = √25 = 5 b = [0, 1] a − b = [3 − 0, 4 − 1] = [3, 3] dist(a, b) = √(3² + 3²) = √18 ≈ 4.24

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 = Σᵢ aᵢbᵢ = |a| |b| cos θ cos θ = (a·b) / (|a| |b|)
The right-hand ratio is cosine similarity: 1 = same direction, 0 = perpendicular, −1 = opposite. It ignores length.
In words: Read the first part as “multiply matching components and add them up”. The same number also equals “length × length × how aligned they are”, where cos θ is 1 when the vectors point the same way, 0 at a right angle and −1 when opposite. Dividing out the lengths (second formula) leaves pure direction: Cosine similarity.
Symbols(hover a symbol in the formula)
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
a = [2, 1], b = [1, 3] a·b = 2·1 + 1·3 = 2 + 3 = 5 |a| = √(4 + 1) = √5 ≈ 2.236 |b| = √(1 + 9) = √10 ≈ 3.162 |a| |b| = √50 ≈ 7.071 cos θ = 5 / 7.071 ≈ 0.707 → θ = 45° (fairly similar direction) Double a to [4, 2]: a·b = 10, but cos θ is still 0.707 — cosine ignores length.

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.

Loading interactive…
Drag the tips of vectors a and b. Switch between addition mode and dot product & projection mode.
  • 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)ᵢ = Σⱼ Wᵢⱼ xⱼ (m×n) · (n×p) → (m×p)
A 3×4 matrix times a 4×2 matrix gives 3×2. A 3×4 times a 3×2 is an error — the inner sizes (4 vs 3) differ.
In words: Read the left part as “entry i of the result is the Dot product of row i of W with x”. The right part is the shape rule: the two inner sizes (n and n) must match and cancel out, the two outer sizes give the result's shape.
Symbols(hover a symbol in the formula)
(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
W (3×2) = [[1, 2], [3, 4], [0, −1]], x (2×1) = [5, 6] (Wx)₁ = 1·5 + 2·6 = 17 (Wx)₂ = 3·5 + 4·6 = 39 (Wx)₃ = 0·5 + (−1)·6 = −6 Shapes: (3×2) · (2×1) → (3×1), so Wx = [17, 39, −6] As a layer: 2 inputs, 3 neurons, 3 outputs. A batch of 32 examples: X (32×2) · Wᵀ (2×3) → (32×3).

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.

ObjectAxesExample shapeMeaning
Scalar0()a single loss value
Vector1(768,)one token embedding
Matrix2(1000, 20)1000 examples × 20 features
3-D tensor3(8, 512, 768)batch × tokens × embedding dim
4-D tensor4(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) = lim_{h→0} (f(x+h) − f(x)) / h ∇f = [∂f/∂x₁, ∂f/∂x₂, …, ∂f/∂xₙ]
In words: Left: the Derivative is “rise over run” for a step h so tiny it shrinks to zero — the slope of the curve exactly at x. Right: for a function of many inputs, compute that slope separately along each input (holding the others fixed) and stack the results into one vector, the Gradient. It points in the direction where f grows fastest.
Symbols(hover a symbol in the formula)
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
f(x) = x², at x = 3 (true slope 2x = 6): h = 0.1 → (3.1² − 9) / 0.1 = (9.61 − 9) / 0.1 = 6.1 h = 0.01 → 6.01 h = 0.001 → 6.001 → the limit is 6 ✓ Two inputs: f(x₁, x₂) = x₁² + 3·x₂, at (1, 2) ∂f/∂x₁ = 2·x₁ = 2 (x₂ frozen) ∂f/∂x₂ = 3 (x₁ frozen) ∇f = [2, 3]: f rises fastest if you move 2 parts along x₁ and 3 parts along x₂.

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.

Chain rule: d/dx f(g(x)) = f′(g(x)) · g′(x)
Example: f(g) = g², g(x) = 3x + 1 → d/dx = 2(3x + 1) · 3.
In words: “the slope of a function inside a function = slope of the outer one (measured at the inner value) times slope of the inner one”. Rates of change multiply along a chain: if g changes 3× as fast as x and f changes 8× as fast as g, then f changes 24× as fast as x. Backpropagation applies this rule layer by layer.
Symbols(hover a symbol in the formula)
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
g(x) = 3x + 1, f(g) = g², at x = 1 g(1) = 4 f′(g) = 2g → f′(4) = 8 g′(x) = 3 d/dx f(g(x)) = 8 · 3 = 24 Check numerically: x = 1.001 → g = 4.003 → f = 16.024009 (16.024009 − 16) / 0.001 ≈ 24.01 ✓

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

Σₖ p(k) = 1 N(x; μ, σ²) = (1 / √(2πσ²)) · e^(−(x−μ)² / (2σ²)) P(A | B) = P(B | A) · P(A) / P(B)
In words: Three facts in one line. (1) The probabilities of all possible outcomes add up to 1. (2) The bell-shaped normal (Gaussian) density is highest at the mean μ and falls off the further x is from μ, measured in units of the spread σ. (3) Bayes' rule flips a conditional probability: from “how likely is the evidence if A is true” to “how likely is A now that I saw the evidence”.
Symbols(hover a symbol in the formula)
Σₖ
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
(1) Classifier output: cat 0.85 + dog 0.12 + fox 0.03 = 1.00 ✓ (2) Standard normal, μ = 0, σ² = 1: x = 0: 1/√(2π) ≈ 0.399 x = 1: 0.399 · e^(−1/2) ≈ 0.399 · 0.607 ≈ 0.242 (3) A = has disease (P(A) = 0.01), B = test positive. P(B | A) = 0.9, false-positive rate P(B | not A) = 0.05 P(B) = 0.9·0.01 + 0.05·0.99 = 0.009 + 0.0495 = 0.0585 P(A | B) = 0.9 · 0.01 / 0.0585 ≈ 0.154 → a positive test means only ~15% chance of disease, because the disease is rare.
python
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
Every concept in this lesson in a dozen lines of NumPy.
!
Common pitfalls
* 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

1.
Two vectors are perpendicular (90° apart). What is their dot product?
2.
You double the length of vector a without changing its direction. What happens to cosine similarity with b?
3.
What is the shape of the product of a (3×4) matrix and a (4×2) matrix?
4.
The gradient ∇L of a loss function points…
5.
A classifier outputs cat 0.7, dog 0.2, fox 0.2. What is wrong?
Score: 0/5

References

  1. [1]
    Deep Learning — Chapter 2: Linear Algebra
    BookGoodfellow, Bengio & Courville2016deeplearningbook.org
  2. [2]
    Dive into Deep Learning — 2.3 Linear Algebra
    BookZhang, Lipton, Li & Smolad2l.ai
  3. [3]
    Deep Learning — Chapter 4: Numerical Computation
    BookGoodfellow, Bengio & Courville2016deeplearningbook.org
    Gradients and gradient-based optimisation.
  4. [4]
    Deep Learning — Chapter 3: Probability and Information Theory
    BookGoodfellow, Bengio & Courville2016deeplearningbook.org
  5. [5]
    Mathematics for Machine Learning
    BookDeisenroth, Faisal & Ong2020mml-book.github.io
← Previous
Types of learning
Next →
Data and features