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
Vectors & Operations
Vector arithmetic, dot products, norms, and matrix ops — the atomic units of all ML computation.
Matrices & Transforms
Linear transformations, rotation, projection, determinants — how matrices encode geometric operations.
Probabilistic and information-theoretic foundations
Probability & Stats
Distributions, Bayes' theorem, MLE — the language of uncertainty in ML.
Information Theory
Entropy, cross-entropy, KL divergence — measuring information and defining loss functions.
Calculus for Optimization
Gradients, chain rule, Hessians, gradient descent — the engine behind neural network training.
Decompositions and dimensionality reduction
Matrix Decompositions
SVD, LU, QR, Cholesky — factoring matrices to solve systems and compress data.
Eigenvalues & PCA
Eigenvectors, spectral theorem, PCA — finding directions of maximum variance for dimensionality reduction.
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 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 returns a scalar that measures how well two vectors align, and the Euclidean norm gives the length of a vector.
In this topic
- 1Vector Definition
- 2Vector Addition
- 3Dot Product
- 4Vector Magnitude (Norm)
- 5Matrix Multiplication
- 6Transpose
- 7Matrix Rank
- 8Matrix Inverse
Vector Definition
A vector is a quantity with both magnitude (length) and direction. In computer vision, vectors represent:
- Pixel coordinates: Position 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 matrix, while a row vector is . The transpose operation 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.
A vector in is a point in -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.
Express the pixel at position (120, 80) in a 640x480 image as a vector, and find its transpose.
Vector Addition
Vector addition combines two vectors component-wise. Geometrically, place the tail of at the tip of —the result points from 's tail to 's tip (the parallelogram rule).
Properties:
- Commutative:
- Associative:
- Identity:
- Inverse:
Applications:
- Combining displacements or velocities in tracking
- Superimposing optical flow fields
- Accumulating gradients in neural network optimization
- Blending feature vectors in attention mechanisms
Adding vectors places them tip-to-tail. In gradient accumulation, each mini-batch contributes a gradient vector; the sum is the total update direction. Commutativity () means the order of accumulation doesn't matter.
A tracked object moves by in frame 1 and in frame 2. Find the total displacement.
Dot Product
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 ()
- Zero: Vectors are perpendicular ()
- Negative: Vectors point in opposite directions ()
Projection Formula: The projection of onto is:
Applications in CV/ML:
- Cosine similarity: for comparing embeddings
- Attention mechanisms: Query-key dot products in transformers
- Convolution: Each filter application is a dot product
- Lighting: Lambert's law uses for diffuse shading
The dot product projects one vector onto another. When the vectors are orthogonal and share no information — this is why orthogonal features are ideal in ML: zero redundancy.
Compute the cosine similarity between image embeddings and .
Vector Magnitude (Norm)
The magnitude or L2 norm (Euclidean norm) is the vector's length. A unit vector has magnitude 1:
Other Important Norms:
- L1 norm (Manhattan): — encourages sparsity in regularization
- L∞ norm (Chebyshev): — maximum absolute value
- Lp norm:
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
The L2 norm 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.
Normalize the gradient vector to a unit vector.
Matrix Multiplication
Matrix multiplication computes a whole batch of dot products at once. In the formula, entry is the dot product of row of with column of , summing over the shared index , so the inner dimensions must match: an matrix times an matrix gives an result. A linear layer computes this way, with one input example per row of . The product is associative, , but not commutative, since and usually differ or do not even exist. A costly beginner bug is using NumPy's element-wise * where the matrix product @ was meant.
Each element is a dot product between row of and column of . A neural network layer computes every output neuron as a dot product of the input with a learned weight vector.
Multiply A = [[1,2],[3,4]] by B = [[5,6],[7,8]]
Transpose
The transpose flips a matrix across its main diagonal. The formula says the entry in row , column of is the entry in row , column of , so an matrix becomes . It turns column vectors into row vectors, which lets us write the dot product as . The key identity is , with the order reversed, and it appears in every backpropagation derivation: the gradient flowing back through is multiplied by . A matrix equal to its own transpose is symmetric, and covariance matrices are the main example. Transposing never changes the rank.
Transposing swaps rows and columns: . The identity reverses multiplication order — this is exactly what backpropagation does when it propagates gradients backward through layers.
Find the transpose of A = [[1,2,3],[4,5,6]]
Matrix Rank
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 matrix has rank at most , and reaching that bound is called full rank. A square matrix is invertible exactly when its rank is . 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.
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.
Find rank of A = [[1,2],[2,4]]
Matrix Inverse
The inverse undoes a matrix: multiplying by on either side gives the identity , so has the unique solution . Only square, full-rank matrices, those with a nonzero determinant, have one. For a 2×2 matrix [[a, b], [c, d]], swap and , negate and , and divide by . The inverse appears in the closed-form regression solution . 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.
If then , but only when is full rank. The normal equation gives closed-form linear regression — but fails when features are collinear ( is singular).
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.
Related Problems on PixelBank
A photo editor rotates an image by 30 degrees, a camera model maps 3D points onto a 2D sensor, and a data pipeline rescales every feature to unit variance. Each operation takes vectors in and puts vectors out. Each must run on millions of points quickly, chain with other operations without losing track of what happened, and sometimes be undone. What single object can describe such an operation, compose it with others, and tell us whether it can be reversed?
The previous topic, Vectors & Vector Operations, treated matrices as tables of numbers that multiply vectors. This topic reads them as transformations. The columns of a matrix show where the basis vectors land, so a 2×2 matrix fully describes a rotation, a scaling, a shear, or a projection of the plane. Multiplying matrices composes transformations, the determinant measures how much they scale area, and the inverse undoes them when that is possible. A neural network layer without its activation is exactly such a linear map.
We start with the matrix-as-transformation view and composition, then study rotation, scaling, and projection matrices, and finish with determinants, inverses, and orthogonal matrices.
Definition
A linear transformation from to is a map that preserves addition and scaling, . Every such map equals multiplication by a unique matrix whose -th column is the image of the -th standard basis vector. Composing two transformations corresponds to multiplying their matrices, and the determinant of a square matrix measures how the map scales area or volume.
In this topic
- 1Matrix as Linear Transformation
- 2Matrix Multiplication
- 3Rotation Matrix
- 4Matrix Inverse
- 5Linear Transformation Definition
- 6Scaling Matrix
- 7Projection Matrix
- 8Determinant
- 9Orthogonal Matrices
Matrix as Linear Transformation
A matrix transforms vectors by mapping each input to an output. The columns of a matrix show where the basis vectors (x and y axes) end up after transformation.
Key insight: Any linear transformation—rotation, scaling, shearing—can be represented as a matrix. This is why matrices are fundamental to computer graphics and vision.
What makes a transformation linear?
- (additivity)
- (scaling)
Common Transformations:
- Scaling: Diagonal entries stretch/compress axes
- Rotation: Preserves lengths and angles
- Shear: Skews one axis relative to another
- Reflection: Flips across an axis (determinant = -1)
A matrix maps every vector to a new vector while preserving the grid lines' parallelism and even spacing. The columns of are where the standard basis vectors land — so reading the columns tells you everything about the transformation.
Apply the scaling matrix to stretch an image horizontally.
Matrix Multiplication
Matrix multiplication composes transformations. If rotates and scales, then does both (scale first, then rotate).
Important: Matrix multiplication is not commutative— in general. The order of transformations matters!
Dimensions: For (m×n) and (n×p), the result is (m×p). Inner dimensions must match.
Properties:
- Associative: — compute in any order
- Distributive:
- Transpose: — order reverses
Computational Cost: Multiplying two matrices naively costs . Optimized algorithms like Strassen's achieve , which matters for large neural network layers.
Multiplying composes two transformations: first , then . Non-commutativity () means rotating then scaling differs from scaling then rotating — order matters in every graphics pipeline and neural network.
Compute where and .
Rotation Matrix
The rotation matrix rotates points counterclockwise by angle . Key properties:
- Orthogonal: (columns are perpendicular unit vectors)
- Determinant = 1: Preserves area/volume (proper rotation)
- Inverse = Transpose: (rotate by )
- Composition:
In 3D: Rotation matrices are 3×3. Common representations:
- Euler angles: Three successive rotations (but suffer from gimbal lock)
- Axis-angle: Rotate by around unit vector
- Quaternions: 4D representation avoiding gimbal lock, used in 3D vision
Rodrigues' Formula converts axis-angle to matrix: where is the skew-symmetric matrix of the axis.
is orthogonal: , so and lengths are preserved. In 3D vision, rotation matrices live on SO(3), a curved manifold — which is why Euler angles suffer gimbal lock and quaternions are preferred.
Rotate point by counterclockwise using the rotation matrix.
Matrix Inverse
The inverse undoes transformation . If rotates 30°, rotates -30°.
When it exists: Only square matrices with non-zero determinant are invertible. Singular matrices (det = 0) have no inverse—they collapse space into lower dimensions.
For 2×2:
Pseudoinverse: For non-square or singular matrices, the Moore-Penrose pseudoinverse provides a best-fit solution: Used in least squares problems and solving overdetermined systems.
Numerical Considerations: Direct inversion is often unstable. In practice, use:
- LU decomposition for general systems
- Cholesky for symmetric positive definite matrices
- SVD for ill-conditioned matrices
undoes : if rotates 30°, rotates -30°. When , the transformation crushes a dimension and cannot be undone — exactly when has no unique solution.
Find the inverse of .
Linear Transformation Definition
Linearity is the property that makes a transformation predictable from very little data. The formula says respects linear combinations: transforming gives the same result as transforming and separately and combining them with the same scalars and . Consequently is fully determined by where it sends the basis vectors, and those images become the columns of its matrix. Two quick tests catch most non-examples. A linear map must send to , so translation by a fixed offset fails, and it cannot contain squares or products of inputs. A layer is linear; adding a bias makes it affine.
Linearity means — scaling inputs scales outputs proportionally. Neural networks break linearity with activation functions; without them, stacking layers collapses to a single matrix.
Is T(x,y) = (2x+y, x-y) a linear transformation?
Scaling Matrix
A scaling matrix is diagonal: multiplies every x-coordinate and every y-coordinate, and the two axes never mix. Factors above 1 stretch, factors between 0 and 1 compress, and a negative factor also reflects across the other axis. The determinant is the factor by which areas change. Equal factors give uniform scaling, which preserves shapes; unequal factors distort circles into ellipses. Standardizing features, dividing each column by its standard deviation, is exactly a diagonal scaling of the data. A zero factor collapses an axis entirely, which makes the matrix singular and destroys the information along that axis.
A diagonal matrix stretches each axis independently. Batch normalization rescales features with learned values — it's a diagonal scaling in feature space that stabilizes training.
Apply scaling (sₓ=2, sᵧ=0.5) to [3, 4]
Projection Matrix
where
Projection keeps the part of a vector that lies along a chosen direction and discards the rest. For a unit vector , the matrix sends to : the dot product measures how far reaches along , and multiplying by points the result in that direction. Two properties identify it: , since projecting twice changes nothing, and . Its rank is 1 and its determinant is 0, so it cannot be undone. The formula requires unit length; for any other , divide by . PCA projects data onto its principal directions this way.
satisfies (idempotent): projecting twice gives the same result as projecting once. PCA projects data onto the top- eigenvectors of the covariance matrix, discarding low-variance directions.
Project [3, 4] onto the x-axis (u = [1, 0])
Determinant
The determinant condenses a square matrix into one number that says how the transformation scales space. Its absolute value is the factor by which areas, in 2D, or volumes, in 3D, are multiplied, and its sign says whether orientation is preserved or flipped. For a 2×2 matrix [[a, b], [c, d]] it equals . A determinant of zero means some direction is crushed to nothing, so the matrix is singular and has no inverse. It is multiplicative, , matching the composition of area scalings, and it equals the product of the eigenvalues. Its size is a poor measure of near-singularity, though; the condition number measures that properly.
The determinant measures the signed volume scaling factor. means the transformation collapses a dimension — precisely when has no unique solution.
Find det([[3,1],[2,4]])
Orthogonal Matrices
Orthogonal matrices move space rigidly, without stretching it. The formula says each column has length 1 and every pair of columns is perpendicular, and it gives the cheapest possible inverse, . Because and dot products are preserved, lengths and angles survive, and rounding errors are not amplified: the condition number is 1. The determinant is +1 for rotations and -1 for reflections, and every eigenvalue has absolute value 1. Orthogonal weight initialization uses these properties to keep signal norms stable across layers. A matrix whose columns are orthogonal but not unit length is not an orthogonal matrix.
Orthogonal matrices satisfy — their columns form an orthonormal basis. Multiplying by is a rigid-body motion (rotation/reflection) that preserves all distances and angles, making them numerically stable and cheap to invert ().
Verify Q = [[1,0],[0,-1]] (reflection about x-axis) is orthogonal
Theory Exercise
Problem:
Apply the rotation matrix R(45°) to the point (1, 0). What are the new coordinates?
Hints:
- cos(45°) = sin(45°) = √2/2 ≈ 0.707
- Multiply the rotation matrix by the point vector
- The result should have magnitude 1 (rotation preserves length)
Coding Exercise
Problem:
Build a 2D rotation matrix for a 30-degree angle and verify it is orthogonal (RᵀR = I) with determinant 1. Apply it to a unit vector and confirm the length is preserved, then check that the inverse equals the transpose.
Hints:
- A 2D rotation matrix is [[cos, -sin], [sin, cos]]; remember np.cos/np.sin take radians.
- Orthogonal means RᵀR equals the identity; use np.allclose to compare against np.eye(2).
- For an orthogonal matrix the inverse is just the transpose, and the determinant is +1 (a pure rotation, no reflection or scaling).
Related Problems on PixelBank
A spam filter sees the word "winner" and has to decide how likely the email is to be spam. A medical classifier outputs 0.83, and a doctor asks what that number means and how far to trust it. A training loop has a few thousand labelled examples and must settle on the parameters that best explain them. None of these can be answered with exact arithmetic, because the inputs are noisy and incomplete. We need a precise language for uncertainty.
The previous topic, Matrices & Transformations, described deterministic maps: the same input always gives the same output. Real data does not behave that way, so this topic adds probability. A distribution assigns probabilities to outcomes. Expectation, variance, and covariance summarize it with a few numbers. Bayes' theorem updates beliefs when evidence arrives, and maximum likelihood picks the parameters under which the observed data is most probable. Nearly every loss function in machine learning is a negative log-likelihood, so these ideas return in every later chapter.
We cover the normal distribution, Bayes' theorem, mean and variance, covariance and correlation, maximum likelihood estimation, and expectation, the average that every training objective minimizes.
Definition
A probability distribution assigns to each outcome, or range of outcomes, of a random variable a number between 0 and 1, with total probability 1. The expectation is the probability-weighted average of , and the variance measures its spread. Bayes' theorem, , converts the probability of the evidence given a hypothesis into the probability of the hypothesis given the evidence.
In this topic
- 1Normal Distribution
- 2Bayes' Theorem
- 3Mean and Variance
- 4Covariance and Correlation
- 5Maximum Likelihood Estimation (MLE)
- 6Expectation
Normal Distribution
The normal, or Gaussian, distribution is the bell curve, and it earns its central place through the Central Limit Theorem: sums and averages of many independent effects tend toward it, whatever their individual distributions. In the formula, is the mean, which sets the center, is the standard deviation, which sets the width, and the factor makes the total area 1. The exponent penalizes squared distance from the mean, so values beyond three standard deviations are rare. Assuming Gaussian noise is what turns maximum likelihood into least squares. Real data often has heavier tails, however, and a Gaussian model then badly underestimates extreme events.
The Gaussian arises whenever many small independent effects add up (Central Limit Theorem). ML weight initialization uses Gaussians because it centers activations near zero with controlled variance, preventing vanishing/exploding gradients.
For N(μ=100, σ=15), what % of data falls within 1 standard deviation?
Bayes' Theorem
Bayes' theorem reverses a conditional probability. We usually know how likely the evidence is under a hypothesis , the likelihood , but we want the probability of the hypothesis after seeing the evidence, the posterior . The theorem multiplies the likelihood by the prior , our belief before the evidence, and divides by , the total probability of the evidence, found by summing over all hypotheses. The classic mistake, base-rate neglect, is to treat as if it were . Naive Bayes classifiers, Bayesian inference, and probabilistic graphical models are all built on this single equation.
updates beliefs given evidence. The prior encodes what you knew before; the likelihood is how well the data fits. Bayesian inference treats model parameters as random variables rather than fixed unknowns.
1% have disease, test is 90% accurate. If positive, what's P(disease)?
Mean and Variance
The mean is the balance point of the data, the sum of the values divided by their count . The variance is the average squared distance from that mean, and the standard deviation , its square root, returns the spread to the original units. Squaring makes every deviation positive and weights large deviations heavily, so a single outlier can inflate the variance a lot. Dividing by gives the population variance; dividing by gives the unbiased sample estimate, and NumPy's var divides by unless you pass ddof=1. Standardization subtracts the mean and divides by the standard deviation, and batch normalization applies it inside networks.
The mean locates the center; the variance measures spread. Bias-variance tradeoff: a model with high bias misses the true mean, while high variance means predictions scatter widely around it.
Find mean and variance of [2, 4, 4, 4, 5, 5, 7, 9]
Covariance and Correlation
Covariance measures whether two variables move together. In the formula, each pair contributes the product of its deviations from the means and : positive when both sit on the same side of their means, negative when they sit on opposite sides. Averaging those products gives . Its size depends on units, so the correlation divides by both standard deviations and always lands in [-1, 1]. Values near 1 or -1 mean a nearly perfect linear relationship. A value of 0 means no linear relationship, not independence: with symmetric has zero correlation. Collecting all pairwise covariances gives the covariance matrix used by PCA.
Covariance captures linear co-movement. Correlation normalizes to . The covariance matrix of features reveals redundancies — PCA diagonalizes it, rotating data into uncorrelated axes.
X=[1,2,3], Y=[2,4,5]. Find Cov(X,Y) and correlation ρ
Maximum Likelihood Estimation (MLE)
Maximum likelihood chooses the parameters under which the observed data is most probable. For independent samples , the likelihood is the product of the individual probabilities , and the estimate is the value that maximizes it. Products of many small numbers underflow, so in practice we maximize the log-likelihood, a sum, which has the same maximizer because log is increasing. Minimizing cross-entropy, and minimizing squared error under Gaussian noise, are both MLE in disguise. With little data MLE overfits: after three heads in three flips it estimates heads with probability 1. Adding a prior gives MAP estimation, which acts as regularization.
MLE finds parameters that make the observed data most probable. Taking the log turns the product into a sum — minimizing negative log-likelihood is equivalent to minimizing cross-entropy loss.
Coin flipped 10 times: 7 heads, 3 tails. Find MLE for p(heads)
Expectation
The expectation is the long-run average of a random variable: each possible value is weighted by its probability , summed for discrete variables and integrated against the density for continuous ones. It need not be a value the variable can actually take. Expectation is linear, and , even for dependent variables, which makes it easy to compute. Training minimizes expected loss over the data distribution, estimated by an average over a mini-batch. The trap is nonlinearity: generally differs from , and the gap between and is exactly the variance.
is the probability-weighted average. In reinforcement learning, the expected return is exactly what the agent maximizes. Linearity of expectation () holds even for dependent variables.
A die pays X dollars for rolling X. Find the expected payout.
Theory Exercise
Problem:
Given a coin that lands heads with probability p=0.6, what is the probability of getting exactly 2 heads in 3 flips? What is the expected number of heads?
Hints:
- Use the binomial distribution: P(k heads) = C(n,k) * p^k * (1-p)^(n-k)
- Expected value for binomial: E[X] = n*p
Coding Exercise
Problem:
Draw samples from a normal distribution, estimate the mean and variance from the samples, and compare to the true parameters. Then implement the Gaussian PDF from scratch and verify it integrates to ~1, and compute the empirical covariance of two correlated variables.
Hints:
- Use np.random.normal(mu, sigma, size) and estimate mean with np.mean, variance with np.var.
- The Gaussian PDF is (1/(sigma*sqrt(2*pi))) * exp(-((x-mu)**2)/(2*sigma**2)).
- Build a correlated variable as y = x + noise, then use np.cov / np.corrcoef to inspect the covariance and correlation.
Related Problems on PixelBank
A classifier predicts 70 percent cat, 20 percent dog, and 10 percent fox for a photo that really shows a cat. How wrong is that? Accuracy only records whether the top guess was right, which ignores confidence and gives no useful gradient. Likewise, a compression tool needs to know how many bits a message really requires, and a VAE needs to measure how far its learned distribution has drifted from a prior. Each case needs a number for surprise, or for the mismatch between two distributions.
The previous topic, Probability & Statistics, gave us distributions and likelihoods. Information theory, founded by Claude Shannon in 1948, measures them. The information in an outcome is its surprise, the negative log of its probability. Entropy is the average surprise of a distribution, cross-entropy is the average surprise when you code with the wrong distribution, and KL divergence is the extra cost of that mistake. These three quantities are the standard classification loss, the VAE regularizer, and the knowledge-distillation objective.
We define entropy, cross-entropy, KL divergence, and mutual information, sort out bits versus nats, and finish with binary cross-entropy, the loss behind logistic regression.
Definition
The entropy of a discrete distribution is , the expected surprise of an outcome. The cross-entropy is the expected surprise when outcomes drawn from are scored by a model , and the Kullback-Leibler divergence is the non-negative excess. With base-2 logarithms these quantities are measured in bits, and with natural logarithms in nats.
In this topic
- 1Entropy
- 2Cross-Entropy
- 3KL Divergence
- 4Mutual Information
- 5Bits vs Nats
- 6Binary Cross-Entropy
Entropy
Entropy measures how unpredictable a distribution is. Each outcome carries surprise : a certain event carries none, and a one-in-a-million event carries a lot. Entropy averages this surprise, weighting each outcome by its probability . With base-2 logs it is the minimum average number of bits per symbol that any lossless code can achieve, Shannon's source coding theorem. It is zero for a deterministic outcome and largest, bits for outcomes, for the uniform distribution. Outcomes with zero probability contribute nothing, since tends to 0, so code must guard against evaluating log 0 directly.
measures average surprise. A uniform distribution over outcomes has maximum entropy ; a deterministic outcome has entropy 0. High-entropy latent spaces in VAEs encourage diverse generation.
Calculate entropy for p = [0.25, 0.25, 0.25, 0.25] vs p = [0.97, 0.01, 0.01, 0.01]
Cross-Entropy
Cross-entropy scores a model distribution against the true distribution . It averages the surprise that the model assigns to each outcome, weighted by how often that outcome really occurs, . It is never smaller than the entropy , and it equals only when . For classification with a one-hot label, every term vanishes except the true class, so the loss is simply the negative log-probability the model gives to the correct answer. Minimizing it over a dataset is maximum likelihood. If the model gives the true class probability 0, the loss is infinite, which is why implementations clip probabilities or work with logits.
measures the cost of encoding data from distribution using a code designed for . Minimizing cross-entropy loss pushes the model distribution toward the true distribution — it's the standard classification objective.
True labels p=[1,0,0], model predicts q=[0.7,0.2,0.1]. Find cross-entropy loss.
KL Divergence
KL divergence measures the extra cost of describing data from with a model . The formula shows it equals the cross-entropy minus the entropy , which no model can remove. It is always at least 0 and equals 0 only when , so it behaves like a distance, but it is not one, because it is asymmetric. The forward direction heavily penalizes a that puts low probability where has mass, while the reverse direction penalizes for mass where has none. When is fixed, minimizing KL and minimizing cross-entropy are equivalent. VAEs, knowledge distillation, and RLHF penalties all use it.
. It's the extra bits needed when using instead of . KL is asymmetric: — mode-seeking vs mode-covering behavior in variational inference.
p=[0.5,0.5], q=[0.9,0.1]. Calculate D_KL(p||q)
Mutual Information
Mutual information measures how much learning one variable tells you about another. The first form says is the entropy of minus its conditional entropy , the uncertainty that remains once is known. The second says it is the KL divergence between the joint distribution and the product of marginals , which is what the joint would be under independence. So it is symmetric, never negative, and zero exactly when and are independent. Unlike correlation, it detects nonlinear dependence. It is used for feature selection and in contrastive learning, where the InfoNCE loss bounds it from below.
measures how much knowing reduces uncertainty about . If , they are independent. Contrastive learning (InfoNCE) maximizes a lower bound on mutual information between augmented views.
X=Weather{sunny,rainy}, Y=Umbrella{yes,no}. If umbrella perfectly predicts weather, find I(X;Y)
Bits vs Nats
The unit of entropy depends only on the base of the logarithm. Base 2 gives bits, the natural fit for binary codes; base gives nats. The conversion follows from : one bit is nats, and one nat is bits, as the formula states. Machine-learning libraries use natural logs, because the derivative of is simply and softmax is defined with the exponential. So a cross-entropy loss printed by PyTorch is in nats. A common mistake is to compare a loss in nats with a compression rate or benchmark figure reported in bits.
Using gives bits; using gives nats; nat bits. In ML we use natural log (nats) because produces cleaner gradients — a computational convenience, not a theoretical necessity.
Convert 2 bits to nats
Binary Cross-Entropy
Binary cross-entropy is cross-entropy for two classes. The label is 0 or 1, and the model outputs , the predicted probability of class 1, usually through a sigmoid. When only the first term survives, giving a loss of ; when only the second survives, giving . The loss is near 0 for confident correct predictions and grows without bound for confident wrong ones. Combined with a sigmoid, its gradient with respect to the logit is simply . Implementations should use the logit form, such as BCEWithLogitsLoss, because computing for near 1 loses precision.
is cross-entropy for a Bernoulli distribution. When , only contributes — the loss is the negative log-probability assigned to the correct class, penalizing confident wrong predictions exponentially.
True y=1, model predicts ŷ=0.9. Then y=1, ŷ=0.1. Compare losses.
Theory Exercise
Problem:
Calculate the entropy of a fair coin (p=0.5) and a biased coin (p=0.9). Which has higher entropy and why?
Hints:
- Use H = -[p log₂(p) + (1-p) log₂(1-p)]
- For p=0.5: both terms are equal
- Higher entropy means more uncertainty
Coding Exercise
Problem:
Implement Shannon entropy, cross-entropy, and KL divergence from scratch for two discrete distributions p and q. Verify KL is non-negative, that KL(p‖q) = cross_entropy(p,q) - entropy(p), and demonstrate KL's asymmetry.
Hints:
- Entropy is -sum(p * log(p)); use log base 2 for bits or natural log for nats.
- KL(p‖q) = sum(p * log(p/q)); add a tiny epsilon or mask zeros to avoid log(0).
- Cross-entropy is -sum(p * log(q)); confirm KL(p‖q) = H(p,q) - H(p) and that swapping p and q changes the KL value.
Related Problems on PixelBank
A network with 100 million weights has just produced a cross-entropy loss of 2.3, and training must decide how to change every one of those weights to make that number smaller. Trying random changes is hopeless in so many dimensions. What we need is local information: for each weight, which direction lowers the loss and how strongly. Calculus provides exactly that, and it is cheap enough to compute for every parameter at every step.
The previous topic, Information Theory, defined the loss functions we want to minimize. This topic supplies the machinery to minimize them. The derivative gives the slope of a function of one variable. The gradient collects the partial derivatives of a function of many variables into a vector that points uphill most steeply, and gradient descent steps the other way. The chain rule differentiates compositions of layers, which is all backpropagation is. Second derivatives, gathered in the Hessian matrix, describe curvature, and convexity tells us when a local minimum is also the global one.
We move from derivatives to gradients, gradient descent, and the chain rule, then to the Hessian, convexity, and Taylor expansion, the approximation behind both gradient descent and Newton's method.
Definition
The gradient of a differentiable function is the vector of partial derivatives . It points in the direction of steepest increase, and its length is that rate of increase. Gradient descent minimizes by repeatedly stepping against the gradient. The Hessian, the matrix of second partial derivatives, describes the local curvature that governs how quickly those steps converge.
In this topic
- 1Derivative (Gradient)
- 2Gradient Vector
- 3Gradient Descent
- 4Chain Rule
- 5Hessian Matrix
- 6Convexity
- 7Taylor Expansion
Derivative (Gradient)
The derivative measures the rate of change of at point . Geometrically, it's the slope of the tangent line.
- Positive derivative: Function is increasing
- Negative derivative: Function is decreasing
- Zero derivative: Local minimum or maximum (critical point)
Common Derivative Rules:
- Power rule:
- Product rule:
- Quotient rule:
Second Derivative: measures curvature. At critical points:
- : Local minimum (concave up)
- : Local maximum (concave down)
- : Inflection point or saddle point
The derivative is the slope of the tangent line — the instantaneous rate of change. Setting it to zero finds extrema. In ML, the gradient of the loss with respect to each weight tells you exactly how to adjust that weight to reduce error.
Find the derivative of the MSE loss with respect to .
Gradient Vector
The gradient generalizes the derivative to multiple variables. For :
- points in the direction of steepest increase
- gives the rate of steepest increase
- points toward steepest decrease
Directional Derivative: Rate of change in direction :
The Hessian Matrix: Matrix of second partial derivatives:
Eigenvalues of the Hessian reveal curvature: all positive = minimum, all negative = maximum, mixed = saddle point.
Image Gradients: Sobel/Prewitt operators compute discrete gradients. Edge magnitude and direction are fundamental to edge detection.
points in the direction of steepest ascent. Its magnitude indicates how steep. Moving opposite to the gradient () is the fastest local decrease — the core idea behind all gradient-based optimizers.
Find the gradient of at point .
Gradient Descent
Gradient descent iteratively minimizes a function by taking steps opposite to the gradient:
- (learning rate): Step size—too large causes overshooting, too small is slow
- Convergence: Stops when gradient is near zero (found a minimum)
- Local vs global: May find local minimum, not global
Variants Used in Deep Learning:
- SGD: Use mini-batch gradients for efficiency
- Momentum: Accumulate velocity to escape local minima
- Adam: Adaptive learning rates per parameter
- AdaGrad/RMSprop: Scale learning rate by historical gradients
Learning Rate Schedules: Start large for fast progress, decay over time for fine convergence. Common: step decay, cosine annealing, warmup.
Convergence Guarantees: For convex functions with Lipschitz gradients, GD converges at rate . Adding momentum can achieve .
iteratively steps downhill. The learning rate controls step size: too large overshoots, too small converges slowly. Adam combines momentum (exponential moving average of gradients) with adaptive per-parameter rates.
One step of gradient descent on from with .
Chain Rule
The chain rule handles derivatives of composed functions. If , then:
Multivariate Chain Rule: For where , :
Backpropagation: Neural networks are compositions of layers. For loss :
Automatic Differentiation: Modern frameworks (PyTorch, JAX) implement the chain rule automatically by building a computational graph and propagating gradients backward through it.
decomposes derivatives through composed functions. Backpropagation is the chain rule applied layer by layer — it computes all gradients in time rather than with finite differences.
Find where is sigmoid.
Hessian Matrix
The Hessian collects every second partial derivative of : entry measures how the slope along changes as you move along . For smooth functions the order of differentiation does not matter, so is symmetric and has real eigenvalues, one curvature per principal direction. At a critical point, where the gradient is zero, all positive eigenvalues mean a local minimum, all negative a maximum, and mixed signs a saddle. The ratio of largest to smallest eigenvalue, the condition number, predicts how badly gradient descent zig-zags. Newton's method steps by , but with parameters has entries, which is prohibitive for large networks.
captures curvature. Positive-definite Hessian means a local minimum; negative-definite means a local maximum. Saddle points (mixed signs) are common in high-dimensional loss landscapes and are the real obstacle, not local minima.
Find Hessian of f(x,y) = x² + xy + y²
Convexity
A function is convex when the chord between any two points on its graph lies on or above the graph. In the formula, a weight between 0 and 1 picks the point on the segment from to , and the inequality says the function value there is at most the same mixture of and . The payoff is that every local minimum is global, so gradient descent cannot get stuck in a bad valley. For twice-differentiable functions, convexity is equivalent to a positive semi-definite Hessian everywhere. Least squares and logistic regression are convex; neural network losses are not, which is why their training depends on initialization.
A function is convex if the line segment between any two points on the graph lies above the graph. Convex loss functions have a single global minimum — no local minima traps. Linear regression loss is convex; deep network loss is not, which is why initialization and learning rate matter.
Is f(x) = x² convex? Check at x=0, y=2, λ=0.5
Taylor Expansion
Taylor expansion replaces a complicated function near a point with a polynomial built from its derivatives there. In the formula, is a small step, is the first-order change predicted by the gradient, and is the second-order correction from the Hessian . Gradient descent trusts only the linear term, which is why its steps must stay small. Newton's method minimizes the quadratic model exactly, giving the step . The approximation error grows with the step size, roughly like the cube of the step for the second-order version, so the model is only reliable locally.
approximates a function locally. First-order approximation (gradient descent) ignores curvature. Newton's method uses the second-order term (Hessian) for better steps but is in memory.
Approximate f(x) = eˣ near x=0 using first 3 Taylor terms
Theory Exercise
Problem:
Use gradient descent to minimize f(x) = x² starting from x₀ = 3 with learning rate α = 0.1. Show the first 5 iterations.
Hints:
- Derivative: f'(x) = 2x
- Update rule: x_new = x - α × f'(x)
- Should converge toward x = 0 (the minimum)
Coding Exercise
Problem:
Minimize the quadratic f(x) = 0.5 * xᵀ A x - bᵀ x by implementing gradient descent from scratch, where the gradient is A x - b. Compare the converged solution to the closed-form minimum x* = A⁻¹ b, and verify the gradient is near zero at the optimum.
Hints:
- The gradient of f(x) = 0.5 xᵀAx - bᵀx is grad = A @ x - b (for symmetric A).
- Update rule: x = x - lr * grad; pick a small learning rate so it converges rather than diverges.
- The exact minimizer is x* = np.linalg.solve(A, b); the gradient there should be ~0.
Related Problems on PixelBank
A streaming service stores a ratings matrix with 100 million users and 50,000 films. Almost all of it is missing and what is present is noisy, yet the service must predict the missing entries, compress the rest, and solve linear systems with it. Working entry by entry is hopeless. The practical move is to rewrite the matrix as a product of a few simpler factors, triangular, orthogonal, or diagonal, that expose its structure and make each task cheap.
The previous topic, Calculus for Optimization, used Hessians and closed-form solutions that require solving linear systems. Matrix decompositions are how those systems are actually solved. The singular value decomposition writes any matrix as a rotation, a scaling, and another rotation, and truncating it gives the best low-rank approximation, the idea behind recommender systems, latent semantic analysis, and LoRA. LU factorization reduces a square system to two triangular ones, QR does the same with an orthogonal factor for stable least squares, and Cholesky halves the work for symmetric positive definite matrices.
We cover the SVD, truncated SVD, and singular values first, then LU, QR, and Cholesky, with the cost and stability trade-offs that decide which one to use.
Definition
A matrix decomposition writes a matrix as a product of simpler factors. The singular value decomposition exists for every real matrix, with orthogonal and and a diagonal of non-negative singular values. LU, QR, and Cholesky factor a matrix into triangular or orthogonal pieces, which turns one hard linear system into a sequence of easy triangular solves.
In this topic
- 1Singular Value Decomposition (SVD)
- 2Truncated SVD
- 3Singular Values
- 4LU Decomposition
- 5QR Decomposition
- 6Cholesky Decomposition
Singular Value Decomposition (SVD)
The SVD says every matrix, of any shape or rank, acts in three steps. In , the orthogonal rotates the input into a special basis, the right singular vectors; the diagonal scales each axis by a singular value , sorted from largest to smallest; and the orthogonal rotates the result into the output space, whose basis is the left singular vectors. The number of nonzero singular values is the rank. Unlike eigendecomposition, the SVD always exists and always uses orthonormal bases. It yields the pseudoinverse, the condition number, and the best low-rank approximations, which is why it is often called the most useful decomposition.
factors any matrix into rotation (), scaling (), and rotation (). The singular values in are ordered by importance — keeping only the top gives the best rank- approximation (Eckart-Young theorem), which is the basis of data compression.
For a 3×2 matrix A, what are the dimensions of U, Σ, and V?
Truncated SVD
Truncation keeps only the largest singular values and their singular vectors: holds the first columns of , the top values, and the first columns of . The Eckart-Young theorem guarantees that is the best possible rank- approximation in both the Frobenius and spectral norms, and the Frobenius error equals the square root of the sum of the discarded . Storage falls from numbers to . Latent semantic analysis, image compression, and recommender systems all rely on it. It only pays off when the singular values decay quickly; a flat spectrum leaves nothing to discard.
Keeping only the top singular values gives , the closest rank- matrix to in Frobenius norm. Latent Semantic Analysis uses truncated SVD on term-document matrices to discover topics — the discarded dimensions are noise.
A 1000×500 matrix with σ = [100,50,10,1,...]. Keep k=2. What's compression ratio?
Singular Values
The singular values are the scaling factors in the SVD, and the formula computes them as square roots of the eigenvalues of , a symmetric positive semi-definite matrix, so they are real and non-negative. Geometrically, maps the unit sphere to an ellipsoid whose semi-axis lengths are the singular values. Three facts make them useful. The largest, , is the spectral norm, the maximum stretch. The sum of all equals the squared Frobenius norm, so each is a share of the energy. The ratio of largest to smallest is the condition number. Singular values equal eigenvalues only for symmetric positive semi-definite matrices.
Singular values measure the 'stretch' along each principal direction. A rapid drop-off means the matrix is effectively low-rank — most information lives in a few dimensions. The condition number measures numerical sensitivity.
Singular values are [10, 5, 1]. What % of energy is in top 2 components?
LU Decomposition
LU factorization records Gaussian elimination. The lower-triangular stores the multipliers used to eliminate entries below each pivot, with ones on its diagonal, and the upper-triangular is the resulting echelon form, so . Factoring costs about operations, but afterwards each new right-hand side needs only a forward solve and a back solve , about operations. The determinant comes free as the product of the diagonal of . A zero or tiny pivot breaks the plain version, so libraries use partial pivoting, , swapping rows to bring the largest entry into pivot position.
factors a matrix into lower-triangular and upper-triangular . Solving becomes two cheap triangular solves: (forward) then (back). This is how numpy.linalg.solve works internally.
Solve Ax=b for 1000 different b vectors. Why use LU?
QR Decomposition
QR factorization writes , where has orthonormal columns and is upper triangular. It is Gram-Schmidt orthogonalization recorded as matrices, though libraries compute it with Householder reflections for stability. Its main use is least squares: because multiplying by preserves lengths, minimizing reduces to solving the triangular system . Unlike the normal equations, it never forms , whose condition number is the square of that of , so it keeps roughly twice as many correct digits on ill-conditioned problems. Repeated QR steps also form the QR algorithm, the standard way to compute all eigenvalues.
factors into orthogonal and upper-triangular . Because preserves lengths, QR is numerically stable for solving least squares: . Gram-Schmidt orthogonalization is the classic way to compute QR.
Solve least squares ||Ax-b||² using QR
Cholesky Decomposition
for positive definite
Cholesky factorization writes a symmetric positive definite matrix as , with lower triangular and a positive diagonal. It is a specialized LU that exploits symmetry, needing about operations, half the cost of LU, and no pivoting. It is also the cheapest test of positive definiteness, because the algorithm needs the square root of a positive number at every step and fails otherwise. Gaussian processes use it to solve with kernel matrices and to compute log-determinants, and it turns independent standard normal samples into correlated ones. Nearly singular covariance matrices can fail through rounding, so a small jitter such as is often added.
works only for symmetric positive-definite matrices. It's twice as fast as LU because it exploits symmetry. Gaussian processes use Cholesky to sample from multivariate normals and compute log-determinants efficiently.
Sample from N(0,Σ) where Σ=[[4,2],[2,3]]
Theory Exercise
Problem:
Why is truncated SVD useful for dimensionality reduction? If a 1000×500 matrix has singular values [100, 50, 10, 1, 0.1, ...], how many components would you keep?
Hints:
- Singular values indicate importance of each component
- Large gap in singular values suggests natural cutoff
- Keeping components with small σ adds noise
Coding Exercise
Problem:
Compute the full SVD of a random matrix and reconstruct it from U, S, Vᵀ to confirm A = U S Vᵀ. Then form a truncated rank-k approximation using the top singular values and report the reconstruction error, observing how it shrinks as k grows.
Hints:
- Use np.linalg.svd(A, full_matrices=False) to get U, s (a 1D array of singular values), and Vt.
- Reconstruct the full matrix as U @ np.diag(s) @ Vt; it should equal A.
- For rank-k, keep only the first k columns of U, first k singular values, and first k rows of Vt; the Frobenius error decreases as k increases.
Related Problems on PixelBank
A dataset of face images has 10,000 pixels per image, yet faces clearly vary in far fewer ways: lighting, pose, expression, identity. How can we find those few directions of variation automatically? A related question arises when a matrix is applied again and again, as in PageRank's random surfer or a recurrent network's hidden state: which directions grow, which die out, and which stay put? Both questions have the same answer, found by looking for the directions that a matrix only stretches and never turns.
The previous topic, Matrix Decompositions, factored matrices into triangular and orthogonal pieces and introduced the SVD. This topic turns to the eigendecomposition. An eigenvector is a direction that a matrix maps onto itself, scaled by its eigenvalue. For symmetric matrices, such as covariance matrices, the eigenvalues are real and the eigenvectors orthogonal, and that fact underlies principal component analysis: the top eigenvectors of the data's covariance matrix are its directions of greatest variance.
We define eigenvectors, compute them from the characteristic equation, and use them to decompose matrices. Then we build PCA step by step, from symmetric and covariance matrices to variance explained.
Definition
A nonzero vector is an eigenvector of a square matrix with eigenvalue if , so the matrix only scales it. The eigenvalues are the roots of the characteristic equation . Principal component analysis projects centered data onto the eigenvectors of its covariance matrix with the largest eigenvalues, which are the directions along which the data varies most.
In this topic
- 1Eigenvector Definition
- 2Characteristic Equation
- 3Eigendecomposition
- 4Symmetric Matrices
- 5Covariance Matrix
- 6Principal Component Analysis (PCA)
- 7Variance Explained
- 8Spectral Theorem
Eigenvector Definition
An eigenvector of matrix is a special vector that, when transformed by , only gets scaled (not rotated). The scale factor is the eigenvalue.
Intuition: Eigenvectors are the 'natural axes' of a transformation—directions that remain unchanged except for stretching/compression.
Key Properties:
- Eigenvectors are defined up to scalar multiples: if is an eigenvector, so is
- The zero vector is never an eigenvector (by definition)
- Different matrices can share eigenvectors but have different eigenvalues
Geometric Interpretation: If you apply transformation repeatedly, most vectors will align with the eigenvector having the largest eigenvalue (this is the power iteration algorithm).
means only gets scaled (by ) when transformed by — its direction is unchanged. Eigenvectors reveal the 'natural axes' of a transformation. In PCA, the eigenvectors of the covariance matrix are the directions of maximum variance.
Verify that is an eigenvector of .
Characteristic Equation
To find eigenvalues, solve the characteristic equation. For a 2×2 matrix:
This gives a polynomial equation in . The roots are the eigenvalues.
Useful Formulas for 2×2:
- Sum of eigenvalues = trace() =
- Product of eigenvalues = det() =
Eigenvalue Types:
- Real & distinct: Two independent eigenvector directions
- Real & repeated: May have fewer independent eigenvectors
- Complex conjugates: Rotation without pure scaling (e.g., rotation matrices)
Finding Eigenvectors: Once you have , solve for . This is a homogeneous system with non-trivial solutions.
is a polynomial whose roots are the eigenvalues. For an matrix, this is a degree- polynomial with exactly roots (counting multiplicity, over ). In practice, eigenvalues are computed iteratively (QR algorithm), not by solving polynomials.
Find eigenvalues of using trace and determinant shortcuts.
Eigendecomposition
If has n linearly independent eigenvectors, it can be decomposed as:
- : Matrix whose columns are eigenvectors
- : Diagonal matrix of eigenvalues
Why This Matters:
- Matrix powers: — just raise diagonal elements to power
- Matrix exponential: — used in differential equations
- Understanding transformations: Decomposition reveals the fundamental structure
Applications in CV/ML:
- PCA: Eigenvectors of covariance matrix are principal components
- Image compression: Keep top- eigenvectors, discard rest
- Eigenfaces: Face recognition using eigenvectors of face covariance
- Graph Laplacian: Eigenvectors enable spectral clustering
- PageRank: Dominant eigenvector of link matrix
expresses as a change of basis (), a diagonal scaling (), and a change back (). This makes computing trivial — just raise each eigenvalue to the th power. Markov chain steady states are the eigenvector for .
Using eigendecomposition, compute for .
Symmetric Matrices
Symmetric matrices (like covariance matrices) have special properties:
- All eigenvalues are real (not complex)
- Eigenvectors for different eigenvalues are orthogonal
- Can always be diagonalized: where is orthogonal
Spectral Theorem: Every symmetric matrix has an orthonormal basis of eigenvectors. This is the mathematical foundation of PCA.
Positive Definite Matrices: A symmetric matrix is positive definite if all eigenvalues are positive (). This means:
- for all non-zero
- Covariance matrices are always positive semi-definite
- Guarantees unique minimum in quadratic optimization
Connection to SVD: For any matrix , is symmetric positive semi-definite. Its eigenvectors are the right singular vectors of .
Symmetric matrices () have all real eigenvalues and orthogonal eigenvectors. The covariance matrix is always symmetric positive semi-definite, which guarantees PCA produces real, non-negative eigenvalues and perpendicular principal components.
Verify that eigenvectors of symmetric are orthogonal.
Covariance Matrix
The covariance matrix collects every pairwise covariance of a dataset in one symmetric matrix. In the formula, holds samples as rows and features as columns, subtracting removes each column's mean, and multiplying the centered data's transpose by itself sums the cross-products, which are then divided by for an unbiased estimate. Diagonal entries are the variances of individual features, and the off-diagonal entry is the covariance of features and . The matrix is always positive semi-definite, so its eigenvalues are non-negative and its eigenvectors orthogonal. Forgetting to center the data is the classic bug, because the means then leak into every entry.
captures pairwise linear relationships. Diagonal entries are variances; off-diagonal are covariances. Whitening data (decorrelation + unit variance) transforms into the identity matrix.
Data: X=[[1,2],[3,4],[5,6]]. Find covariance matrix.
Principal Component Analysis (PCA)
PCA finds the directions along which data varies most and keeps only those. First, center the data by subtracting each feature's mean. Second, compute the covariance matrix. Third, find its eigenvectors and sort them by eigenvalue: these are the principal components, and each eigenvalue is the variance of the data along its component. Finally, project the data onto the top components, reducing each sample to numbers. Because the components are orthogonal, the projected features are uncorrelated. Features on different scales must be standardized first, or the one with the largest units dominates. PCA captures only linear structure, so curved manifolds need methods such as kernel PCA.
PCA finds orthogonal directions that maximize variance: the first PC captures the most variance, the second captures the most remaining variance perpendicular to the first, and so on. Mathematically, PCs are eigenvectors of sorted by eigenvalue. It's equivalent to truncated SVD on centered data.
100-dim data, eigenvalues λ=[50,30,10,5,3,1,1,...]. How many components to keep for 90% variance?
Variance Explained
Each principal component's eigenvalue is the variance of the data along that component, and the eigenvalues add up to the total variance, the trace of the covariance matrix. The explained variance ratio divides one eigenvalue by that total, giving the fraction of spread the component captures. Summing the ratios of the top components gives the cumulative share, and the usual rule is to choose the smallest that reaches a target such as 90 or 95 percent. A scree plot of the eigenvalues shows the same information; look for the elbow where the curve flattens. Scikit-learn exposes the ratios as the attribute explained_variance_ratio_ after fitting.
The ratio tells you what fraction of total variance the th component captures. Cumulative explained variance guides dimensionality reduction: if the top 10 of 1000 components capture 95% of variance, the remaining 990 dimensions are mostly noise.
Eigenvalues [4, 2, 1, 0.5]. What % does each PC explain?
Spectral Theorem
for symmetric
The spectral theorem guarantees that symmetric matrices have the best possible eigenstructure. For a real matrix with , all eigenvalues are real and there is an orthonormal basis of eigenvectors, so with orthogonal and diagonal , and no inverse needs computing, since . Read the product as rotating into the eigenvector basis, scaling each axis by its eigenvalue, and rotating back. Covariance matrices are symmetric, which is exactly why principal components are orthogonal and projected features uncorrelated. Non-symmetric matrices lose these guarantees: they can have complex eigenvalues, non-orthogonal eigenvectors, or too few eigenvectors to diagonalize.
Every real symmetric matrix can be written with orthogonal and diagonal . This guarantees that symmetric matrices are diagonalizable with real eigenvalues. The spectral theorem is why PCA works: the covariance matrix always admits a clean eigendecomposition.
Why is spectral theorem important for PCA?
Theory Exercise
Problem:
Find the eigenvalues and eigenvectors of A = [[3, 1], [1, 3]].
Hints:
- det(A - λI) = 0 gives characteristic polynomial
- For 2×2: λ² - trace(A)λ + det(A) = 0
- trace(A) = 6, det(A) = 8
Coding Exercise
Problem:
Apply PCA to reduce the Iris dataset from 4 dimensions to 2, then plot the result colored by class.
Hints:
- Use PCA from sklearn.decomposition
- Use matplotlib.pyplot for plotting