v9.1.1
Menu

Chapter 3: Mathematical Foundations

Essential mathematics for AI and ML: linear algebra, probability and statistics, information theory, calculus for optimization, matrix decompositions, and dimensionality reduction with PCA.

Topics
7
Videos
7
Min read
81

Chapter Overview

Mathematics is the foundation of all AI and machine learning. Every algorithm you encounter -- from image filters to neural networks -- relies on concepts from linear algebra, calculus, probability, statistics, and information theory. Understanding these foundations transforms you from someone who applies algorithms to someone who truly understands them.

Linear algebra provides the language: images are matrices of numbers, model parameters are vectors, and predictions are computed through matrix multiplication. When you see Y = XW + b, you are looking at how a neural network layer transforms its inputs. Understanding how matrices transform space -- through rotations, scaling, and projections -- gives you geometric intuition for what models actually do, whether in computer vision or machine learning.

Probability and statistics help you reason about uncertainty. Models don't make perfect predictions -- they estimate probabilities. Understanding distributions, expectations, and Bayes' theorem explains why certain loss functions work and how models quantify confidence. Maximum likelihood estimation connects probability to optimization, forming the basis of most training procedures.

Information theory, developed by Claude Shannon, provides the mathematical framework for measuring information content. Concepts like entropy, cross-entropy, and KL divergence are fundamental to understanding classification loss functions, generative models, and representation learning.

Calculus, specifically gradient-based optimization, is how models learn. The derivative tells us which direction improves predictions, and optimization algorithms follow this gradient to find the best parameters. The chain rule enables backpropagation in neural networks. Understanding convexity helps explain when optimization is easy versus hard.

Matrix decompositions like Singular Value Decomposition (SVD) are workhorses of both CV and ML -- powering image compression, recommender systems, dimensionality reduction, and understanding the geometry of learned representations.

Finally, eigendecomposition underlies dimensionality reduction. Principal Component Analysis (PCA) finds directions of maximum variance by computing eigenvectors of the covariance matrix, while eigenvalues of the Hessian reveal curvature of loss landscapes. In computer vision, eigenvalues power Harris corner detection, and eigenvectors form the basis of Eigenfaces.

This chapter provides the mathematical toolkit you will use throughout your journey:

  • Vectors & Vector Operations: The data structures and operations at the heart of all CV and ML
  • Matrices & Transformations: How matrices represent and compose geometric transformations
  • Probability & Statistics: Tools for reasoning about uncertainty and measuring model performance
  • Information Theory: Entropy, cross-entropy, and KL divergence for loss functions
  • Calculus for Optimization: Gradients, gradient descent, and convexity for training models
  • Matrix Decompositions: SVD and its applications
  • Eigenvalues & PCA: Understanding and implementing dimensionality reduction

Chapter Roadmap

Click any topic to jump in

Explainer video
1
Vectors & Operations

Vector arithmetic, dot products, norms, and matrix ops — the atomic units of all ML computation.

Vector DefinitionVector AdditionDot ProductVector Magnitude (Norm)Matrix MultiplicationTransposeMatrix RankMatrix Inverse
2
Matrices & Transforms

Linear transformations, rotation, projection, determinants — how matrices encode geometric operations.

Matrix as Linear TransformationMatrix MultiplicationRotation MatrixMatrix InverseLinear Transformation DefinitionScaling MatrixProjection MatrixDeterminantOrthogonal Matrices
Uncertainty and information

Probabilistic and information-theoretic foundations

3
Probability & Stats

Distributions, Bayes' theorem, MLE — the language of uncertainty in ML.

Normal DistributionBayes' TheoremMean and VarianceCovariance and CorrelationMaximum Likelihood Estimation (MLE)Expectation
4
Information Theory

Entropy, cross-entropy, KL divergence — measuring information and defining loss functions.

EntropyCross-EntropyKL DivergenceMutual InformationBits vs NatsBinary Cross-Entropy
Optimizing with derivatives
5
Calculus for Optimization

Gradients, chain rule, Hessians, gradient descent — the engine behind neural network training.

Derivative (Gradient)Gradient VectorGradient DescentChain RuleHessian MatrixConvexityTaylor Expansion
Factoring and reducing

Decompositions and dimensionality reduction

6
Matrix Decompositions

SVD, LU, QR, Cholesky — factoring matrices to solve systems and compress data.

Singular Value Decomposition (SVD)Truncated SVDSingular ValuesLU DecompositionQR DecompositionCholesky Decomposition
7
Eigenvalues & PCA

Eigenvectors, spectral theorem, PCA — finding directions of maximum variance for dimensionality reduction.

Eigenvector DefinitionCharacteristic EquationEigendecompositionSymmetric MatricesCovariance MatrixPrincipal Component Analysis (PCA)Variance ExplainedSpectral Theorem

Topics

7 topics in this chapter

A photo-search app has to decide which of a million stored images looks most like the one you just uploaded. A tracker needs to know how far an object moved between two frames and in which direction. A linear layer has to turn 512 input features into 10 class scores. All three problems ask for the same thing: a way to store several numbers as one object, and then add, compare, and measure those objects with a few cheap, well-defined operations.

The previous chapter, NumPy & Data Wrangling, gave you arrays and taught you to slice, broadcast, and multiply them. This chapter explains the mathematics behind those array operations, and vectors come first because every other object here is built from them. A vector is an ordered list of numbers that can be read as a point, an arrow, or a feature description. Addition combines displacements, the dot product measures alignment and similarity, and a norm measures length.

We start with the definition, addition, the dot product, and norms. The topic then introduces the matrix operations the rest of the chapter depends on: multiplication, transpose, rank, and the inverse.

Definition

A vector in Rn\mathbb{R}^n is an ordered list of n real numbers, usually written as a column. Vectors add component by component and scale by multiplying every component by the same number. The dot product a⋅b=∑iaibi\mathbf{a} \cdot \mathbf{b} = \sum_i a_i b_i returns a scalar that measures how well two vectors align, and the Euclidean norm ∥v∥=v⋅v\|\mathbf{v}\| = \sqrt{\mathbf{v} \cdot \mathbf{v}} gives the length of a vector.

In this topic

  1. 1Vector Definition
  2. 2Vector Addition
  3. 3Dot Product
  4. 4Vector Magnitude (Norm)
  5. 5Matrix Multiplication
  6. 6Transpose
  7. 7Matrix Rank
  8. 8Matrix Inverse
1 of 8
Vector Definition

v⃗=(vxvyvz)\vec{v} = \begin{pmatrix} v_x \\ v_y \\ v_z \end{pmatrix}

A vector is a quantity with both magnitude (length) and direction. In computer vision, vectors represent:

  • Pixel coordinates: Position (x,y)(x, y) in an image
  • Gradients: Direction and rate of intensity change
  • Features: High-dimensional descriptors of image patches
  • Transformations: Movement and rotation parameters

Vectors can have any number of dimensions. 2D vectors describe points in images, 3D vectors describe points in space, and feature vectors can have hundreds or thousands of dimensions.

Row vs Column Vectors: By convention, we typically use column vectors in linear algebra. A column vector is an n×1n \times 1 matrix, while a row vector is 1×n1 \times n. The transpose operation v⃗T\vec{v}^T converts between them.

Geometric vs Algebraic View: Geometrically, a vector is an arrow from origin to a point. Algebraically, it's an ordered list of numbers. Both views are useful—the geometric view helps with intuition, while the algebraic view enables computation.

Mathematical Intuition

A vector in Rn\mathbb{R}^n is a point in nn-dimensional space and an arrow from the origin. In ML, a 768-dim BERT embedding and a 2D pixel coordinate are both vectors — the algebra is identical, only the dimension changes.

Example:

Express the pixel at position (120, 80) in a 640x480 image as a vector, and find its transpose.

2 of 8
Vector Addition

a⃗+b⃗=(ax+bxay+by)\vec{a} + \vec{b} = \begin{pmatrix} a_x + b_x \\ a_y + b_y \end{pmatrix}

Vector addition combines two vectors component-wise. Geometrically, place the tail of b⃗\vec{b} at the tip of a⃗\vec{a}—the result points from a⃗\vec{a}'s tail to b⃗\vec{b}'s tip (the parallelogram rule).

Properties:

  • Commutative: a⃗+b⃗=b⃗+a⃗\vec{a} + \vec{b} = \vec{b} + \vec{a}
  • Associative: (a⃗+b⃗)+c⃗=a⃗+(b⃗+c⃗)(\vec{a} + \vec{b}) + \vec{c} = \vec{a} + (\vec{b} + \vec{c})
  • Identity: a⃗+0⃗=a⃗\vec{a} + \vec{0} = \vec{a}
  • Inverse: a⃗+(−a⃗)=0⃗\vec{a} + (-\vec{a}) = \vec{0}

Applications:

  • Combining displacements or velocities in tracking
  • Superimposing optical flow fields
  • Accumulating gradients in neural network optimization
  • Blending feature vectors in attention mechanisms
Mathematical Intuition

Adding vectors a⃗+b⃗\vec{a} + \vec{b} places them tip-to-tail. In gradient accumulation, each mini-batch contributes a gradient vector; the sum is the total update direction. Commutativity (a⃗+b⃗=b⃗+a⃗\vec{a}+\vec{b}=\vec{b}+\vec{a}) means the order of accumulation doesn't matter.

Example:

A tracked object moves by d1⃗=(5,3)\vec{d_1} = (5, 3) in frame 1 and d2⃗=(−2,4)\vec{d_2} = (-2, 4) in frame 2. Find the total displacement.

3 of 8
Dot Product

a⃗⋅b⃗=∣a⃗∣∣b⃗∣cos⁡θ=∑iaibi\vec{a} \cdot \vec{b} = |\vec{a}||\vec{b}|\cos\theta = \sum_i a_i b_i

The dot product (inner product) measures how much two vectors point in the same direction. It returns a scalar (single number):

  • Positive: Vectors point in similar directions (θ<90°\theta < 90°)
  • Zero: Vectors are perpendicular (θ=90°\theta = 90°)
  • Negative: Vectors point in opposite directions (θ>90°\theta > 90°)

Projection Formula: The projection of a⃗\vec{a} onto b⃗\vec{b} is: projb⃗a⃗=a⃗⋅b⃗∣b⃗∣2b⃗\text{proj}_{\vec{b}}\vec{a} = \frac{\vec{a} \cdot \vec{b}}{|\vec{b}|^2}\vec{b}

Applications in CV/ML:

  • Cosine similarity: cos⁡θ=a⃗⋅b⃗∣a⃗∣∣b⃗∣\cos\theta = \frac{\vec{a} \cdot \vec{b}}{|\vec{a}||\vec{b}|} for comparing embeddings
  • Attention mechanisms: Query-key dot products in transformers
  • Convolution: Each filter application is a dot product
  • Lighting: Lambert's law uses n⃗⋅l⃗\vec{n} \cdot \vec{l} for diffuse shading
Mathematical Intuition

The dot product a⃗⋅b⃗=∥a∥∥b∥cos⁡θ\vec{a} \cdot \vec{b} = \|a\|\|b\|\cos\theta projects one vector onto another. When cos⁡θ=0\cos\theta=0 the vectors are orthogonal and share no information — this is why orthogonal features are ideal in ML: zero redundancy.

Example:

Compute the cosine similarity between image embeddings a⃗=(3,4)\vec{a} = (3, 4) and b⃗=(4,3)\vec{b} = (4, 3).

4 of 8
Vector Magnitude (Norm)

∣v⃗∣=∥v⃗∥2=∑ivi2|\vec{v}| = \|\vec{v}\|_2 = \sqrt{\sum_i v_i^2}

The magnitude or L2 norm (Euclidean norm) is the vector's length. A unit vector has magnitude 1:

v^=v⃗∣v⃗∣\hat{v} = \frac{\vec{v}}{|\vec{v}|}

Other Important Norms:

  • L1 norm (Manhattan): ∥v⃗∥1=∑i∣vi∣\|\vec{v}\|_1 = \sum_i |v_i| — encourages sparsity in regularization
  • L∞ norm (Chebyshev): ∥v⃗∥∞=max⁡i∣vi∣\|\vec{v}\|_\infty = \max_i |v_i| — maximum absolute value
  • Lp norm: ∥v⃗∥p=(∑i∣vi∣p)1/p\|\vec{v}\|_p = (\sum_i |v_i|^p)^{1/p}

Why Normalize? Normalizing vectors is essential when you care about direction but not scale:

  • Comparing gradient directions in edge detection
  • Unit-length embeddings in contrastive learning (SimCLR, CLIP)
  • Preventing magnitude from dominating similarity scores
  • Numerical stability in deep learning
Mathematical Intuition

The L2 norm ∥v⃗∥2\|\vec{v}\|_2 is Euclidean distance from the origin. L1 encourages sparsity because its unit ball has corners on the axes, pushing small weights to exactly zero — the geometric reason Lasso produces sparse solutions.

Example:

Normalize the gradient vector g⃗=(6,8)\vec{g} = (6, 8) to a unit vector.

5 of 8
Matrix Multiplication

Cij=∑kAikBkjC_{ij} = \sum_k A_{ik} B_{kj}

Matrix multiplication computes a whole batch of dot products at once. In the formula, entry CijC_{ij} is the dot product of row ii of AA with column jj of BB, summing over the shared index kk, so the inner dimensions must match: an m×nm \times n matrix times an n×pn \times p matrix gives an m×pm \times p result. A linear layer computes Y=XW+bY = XW + b this way, with one input example per row of XX. The product is associative, (AB)C=A(BC)(AB)C = A(BC), but not commutative, since ABAB and BABA usually differ or do not even exist. A costly beginner bug is using NumPy's element-wise * where the matrix product @ was meant.

Mathematical Intuition

Each element Cij=∑kAikBkjC_{ij} = \sum_k A_{ik}B_{kj} is a dot product between row ii of AA and column jj of BB. A neural network layer Y=XWY = XW computes every output neuron as a dot product of the input with a learned weight vector.

Example:

Multiply A = [[1,2],[3,4]] by B = [[5,6],[7,8]]

6 of 8
Transpose

(AT)ij=Aji(A^T)_{ij} = A_{ji}

The transpose flips a matrix across its main diagonal. The formula says the entry in row ii, column jj of ATA^T is the entry in row jj, column ii of AA, so an m×nm \times n matrix becomes n×mn \times m. It turns column vectors into row vectors, which lets us write the dot product as aTb\mathbf{a}^T\mathbf{b}. The key identity is (AB)T=BTAT(AB)^T = B^TA^T, with the order reversed, and it appears in every backpropagation derivation: the gradient flowing back through Y=XWY = XW is multiplied by WTW^T. A matrix equal to its own transpose is symmetric, and covariance matrices are the main example. Transposing never changes the rank.

Mathematical Intuition

Transposing swaps rows and columns: (AT)ij=Aji(A^T)_{ij} = A_{ji}. The identity (AB)T=BTAT(AB)^T = B^T A^T reverses multiplication order — this is exactly what backpropagation does when it propagates gradients backward through layers.

Example:

Find the transpose of A = [[1,2,3],[4,5,6]]

7 of 8
Matrix Rank

rank(A)=number of linearly independent rows/columns\text{rank}(A) = \text{number of linearly independent rows/columns}

Rank counts how many genuinely different directions a matrix contains. It is the number of linearly independent columns, which always equals the number of independent rows, and row reduction finds it as the number of pivots. An m×nm \times n matrix has rank at most min⁡(m,n)\min(m, n), and reaching that bound is called full rank. A square n×nn \times n matrix is invertible exactly when its rank is nn. Lower rank means redundancy: some columns are combinations of others, so the matrix squeezes its inputs into a smaller subspace. Low rank can also be useful, since LoRA stores a weight update as a product of two thin matrices. In floating point, rank depends on a tolerance.

Mathematical Intuition

Rank counts the number of linearly independent rows (or columns). A rank-deficient weight matrix means some neurons compute redundant features. In practice, neural networks often learn low-rank representations, which is why LoRA fine-tuning works.

Example:

Find rank of A = [[1,2],[2,4]]

8 of 8
Matrix Inverse

A−1A=AA−1=IA^{-1}A = AA^{-1} = I

The inverse undoes a matrix: multiplying by A−1A^{-1} on either side gives the identity II, so Ax=bA\mathbf{x} = \mathbf{b} has the unique solution x=A−1b\mathbf{x} = A^{-1}\mathbf{b}. Only square, full-rank matrices, those with a nonzero determinant, have one. For a 2×2 matrix [[a, b], [c, d]], swap aa and dd, negate bb and cc, and divide by ad−bcad - bc. The inverse appears in the closed-form regression solution w=(XTX)−1XTy\mathbf{w} = (X^TX)^{-1}X^T\mathbf{y}. In practice you rarely form it explicitly: np.linalg.solve is faster and more accurate, and the pseudoinverse handles matrices that have no inverse at all.

Mathematical Intuition

If Ax⃗=b⃗A\vec{x} = \vec{b} then x⃗=A−1b⃗\vec{x} = A^{-1}\vec{b}, but only when AA is full rank. The normal equation w⃗=(XTX)−1XTy⃗\vec{w} = (X^TX)^{-1}X^T\vec{y} gives closed-form linear regression — but fails when features are collinear (XTXX^TX is singular).

Example:

Find inverse of A = [[2,1],[5,3]]

Theory Exercise

Problem:

Given vectors a = (3, 4) and b = (1, 2), calculate: (a) a + b, (b) a · b, (c) the angle between them.

Hints:
  • Add component-wise for vector sum
  • Dot product: multiply corresponding components and sum
  • Use cos(θ) = (a · b) / (|a| |b|)

Coding Exercise

Problem:

Given two 3D vectors, compute their dot product, each vector's L2 norm, and the angle between them from scratch, then verify your dot product against np.dot. Also confirm the Cauchy-Schwarz inequality |a·b| <= ||a|| ||b|| holds.

Hints:
  • The dot product is the sum of elementwise products: sum(a*b).
  • The L2 norm is sqrt of the dot product of a vector with itself; cos(theta) = (a·b)/(||a|| ||b||).
  • Clip the cosine to [-1, 1] before calling np.arccos to avoid NaNs from floating-point drift.