Chapter 5: Linear Algebra
The mathematical language of AI: vector spaces, orthogonality, projections, least squares, spectral decomposition, and numerical methods — with direct connections to embeddings, PCA, transformers, and training stability.
- Topics
- 8
- Videos
- 8
- Min read
- 49
Chapter Overview
This chapter takes you beyond basic matrix operations into the structural theory of linear algebra — the mathematical language that powers modern AI. You will learn about vector spaces (the home of embeddings and latent representations), orthogonal projections (the engine behind attention mechanisms and PCA), least squares and the pseudoinverse (the foundation of linear regression and linear probing), spectral decomposition (used in PCA, SVD, LoRA, and graph neural networks), and numerical stability (critical for mixed-precision training with FP16/BF16).
Every major AI concept maps to linear algebra: PCA is eigendecomposition of the covariance matrix. Attention is softmax-weighted projection. LoRA exploits low-rank structure. Batch normalization decorrelates features. Gradient descent navigates curvature described by the Hessian's eigenvalues. Understanding these connections will make every AI system more transparent.
Chapter Roadmap
Click any topic to jump in
Linear Spaces
Vector spaces, subspaces, span — the abstract structure underlying all of linear algebra.
Independence & Basis
Linear independence, basis, dimension — minimal sets that generate entire spaces.
Range, null space, and projection
Null & Column Space
Four fundamental subspaces and rank-nullity — what a matrix can and cannot reach.
Orthogonality
Projections onto subspaces and orthogonal complements — the geometry of least squares.
Orthogonalization and system solving
Gram-Schmidt & QR
Orthogonalizing bases and QR factorization — numerically stable linear system solving.
Least Squares
Normal equations, pseudoinverse, linear regression — solving overdetermined systems.
Eigenstructure and numerical reality
Spectral Theory
Spectral theorem, quadratic forms, positive definiteness — eigenvalue structure governing optimization.
Numerical Methods
Condition numbers, floating-point, iterative solvers, sparse matrices — practical computation at scale.
Topics
8 topics in this chapter
A sentence encoder turns "cat" and "kitten" into lists of 768 numbers, and a retrieval system then averages, subtracts, and rescales those lists without a second thought. Why is that allowed? Why does the average of two embeddings still count as an embedding, while the average of two phone numbers means nothing at all? The answer has little to do with the numbers themselves. It depends on which operations the collection is closed under, meaning which operations can never carry you outside it.
The previous chapter, Probability & Statistics, treated data as random vectors and summarized them with means and covariance matrices. Both summaries quietly assumed that vectors can be added and scaled. This topic makes that assumption explicit. A vector space is any collection in which adding and scaling never leave the collection, and that one idea covers arrows in the plane, polynomials, images, and weight tensors alike.
We start with the axioms that define a vector space, then carve out subspaces, the flat self-contained pieces through the origin, and finish with span, the set of everything reachable from a handful of vectors.
Definition
A vector space over the real numbers is a set with an addition and a scalar multiplication such that and stay in for all and every real , and eight axioms hold: associativity and commutativity of addition, a zero vector, additive inverses, two distributive laws, compatible scaling, and . A subspace is a nonempty subset closed under both operations.
In this topic
- 1Vector Space Axioms
- 2Subspaces
- 3Span
Vector Space Axioms
Why list axioms at all? The algorithms of linear algebra, such as elimination, projection, and eigen-decomposition, only ever add and scale, so any set obeying the same rules inherits every theorem for free. In the formula, is the set, and are elements, and is a real scalar. Closure says both operations stay inside . The eight axioms add associativity, commutativity, a zero vector, additive inverses, identity scaling, compatibility , and two distributive laws. The failure modes are subtle. Vectors with positive entries look like a space but lack inverses, and probability vectors fail too, because the sum of two has entries adding to 2.
The axioms guarantee that linear combinations always land back in the same space. In ML, this means any weighted average of word embeddings (a linear combination) remains a valid embedding — the representation space is closed under the operations models actually perform.
Show that the set of all 2×2 matrices forms a vector space.
Subspaces
Most useful sets in machine learning sit inside a bigger space: the plane of vectors orthogonal to a normal, the solutions of a homogeneous system, the outputs a layer can produce. A subspace of is such a subset that is a vector space in its own right. Because it inherits the axioms from , you only check three things: , closure under addition, and closure under scaling. Lines and planes through the origin in qualify. The classic failure is an offset: the line misses the origin, and adding two of its points leaves the line. Solutions of always form a subspace, the null space.
A subspace is a self-contained linear world within a larger space. The set of all vectors satisfying is always a subspace (the null space), which is why solutions to homogeneous systems form clean geometric objects (lines, planes) through the origin rather than scattered point clouds.
Span
The span of a set of vectors is the set of all possible linear combinations. It is always a subspace. Two non-parallel vectors in span a plane; three independent vectors span all of . The span tells you what you can 'reach' using only addition and scaling of the given vectors. In AI, the span of a set of word embeddings defines the 'concepts' that can be expressed as mixtures of those words.
The span of vectors is the smallest subspace containing them — it is the set of all reachable points via linear combination. In latent space, the span of a few concept vectors (e.g., 'king', 'queen') defines the subspace of expressible meanings. Adding a vector outside the span increases dimension by exactly one.
Theory Exercise
Problem:
Is the set S = {(x, y, z) ∈ R³ : x + 2y - z = 0} a subspace of R³?
Hints:
- Check if (0,0,0) satisfies the equation.
- Take two arbitrary vectors in S and check if their sum is also in S.
Coding Exercise
Problem:
Verify numerically that a set is a subspace and check closure. Given the plane W = {(x, y, z) : x + 2y - z = 0} in R^3, write a membership test, confirm the zero vector belongs, and demonstrate closure by checking that random linear combinations of vectors in W stay in W. Also show a vector NOT on the plane fails the test.
Hints:
- A vector v is in W iff np.dot([1, 2, -1], v) is approximately 0.
- Generate vectors in W by picking x, y freely and setting z = x + 2y.
- Use np.isclose for the floating-point comparison.
The previous topic showed that the span of a few vectors is everything they can reach. Span alone is wasteful, though. The vectors (1, 0), (0, 1), and (1, 1) span the plane, yet the third adds nothing the first two could not already build, and a point such as (2, 3) now has infinitely many recipes. If a feature vector can be written several ways, which coefficients are the real features? Redundancy also costs memory and hides structure, as when two neurons in a layer compute scaled copies of the same response.
This topic asks for the smallest set of vectors that still reaches everything. Linear independence is the test for redundancy: no vector in the set is a combination of the others. A basis is an independent spanning set, and its size, the dimension, turns out to be the same for every basis of the space. That invariant is exactly what a phrase like "768-dimensional embedding" means.
We begin with independence and its rank test, then define basis and dimension, and close with coordinates, the unique address every vector receives once a basis is fixed.
Definition
Vectors are linearly independent when forces every coefficient to be zero. A basis of a vector space is an independent set that also spans . Every basis of has the same number of elements, called the dimension of , and relative to a fixed basis each vector has exactly one list of coordinates.
In this topic
- 1Linear Independence
- 2Basis & Dimension
- 3Coordinates
Linear Independence
Independence formalizes the idea of no wasted vectors. The formula says the only way to combine with coefficients into the zero vector is to set every to zero. If some nontrivial combination gives zero, then any vector with a nonzero coefficient can be solved for in terms of the others, so it was redundant. In practice you stack the vectors as the columns of a matrix and check whether ; for a square matrix, is equivalent. In at most vectors can be independent. Floating point blurs the test, because nearly dependent columns make the rank depend on the tolerance.
Independence means no vector is wasted — each adds a genuinely new direction. Testing independence reduces to checking if (square case) or (general case). In neural networks, redundant neurons (linearly dependent weight rows) waste parameters without increasing model capacity.
Basis & Dimension
Independence prevents redundancy and spanning guarantees reach, and a basis has both. In the formula, is the number of vectors in any basis of . The theorem behind it, the exchange lemma, says this count never depends on which basis you pick, so the dimension is well defined. The standard basis of uses , which has a 1 in slot and zeros elsewhere. For a subspace defined by equations, count the free variables: each one contributes one basis vector. A common mistake is to call any spanning set a basis. If it has more vectors than the dimension, it is dependent.
A basis is a maximally efficient coordinate system: every vector has a unique address. Dimension is an invariant — all bases have the same size. When a model uses 768-dimensional embeddings, it has exactly 768 independent directions for encoding meaning, regardless of which particular basis vectors are chosen.
Find a basis for the subspace W = {(x, y, z) : x - y + z = 0} of R³.
Coordinates
A basis turns abstract vectors into lists of numbers. Given a basis with vectors , the coefficients in the formula are the coordinates of , and independence makes them unique. To compute them, place the basis vectors in the columns of a matrix and solve . For an orthonormal basis this collapses to dot products, . Changing the basis changes the numbers, not the vector: PCA rewrites each data point in the eigenvector basis of the covariance matrix. The usual pitfall is mixing coordinates taken from two different bases, which silently compares incompatible numbers.
Coordinates are basis-dependent representations of a basis-independent object. PCA changes basis to align axes with maximum variance directions; the vector itself does not change, only its description. Understanding this distinction is critical: a CNN's feature extractor is a learned change of basis from pixel coordinates to semantically meaningful coordinates.
Theory Exercise
Problem:
Are the vectors v₁ = (1, 2, 3), v₂ = (4, 5, 6), v₃ = (7, 8, 9) linearly independent?
Hints:
- Form a matrix with these as columns and compute its determinant.
- If det = 0, the vectors are dependent.
Coding Exercise
Problem:
Test linear independence via matrix rank and recover basis coordinates. For the vectors v1=(1,2,3), v2=(4,5,6), v3=(7,8,9), determine whether they are independent using np.linalg.matrix_rank, expose the dependency, then for an independent basis express an arbitrary vector in that basis by solving B c = v.
Hints:
- Stack the vectors as columns; rank < number of columns means dependence.
- For the dependent trio, solve a least-squares system to find how v3 is built from v1 and v2.
- For an independent basis B, the coordinates of v are np.linalg.solve(B, v).
Related Problems on PixelBank
Suppose a linear layer maps 512 input features to 128 outputs through a weight matrix W. Two practical questions follow at once. Which outputs can this layer ever produce, whatever input it sees? And which changes to the input will it never notice, because W sends them to exactly zero? The same two questions decide whether a linear system Ax = b has a solution at all, and if it does, whether that solution is unique or one of infinitely many.
The previous topic gave us bases and dimension for any subspace. Here we apply those tools to the subspaces that a matrix creates. The column space collects every output Ax, and the null space collects every input that A sends to zero. Their dimensions, the rank and the nullity, are tied together by the rank-nullity theorem, a conservation law for the columns of A. Low rank is also the idea behind LoRA, which fine-tunes very large models by learning weight updates of small rank.
We study the column space first, then the null space, and finish with rank-nullity, which folds solvability and uniqueness into a single count.
Definition
For an matrix , the column space is the set of all products , which is the subspace of spanned by the columns of . The null space is the set of all in with . Their dimensions are called the rank and the nullity, and the two always add up to , the number of columns.
In this topic
- 1Column Space
- 2Null Space
- 3Rank-Nullity Theorem
Column Space
The column space answers the question of what a matrix can output. Writing as , where is column , shows that every output is a combination of the columns, so the column space is their span. Consequently is solvable if and only if lies in that span. Its dimension is the rank, the number of pivots found by row reduction, and the pivot columns of the original form a basis. A 3×2 matrix can reach at most a plane in , so most right-hand sides have no exact solution, which is the situation least squares will handle.
The column space is the image of the linear map . The equation is solvable exactly when . In a neural network layer , the column space of determines which output patterns are achievable — any output outside is impossible for that layer.
Null Space
The null space (or kernel) of is the set of all vectors that maps to zero. If the null space contains only the zero vector, then is injective (one-to-one), and solutions to are unique when they exist. A larger null space means more 'degrees of freedom' in the solution. In neural networks, the null space of a layer's weight matrix represents input directions that the layer ignores — understanding this helps diagnose vanishing gradients and dead neurons.
The null space contains all inputs that a matrix annihilates: . A nontrivial null space means multiple distinct inputs produce the same output ( whenever ). In autoencoders, the null space of the encoder represents information the bottleneck discards.
Rank-Nullity Theorem
Every column of ends up doing one of two jobs. Either it adds a new independent direction to the output, raising the rank, or it is a combination of earlier columns, which creates a free variable and one more dimension of null space. The theorem makes this bookkeeping exact: , where counts columns, not rows. The practical reading is simple. If the rank equals , the null space contains only the zero vector and solutions are unique; any shortfall in rank shows up as a family of solutions with that many dimensions. A frequent slip is subtracting the rank from the number of rows instead.
Rank-nullity means input splits into directions that produce output (column space preimage) and directions annihilated (null space). In ML, the null space represents directions along which features carry no information — rank deficiency in a weight matrix signals redundant parameters.
A 4×6 matrix has rank 3. What is the dimension of its null space?
Theory Exercise
Problem:
Find the null space and column space of A = [[1, 2, 3], [2, 4, 6]].
Hints:
- Row reduce A to echelon form.
- The pivot columns form a basis for the column space.
Coding Exercise
Problem:
Compute a basis for the null space of A = [[1, 2, 3], [2, 4, 6]] using the SVD, verify A @ (null basis) is zero, and confirm the rank-nullity theorem rank(A) + nullity(A) = number of columns.
Hints:
- The right singular vectors (rows of Vt) whose singular values are ~0 span the null space.
- np.linalg.svd returns U, s, Vt; count singular values above a tolerance to get the rank.
- Check A @ null_vectors is numerically zero and that rank + nullity equals n=3.
The previous topic ended with a sobering fact: when b lies outside the column space of A, the system Ax = b has no solution at all. Real data is almost always like that. Measurements carry noise, so a hundred observations of a line will not sit exactly on any line. We still want an answer, and the natural choice is the point of the reachable subspace that lies closest to b. How do we find that point, and how do we know it is the closest?
Orthogonality is the tool. Two vectors are orthogonal when their dot product is zero, and orthogonal directions behave independently: lengths add by Pythagoras, and coordinates can be read off one at a time. Dropping a perpendicular from b onto a subspace gives the closest point, the orthogonal projection, and the leftover error is perpendicular to everything in the subspace. That single picture underlies least squares, PCA, and the dot-product scores inside transformer attention.
We move from orthogonal vectors to projection onto a single vector, then onto a whole subspace through a projection matrix, and close with the orthogonal complement, which splits every vector into two perpendicular parts.
Definition
Vectors and are orthogonal when . The orthogonal projection of onto a subspace is the unique vector in for which is orthogonal to every vector of , and it is also the point of nearest to . The orthogonal complement of is the set of all vectors orthogonal to .
In this topic
- 1Orthogonal Vectors
- 2Projection onto a Vector
- 3Projection onto a Subspace
- 4Orthogonal Complement
Orthogonal Vectors
Orthogonality is the cleanest possible relationship between two directions. The formula says exactly when the dot product, the sum of , is zero; in two or three dimensions that means a right angle, because . For orthogonal vectors Pythagoras holds, so squared lengths simply add. A set of mutually orthogonal nonzero vectors is automatically independent: dot any combination equal to zero with , and every term except vanishes, forcing . The zero vector is orthogonal to everything, so it must be excluded before calling such a set a basis.
Orthogonality () means complete statistical decorrelation in the geometric sense — knowing the component along tells you nothing about the component along . The Pythagorean theorem holds only for orthogonal vectors, which is why orthonormal bases simplify every computation from norms to projections.
Projection onto a Vector
To find the closest point to on the line through , look for a multiple whose error is orthogonal to . Setting and solving for gives exactly the formula. The numerator measures how much points along , and the denominator removes the effect of the length of , so rescaling leaves the projection unchanged. The result splits into a part along plus a perpendicular residual. Forgetting the denominator is a common bug; it is only safe when has unit length.
The projection decomposes into a component along and an orthogonal residual. This is exactly the dot-product attention operation: the query-key dot product measures how much the value should contribute, which is a scalar projection. The residual is the part of the signal that this attention head ignores.
Project v = (3, 4) onto u = (1, 0).
Projection onto a Subspace
For a subspace spanned by the columns of , the projection has the form for some coefficient vector , and the residual must be orthogonal to every column, which means . Solving gives the coefficients in the formula, and the projection matrix is . It satisfies , since projecting twice changes nothing, and . The formula requires independent columns; otherwise is singular. When the columns are orthonormal, and simplifies to , which is why orthonormal bases are prized.
The projection matrix finds the closest point in to any vector . The key properties (projecting twice changes nothing) and (symmetry) uniquely characterize orthogonal projections. PCA projects high-dimensional data onto the top- eigenvector subspace, and the projection error equals the sum of discarded eigenvalues.
Orthogonal Complement
Given a subspace of , its orthogonal complement collects every vector whose dot product with all of is zero. It is itself a subspace, and the dimensions add up, as . Every vector splits uniquely as , where is the projection onto and is the residual. The most useful instance comes from , which says has zero dot product with each row of , so the null space is the orthogonal complement of the row space. To test membership it is enough to check a spanning set of , not every vector in it.
Every subspace of induces a clean decomposition: with . The null space of is exactly the orthogonal complement of the row space — this is why means is perpendicular to every row of . In residual networks, the skip connection preserves the complement of what the layer learns.
Theory Exercise
Problem:
Project b = (1, 2, 3) onto the subspace W = span{(1, 0, 1), (0, 1, 0)}.
Hints:
- Form matrix A with the spanning vectors as columns.
- Compute A(AᵀA)⁻¹Aᵀb.
Coding Exercise
Problem:
Build the projection matrix P = A (A^T A)^{-1} A^T onto the subspace W = span{(1,0,1), (0,1,0)}, project b = (1,2,3), and verify the defining properties: P is idempotent (P^2 = P), symmetric (P^T = P), and the residual b - Pb is orthogonal to every column of A.
Hints:
- Stack the spanning vectors as columns of A.
- P = A @ inv(A.T @ A) @ A.T.
- Check np.allclose(P @ P, P), np.allclose(P, P.T), and A.T @ (b - P@b) ~ 0.
Related Problems on PixelBank
The previous topic showed how much simpler projection becomes with an orthonormal basis: the projection matrix shrinks from A(AᵀA)⁻¹Aᵀ to AAᵀ, and each coordinate is a single dot product. Yet the bases we meet in practice are rarely orthonormal. The columns of a design matrix, the features extracted by a network, or the vectors spanning a solution set point in whatever directions the data provides. Can we trade such a basis for an orthonormal one that spans exactly the same space, and can we do it without losing accuracy in floating point?
The Gram-Schmidt process answers yes. It takes the vectors one at a time, removes from each the parts that lie along the directions already built, and normalizes what remains. Recording the removed amounts along the way produces the QR factorization A = QR, with Q orthonormal and R upper triangular. QR is the workhorse behind stable least-squares solvers, the QR algorithm for eigenvalues, and orthogonal weight initialization in deep networks.
We first run Gram-Schmidt and see why its classical form loses orthogonality, then package the process as QR and compare it with the normal equations.
Definition
The Gram-Schmidt process turns independent vectors into orthonormal vectors such that, for every , the first outputs span the same subspace as the first inputs. Applied to the columns of a matrix with independent columns, it yields , where has orthonormal columns and is upper triangular with a positive diagonal.
In this topic
- 1Gram-Schmidt Process
- 2QR Factorization
Gram-Schmidt Process
Gram-Schmidt builds the orthonormal basis one vector at a time. For the -th input , the formula subtracts its projection onto each earlier direction , leaving , the part of that is genuinely new; dividing by its length gives the unit vector . Because only earlier directions are removed, the first outputs span the same space as the first inputs. If some comes out zero, then depended on its predecessors. The classical version projects the original and loses orthogonality in floating point when inputs are nearly parallel. The modified version subtracts from the running residual instead.
Gram-Schmidt constructs an orthonormal basis by iteratively removing components along previously computed directions: . The key insight is that each step preserves the span: . In practice, classical Gram-Schmidt suffers from numerical cancellation; the modified version reorthogonalizes against updated (not original) vectors for stability.
QR Factorization
QR records the bookkeeping of Gram-Schmidt. Each column of is a combination of through only, with coefficients and diagonal entry . Stacking the as the columns of and the coefficients into gives , where and is upper triangular because later directions never appear in earlier columns. To solve least squares, multiply by and back-substitute in . Production libraries compute QR with Householder reflections rather than Gram-Schmidt, because reflections keep orthogonal to machine precision.
QR writes where is orthogonal and is upper triangular. Solving becomes — triangular back-substitution is and numerically stable. The critical advantage over normal equations: while , so QR preserves twice as many digits of accuracy.
Why is QR preferred over computing (AᵀA)⁻¹Aᵀb directly?
Theory Exercise
Problem:
Apply Gram-Schmidt to v₁ = (1, 1, 0) and v₂ = (1, 0, 1).
Hints:
- Start with u₁ = v₁.
- Compute the projection of v₂ onto u₁ and subtract.
Coding Exercise
Problem:
Implement the (modified) Gram-Schmidt process from scratch on the columns of a random 5x3 matrix, then verify your orthonormal Q against np.linalg.qr. Confirm Q^T Q = I and that Q @ R reconstructs the original matrix.
Hints:
- For each column, subtract its projections onto the already-orthonormalized vectors, then normalize.
- Modified Gram-Schmidt subtracts projections sequentially using the updated vector for better stability.
- R[i, j] holds the dot products; check Q.T @ Q against np.eye and compare to np.linalg.qr.
Related Problems on PixelBank
You have 100 measurements that should follow a straight line y = mx + c, but noise scatters them, so no single choice of m and c passes through every point. Written as a matrix system, that is 100 equations in 2 unknowns, and the right-hand side almost surely lies outside the column space. The previous topic built orthogonal projection into the QR factorization. This topic uses those tools to answer the practical question: which m and c are best, and what should best mean?
Least squares defines best as the minimizer of the sum of squared residuals, the squared length of Ax - b. Geometrically, the minimizer is where Ax equals the projection of b onto the column space, so the residual is orthogonal to every column, and that condition is the normal equations. When the columns are dependent, many minimizers exist, and the Moore-Penrose pseudoinverse picks the one of smallest norm. Linear regression, linear probes on frozen embeddings, and ridge regularization are all this problem in different clothing.
We derive the normal equations, generalize them to the pseudoinverse through the SVD, and then map everything onto linear regression and its ridge variant.
Definition
Given a matrix with rows and a vector in , a least-squares solution is any that minimizes . These minimizers are exactly the solutions of the normal equations . Among them, the one with the smallest norm is , where is the Moore-Penrose pseudoinverse, and it is unique even when is rank-deficient.
In this topic
- 1Normal Equations
- 2Moore-Penrose Pseudoinverse
- 3Connection to Linear Regression
Normal Equations
Least squares minimizes , the squared length of the residual. Two derivations lead to the same answer. With calculus, the gradient must vanish. With geometry, the best is the projection of onto the column space, so the residual is orthogonal to every column. Either way we get the normal equations in the formula, an system however many rows has. If the columns of are independent, is invertible and is unique. There are two failure modes: dependent columns make singular, and forming squares the condition number, which QR avoids.
The normal equations arise from setting the gradient of to zero. Geometrically, the residual must be orthogonal to the column space — this is the same principle as dropping a perpendicular from a point to a plane. Every closed-form linear regression formula is a restatement of the normal equations.
Moore-Penrose Pseudoinverse
The pseudoinverse extends inversion to every matrix. Write the SVD , with orthonormal and and the singular values on the diagonal of . Then replaces each nonzero by , leaves the zeros alone, and transposes the shape, and the formula assembles . The vector minimizes the residual and, among all minimizers, has the smallest norm. For full column rank it equals . In floating point, singular values near zero must be cut off by a tolerance, NumPy's rcond, because inverting a tiny turns noise into enormous coefficients.
The pseudoinverse inverts only the nonzero singular values, giving the minimum-norm least squares solution for any matrix. For full-rank overdetermined systems, ; for underdetermined systems, gives the shortest solution. In overparameterized neural networks, gradient descent implicitly converges to the minimum-norm solution — the pseudoinverse solution.
Why use the pseudoinverse instead of the normal equations?
Connection to Linear Regression
Linear regression is least squares under statistical names. Each row of the design matrix is one example and each column one feature, plus a column of ones for the intercept; holds the targets and the fitted weights, so the formula is the normal equations in new letters. Under Gaussian noise this estimate is also the maximum-likelihood one, which ties it back to the probability chapter. Ridge regression adds the penalty , giving . Adding lifts every eigenvalue of by , so the system stays invertible for any positive , even with collinear features, at the price of shrinking the weights.
Linear regression is the canonical least squares problem: minimize . The closed-form solution is the normal equation applied to the design matrix. Ridge regression adds to , which improves the condition number from to at most — a direct regularization of numerical stability.
Theory Exercise
Problem:
Find the least squares line y = mx + b for the points (0, 1), (1, 3), (2, 4).
Hints:
- Set up the system Ax = y where A = [[1, 0], [1, 1], [1, 2]] and x = [b, m]ᵀ.
- Solve the normal equations AᵀAx = Aᵀy.
Coding Exercise
Problem:
Fit a noisy linear regression three different ways and confirm they agree: (1) the normal equations (A^T A)^{-1} A^T b, (2) np.linalg.lstsq, and (3) the Moore-Penrose pseudoinverse np.linalg.pinv. Generate data from y = 3x + 2 plus noise, build a design matrix with an intercept column, and compare the recovered coefficients.
Hints:
- Design matrix A has a column of ones and a column of x values.
- Normal equations: np.linalg.solve(A.T @ A, A.T @ y) is more stable than forming the inverse.
- np.linalg.pinv(A) @ y gives the minimum-norm least-squares solution.
Related Problems on PixelBank
Training a network means walking downhill on a loss surface with millions of dimensions. Near a minimum that surface looks like a bowl, but bowls can be round, long and narrow, or not bowls at all. A long narrow valley forces gradient descent to zig-zag, while a saddle hides a direction that keeps going down. How can we read the shape of such a surface, and name its steepest and flattest directions, from a matrix of second derivatives?
The previous topic solved least squares, whose loss is exactly such a quadratic bowl with matrix AᵀA. This topic studies symmetric matrices in general. The spectral theorem says every real symmetric matrix has real eigenvalues and an orthonormal basis of eigenvectors, so in the right coordinates it is just a scaling along perpendicular axes. The quadratic form xᵀAx then becomes a weighted sum of squares, and the signs of the eigenvalues decide whether it is a bowl, a dome, or a saddle. The same decomposition powers PCA and spectral clustering.
We state the spectral theorem, use it to classify quadratic forms, study positive definite matrices, and finish with the Rayleigh quotient, which turns eigenvalues into an optimization problem.
Definition
The spectral theorem states that a real symmetric matrix factors as , where is orthogonal with eigenvectors as its columns and is diagonal with the real eigenvalues. The associated quadratic form sends to . The matrix is positive definite when this value is positive for every nonzero , which holds exactly when all eigenvalues are positive.
In this topic
- 1Spectral Theorem
- 2Quadratic Forms
- 3Positive Definite Matrices
- 4Rayleigh Quotient
Spectral Theorem
General square matrices can have complex eigenvalues or too few eigenvectors, but symmetric ones are always well behaved. The theorem says a real symmetric has real eigenvalues and orthonormal eigenvectors, collected as the columns of , so and holds the eigenvalues on its diagonal. Read from right to left: rotate into eigenvector coordinates, scale each coordinate by its eigenvalue, and rotate back. Eigenvectors for distinct eigenvalues are automatically orthogonal. Covariance matrices are symmetric, so PCA is exactly this factorization. For non-symmetric matrices the guarantee fails: the rotation [[0, -1], [1, 0]] has eigenvalues .
The spectral theorem means every symmetric matrix acts by rotating to eigenvector coordinates, scaling each axis by its eigenvalue, and rotating back. This is the mathematical engine of PCA: the covariance matrix's eigenvectors are the principal directions, and the eigenvalues are the variances along those directions. SVD generalizes this to non-symmetric (even non-square) matrices.
Quadratic Forms
A quadratic form assigns each vector the number , a polynomial whose terms all have degree two. Only the symmetric part of matters, so we take symmetric and split each cross term evenly; a term puts 2 in both off-diagonal slots. Substituting from the spectral theorem gives , a pure sum of squares. The eigenvalue signs now decide the shape: all positive gives a bowl, all negative a dome, mixed signs a saddle, and a zero eigenvalue a flat trough. Judging from the diagonal alone fails, since [[1, 3], [3, 1]] has a positive diagonal yet an eigenvalue of -2.
The quadratic form encodes the curvature of a scalar field. In the eigenbasis, , revealing that each eigenvalue controls curvature along its eigenvector. The Hessian of a loss function is a quadratic form — its eigenvalue spectrum determines whether gradient descent converges (all ), diverges (some ), or oscillates (large ratio).
Classify the quadratic form f(x, y) = 2x² + 4xy + 5y².
Positive Definite Matrices
Positive definiteness is the matrix version of a positive number. The formula lists two equivalent tests: for every nonzero , or all eigenvalues positive. Further equivalents are Sylvester's criterion, which requires all leading principal minors to be positive, and the existence of a Cholesky factor , which is also the cheapest numerical test: attempt it and see whether it fails. Semi-definite matrices allow zero eigenvalues. Covariance and kernel matrices are always semi-definite, since is a variance. At a critical point of a loss, a positive definite Hessian certifies a strict local minimum, while a single negative eigenvalue marks a saddle.
Positive definiteness ( for all ) guarantees a unique global minimum for the quadratic . Equivalently, means the Cholesky factorization exists — the most efficient way to solve symmetric positive definite systems. Covariance matrices and kernel matrices are always positive semi-definite by construction.
Rayleigh Quotient
The Rayleigh quotient measures how much a matrix 'stretches' in a given direction. Its maximum is the largest eigenvalue (achieved at the corresponding eigenvector), and its minimum is the smallest. This is exactly how PCA works: the first principal component maximizes the Rayleigh quotient of the covariance matrix. It also appears in spectral clustering, Fisher's linear discriminant, and the power iteration method used to find dominant singular vectors in large-scale SVD (as used by recommendation engines).
The Rayleigh quotient is bounded by , with equality at the corresponding eigenvectors. PCA finds the top- principal components by maximizing sequentially with orthogonality constraints. The power iteration algorithm for computing dominant eigenvectors is just repeated multiplication: converges because each step amplifies the dominant eigenvector component.
Theory Exercise
Problem:
Find the eigendecomposition of A = [[3, 1], [1, 3]] and determine if it's positive definite.
Hints:
- Solve det(A - λI) = 0.
- Both eigenvalues must be positive for PD.
Coding Exercise
Problem:
Eigendecompose a symmetric matrix and use it for PCA. First eigendecompose A = [[3, 1], [1, 3]] with np.linalg.eigh, verify A = Q Lambda Q^T and check positive definiteness. Then build a covariance matrix from correlated 2D data, find its principal directions, and confirm the top eigenvector aligns with the direction of maximum variance.
Hints:
- np.linalg.eigh returns eigenvalues (ascending) and an orthogonal eigenvector matrix for symmetric inputs.
- Positive definite means all eigenvalues > 0; reconstruct A via Q @ diag(eigvals) @ Q.T.
- For PCA, compute np.cov(data.T) and eigendecompose it; the eigenvector with the largest eigenvalue is the first principal component.
Every algorithm in this chapter so far assumed exact arithmetic. A computer does not have it: float64 keeps about 16 significant digits, float32 about 7, and the bfloat16 format used in large-model training only 2 or 3. Each operation rounds, and some problems magnify those tiny rounding errors into answers that are completely wrong, while others shrug them off. Why does solving one 8×8 system give ten correct digits and another give garbage, with the very same code?
The previous topic analyzed symmetric matrices through their eigenvalues. Here singular values take over as the measure of trouble. The condition number, the ratio of the largest to the smallest singular value, bounds how much relative input error can grow in the output, and its base-10 logarithm estimates how many digits you lose. That one number explains why the normal equations are risky, why you should never form an inverse explicitly, and why mixed-precision training needs loss scaling and FP32 master weights.
We cover the condition number, floating-point rules of thumb, iterative solvers such as conjugate gradients that scale to millions of unknowns, and the sparse storage formats that make those solvers affordable.
Definition
Numerical linear algebra studies algorithms that compute solutions, factorizations, and eigenvalues in finite-precision arithmetic, together with their accuracy and cost. Its central measure is the condition number , which bounds how much a relative perturbation of the data can be amplified in the solution of , whichever algorithm is used to compute that solution.
In this topic
- 1Condition Number
- 2Floating-Point Considerations
- 3Iterative Methods
- 4Sparse Matrices
Condition Number
Before trusting a computed answer, ask how sensitive the problem itself is. The condition number , which in the 2-norm equals the ratio of the largest to the smallest singular value, bounds the amplification: a relative change in can move by up to in relative terms. With unit roundoff near , a condition number of leaves about trustworthy digits. Orthogonal matrices have , the ideal; the 8×8 Hilbert matrix has . Conditioning belongs to the problem, not the algorithm, so no solver can recover digits an ill-conditioned matrix has already destroyed.
The condition number bounds the relative error amplification: . With digits of precision, you can trust roughly digits in the solution. In deep learning, the condition number of the Hessian determines the learning rate: for convergence, but makes progress along small-eigenvalue directions glacially slow — motivating adaptive optimizers like Adam.
Floating-Point Considerations
IEEE 754 float64 stores 53 significant bits, so the gap between 1 and the next representable number, machine epsilon, is , while float32 has . Each operation is exact up to a relative error of about , but errors compound. Subtracting nearly equal numbers cancels leading digits, and adding a tiny number to a huge one loses it entirely: in float64, evaluates to . Three rules follow. Compare floats with a tolerance, never with ==. Solve with LU, QR, or Cholesky rather than forming . In FP16 training, scale the loss so small gradients do not underflow to zero.
IEEE 754 float64 provides decimal digits (), while float32 gives digits. Every arithmetic operation introduces relative error , and these errors accumulate. The practical rule: never explicitly compute (doubles the condition number effect); use factorizations (LU, Cholesky, QR) that maintain backward stability. Mixed-precision training (FP16 forward, FP32 accumulation) exploits this: gradients need fewer digits than parameter updates.
Iterative Methods
Direct factorizations cost time and fill in sparse matrices, which is hopeless for a million unknowns. Iterative methods instead refine a guess using only products . The formula shows the template: compute the residual , apply an easy approximate inverse called the preconditioner, and correct . Jacobi takes to be the diagonal of . Conjugate gradient, for symmetric positive definite , chooses optimal search directions and needs roughly iterations per digit gained, and GMRES handles general matrices. Without preconditioning, a large makes them stall for thousands of steps, so a good often matters more than the method.
Conjugate Gradient solves for symmetric positive definite in at most steps, but typically converges in steps — far fewer for well-conditioned systems. Each step only requires one matrix-vector product , so the matrix need never be stored explicitly. Preconditioning () reduces and accelerates convergence. In ML, L-BFGS uses approximate curvature to precondition gradient descent, and Krylov methods power large-scale eigensolvers for spectral embeddings.
When should you use iterative vs direct solvers?
Sparse Matrices
Large matrices from graphs, meshes, and text are mostly zeros. Sparse formats keep only the nnz nonzero entries, so storage and a matrix-vector product cost instead of . COO stores (row, column, value) triples and is easy to build. CSR packs each row's column indices and values contiguously plus a row-pointer array, which makes row slicing and fast; CSC does the same by columns. A TF-IDF matrix with a 50,000-word vocabulary and about 200 distinct words per document is over 99.5 percent zeros. The trap is fill-in: LU can turn a sparse matrix dense, so iterative solvers suit sparse storage.
A matrix with nonzero entries out of total uses storage in CSR/CSC format instead of . Matrix-vector products cost rather than . In NLP, a vocabulary of 50K tokens with documents averaging 200 unique tokens gives 99.6% sparsity in the TF-IDF matrix. Graph adjacency matrices for social networks, molecular graphs, and scene graphs are similarly sparse — PyTorch's torch.sparse and DGL/PyG libraries exploit this structure for efficient message passing in GNNs.
Theory Exercise
Problem:
A matrix has singular values σ₁ = 100 and σ₂ = 0.01. What is its condition number, and how many digits of accuracy do you expect to lose?
Hints:
- κ = σ_max / σ_min.
- You lose roughly log₁₀(κ) digits.
Coding Exercise
Problem:
Demonstrate how the condition number governs error amplification and use SVD for a low-rank approximation. (1) Build an ill-conditioned Hilbert matrix, perturb b slightly, and measure how much the solution x changes relative to the condition number. (2) Take a rank-heavy matrix, compute its truncated-SVD rank-k approximation, and report the relative reconstruction error.
Hints:
- scipy.linalg.hilbert(n) (or build H[i,j] = 1/(i+j+1)) is famously ill-conditioned.
- Compare the relative change in x to kappa(A) times the relative change in b — kappa bounds the amplification.
- Truncated SVD: keep the top-k singular values; reconstruction error relates to the discarded singular values.