Guide to AI and Data Courses · Lecture Notes
Chapter 31: Linear Algebra
A movie recommender keeps the ratings that millions of users gave to millions of films in a single table. That table is a matrix, and how alike two users' tastes are is measured by the angle between two vectors. Linear algebra is the course that teaches how to understand such tables and the directions hidden in them: turning data into vectors, transforming it with matrices, and breaking a matrix into meaningful parts. These notes introduce the course and work through its three core ideas with small examples you can compute by hand.
Learning outcomes
- Vectors and dot products
- Compute the dot product and norm of vectors and the cosine of the angle between them; recognize perpendicular vectors.
- Matrix multiplication
- Compute by hand how a matrix transforms a vector; write a neural network layer as a matrix product.
- Systems and least squares
- Set up and solve the normal equations to fit the best line to three points, and explain why the error is perpendicular.
- Eigenvalues and SVD
- Find the eigenvalues and eigenvectors of a 2×2 matrix; build the best low-rank approximation from the singular values of a matrix.
- Place of the course
- State how linear algebra relates to optimization, probability, machine learning and computer graphics, and where it differs from them.
31.1What question does the course ask?
How do vectors and matrices represent data and transformations?
Linear algebra studies vectors, matrices and linear transformations. In AI and data courses almost everything is a vector: an image, a word, a user. A neural network layer is, to a large extent, a matrix multiplication.
The question of linear algebra is this: if data is a list of numbers, what can we do with those numbers, and how can we understand what we did? A grayscale image is a list of pixel values, a word embedding is a few hundred numbers, a user is a list of the ratings they gave. All of these are vectors; stacking vectors gives a matrix. The course teaches which operations on these objects make sense beyond adding and scaling, what they mean geometrically, and how to compute them.
Two main ideas run through the course. The first is that a matrix is less a table of numbers than a transformation: it takes a vector and turns it into another, and because it is linear its whole behavior is stored in a handful of numbers. The second is that a matrix that looks complicated is often a combination of simple pieces: the eigenvalue decomposition and the singular value decomposition (SVD) split a matrix into parts that each work along a single direction. By the end of the course you should be able to look at a matrix and say what it does.
31.1.1Why a calculator is not enough
Libraries already multiply, solve and decompose. But interpreting the result, knowing which operation is stable in which situation, and spotting shape or rank errors takes theory. For example, a data matrix with two nearly identical features has low rank, and a least squares problem built on it is ill-conditioned; this is hard to see from strangely large coefficients alone. The course teaches you to see such warnings in advance.
31.1.2At a glance
| Criterion | Linear Algebra |
|---|---|
| Approach | vector spaces and transformations |
| Input | vectors, matrices |
| Output | solution, decomposition, transformation |
| Success measure | accuracy, numerical stability |
| Math load | the theory itself |
| Data needs | none |
31.2A short history
| Year | Milestone |
|---|---|
| 1844 | Grassmann sets out the idea of a multidimensional vector space systematically for the first time. |
| 1858 | Cayley treats matrices as algebraic objects in their own right; matrix multiplication is defined. |
| 1901 | Pearson finds the lines and planes that best fit data: principal component analysis (PCA). |
| 1936 | Eckart and Young show that the SVD gives the best low-rank approximation of a matrix. |
| 1965 | Golub and Kahan give a numerically stable way to compute the SVD on a computer. |
| 1979 | BLAS is published: the basic matrix operations beneath today's scientific and AI libraries. |
31.3Core concepts
The rest of the course is built on the concepts below. The following sections work through the most important ones with examples.
| Concept | Meaning |
|---|---|
| Vectors and spaces | Turning data into a point in many dimensions. |
| Matrix multiplication | Applying a transformation or a network layer. |
| Inner product and norm | Measuring similarity (cosine) and distance. |
| Rank and basis | How many independent directions the data really spans. |
| Linear systems | Ax = b; the least squares solution. |
| Eigenvalues, eigenvectors | Vectors whose direction a map leaves unchanged. |
| SVD | Splitting any matrix into rotate, scale, rotate. |
| Projection | The closest point to a vector in a subspace. |
31.4Vectors, dot products and matrix multiplication
A vector is an ordered list of numbers; geometrically it is a point in space, or the arrow from the origin to that point. The dot product of two vectors is the sum of the products of matching entries. The norm (length) of a vector is the square root of its dot product with itself, and the cosine of the angle between two vectors is their dot product divided by the product of the norms.
a · b = Σ aibi; ‖a‖ = √(a · a); cos θ = (a · b) / (‖a‖ ‖b‖). If the dot product is zero the vectors are perpendicular (orthogonal).
Take three items described by three features (the values are illustrative): u = (1, 2, 2), v = (2, 1, 2), w = (2, −2, 1).
- Norms. ‖u‖ = √(1 + 4 + 4) = 3; ‖v‖ = √(4 + 1 + 4) = 3; ‖w‖ = √(4 + 4 + 1) = 3.
- Dot products. u · v = 2 + 2 + 4 = 8; u · w = 2 − 4 + 2 = 0.
- Cosines. cos θ(u, v) = 8/9 ≈ 0.89 (an angle of about 27°): they are very similar. cos θ(u, w) = 0: perpendicular, that is, independent directions.
In recommender systems and word embeddings, "similarity" is very often exactly this cosine.
Matrix multiplication is the dot product in bulk. An m × n matrix A turns an n-dimensional vector x into an m-dimensional vector Ax; each entry of the result is the dot product of a row of A with x. The same result can be seen as a weighted sum of the columns of A with the entries of x as weights. This second view is the source of the sentence "a matrix product is a linear combination of columns" and the starting point of rank and basis.
A layer multiplies its input by a weight matrix W, adds a bias b and applies ReLU (negatives become zero). Let W = [[1, 0, 2], [−1, 1, 0]], b = (−8, 0) and the input x = (1, 2, 3).
- Row times input. Wx = (1·1 + 0·2 + 2·3, −1·1 + 1·2 + 0·3) = (7, 1).
- Bias. Wx + b = (7 − 8, 1 + 0) = (−1, 1).
- ReLU. (0, 1).
A three-dimensional input became a two-dimensional output. In real networks W has hundreds of rows and columns, but this is the work every layer does.
31.4.1Linear systems and least squares
The system Ax = b asks: "which combination of the columns of A gives b?" Data almost always outnumbers the unknowns, so the system has no exact solution; we then look for the x that minimizes the squared error. The error is smallest when the error vector is perpendicular to every column of A; this condition gives the normal equations: AᵀA x = Aᵀb.
Fit y = c + d·x to the points (1, 1), (2, 2), (3, 2). The rows of A are (1, 1), (1, 2), (1, 3) and b = (1, 2, 2).
- Normal equations. AᵀA = [[3, 6], [6, 14]], Aᵀb = (5, 11); that is, 3c + 6d = 5 and 6c + 14d = 11.
- Solution. The determinant is 42 − 36 = 6. c = (14·5 − 6·11)/6 = 2/3, d = (3·11 − 6·5)/6 = 1/2.
- Line and error. The line's values are 7/6, 5/3, 13/6; the errors (actual − predicted) are −1/6, 1/3, −1/6; the sum of squares is 6/36 = 1/6.
- Checking perpendicularity. The errors sum to −1/6 + 1/3 − 1/6 = 0 and their x-weighted sum is −1/6 + 2/3 − 1/2 = 0: the error is perpendicular to both columns.
Always solving least squares by forming AᵀA and inverting it. The normal equations are fine for small examples, but AᵀA squares the condition number; if the features are close to each other the result can be badly damaged. In practice the problem is solved with QR or SVD (this is how numpy.linalg.lstsq works).
31.5Eigenvalues and eigenvectors
Most vectors change both direction and length when multiplied by a matrix. Some special vectors keep their direction and are only stretched or shrunk. A nonzero vector v with Av = λv is an eigenvector, and the number λ is its eigenvalue. Eigenvectors give the matrix's "natural axes" and eigenvalues the scale factors along those axes.
The values λ that satisfy the characteristic equation det(A − λI) = 0 are the eigenvalues. The trace (sum of the diagonal) equals the sum of the eigenvalues and the determinant equals their product.
Let A = [[2, 1], [1, 2]].
- Characteristic equation. det(A − λI) = (2 − λ)2 − 1 = λ2 − 4λ + 3 = (λ − 3)(λ − 1) = 0; so λ = 3 and λ = 1. (Check: the sum 4 is the trace, the product 3 is the determinant.)
- Eigenvector for λ = 3. (A − 3I)v = 0 gives −v1 + v2 = 0; v = (1, 1).
- Eigenvector for λ = 1. v1 + v2 = 0; v = (1, −1).
- Check. A(1, 1) = (3, 3) = 3·(1, 1) and A(1, −1) = (1, −1) = 1·(1, −1).
The matrix triples vectors along (1, 1) and leaves the (1, −1) direction as it is. The two eigenvectors are perpendicular because the matrix is symmetric.
Eigenvectors also tell us what happens when a matrix is applied again and again. If a vector is written as a combination of eigenvectors, applying A k times multiplies each component by λk. The component with the largest eigenvalue eventually dominates. PageRank, the steady state of Markov chains and vibration modes all come from this observation.
Suppose a sunny day is followed by a sunny day with probability 0.9, and a rainy day is followed by a sunny day with probability 0.5. The state of the day (sunny, rainy) is a probability vector, multiplied every day by P = [[0.9, 0.5], [0.1, 0.5]] (the values are illustrative). The start is a rainy day: (0, 1).
- First days. (0.5, 0.5) → (0.7, 0.3) → (0.78, 0.22) → (0.812, 0.188).
- Steady state. Pπ = π, an eigenvector with eigenvalue 1: 0.9a + 0.5b = a and a + b = 1 give a = 5/6 ≈ 0.833, b = 1/6.
- Speed of convergence. The second eigenvalue is, from the trace, 1.4 − 1 = 0.4; the gap to the steady value shrinks by a factor of 0.4 each day: 0.333 → 0.133 → 0.053.
In the long run the starting condition is forgotten and the chain converges to the dominant eigenvector.
Assuming every square matrix has enough independent eigenvectors. The matrix [[1, 1], [0, 1]] has the single eigenvalue 1 and its eigenvectors lie only along (1, 0); it cannot be diagonalized. Symmetric matrices do not have this problem, which is why the course gives them a week of their own.
31.6The singular value decomposition (SVD)
Eigenvalues behave well only for square matrices, and mostly symmetric ones. Data matrices are rectangular. The SVD works for every matrix: any matrix A can be written as A = UΣVᵀ. V and U are rotation (or reflection) matrices; Σ is a scaling matrix with the singular values on its diagonal in decreasing order. So every linear transformation is a rotation, a scaling along the axes and another rotation.
The singular values are σi = √(eigenvalues of AᵀA). Rebuilding A from only its k largest singular values gives the rank-k matrix closest to A (Eckart-Young).
Let A = [[3, 0], [4, 5]].
- AᵀA. AᵀA = [[25, 20], [20, 25]]. Its eigenvalues are 45 and 5, with eigenvectors (1, 1)/√2 and (1, −1)/√2 (the matrix is symmetric, so they are found as in the previous section).
- Singular values. σ1 = √45 ≈ 6.71, σ2 = √5 ≈ 2.24. (Note: the eigenvalues of A itself are 3 and 5; they are not the singular values.)
- Left vectors. u1 = Av1/σ1 = (1, 3)/√10, u2 = Av2/σ2 = (3, −1)/√10.
- Rank-1 approximation. A1 = σ1 u1 v1ᵀ = 1.5 · [[1, 1], [3, 3]] = [[1.5, 1.5], [4.5, 4.5]].
- Error. A − A1 = [[1.5, −1.5], [−0.5, 0.5]]; the sum of the squared entries is 2.25 + 2.25 + 0.25 + 0.25 = 5 = σ22. 90% of the total "energy" (45 + 5 = 50) is concentrated in a single direction.
The same idea is used in two ways at scale. The first is compression: rebuilding an image or a user-item matrix from its few largest singular values cuts the number of values to store sharply and filters out noise. The second is PCA: the SVD of the mean-centered data matrix gives the directions of greatest spread (the principal components), and projecting the data onto the first few of them reduces the dimension. Eigenfaces in face recognition and matrix factorization in recommender systems are the same computation.
Confusing singular values with eigenvalues, or applying PCA without subtracting the mean and scaling the features. In the example above the matrix has eigenvalues 3 and 5 but singular values 6.71 and 2.24. If the mean is not removed in PCA, the first component may capture the data's distance from the origin rather than its spread.
31.7How is the course taught?
31.7.1A typical workflow
In face recognition each face image is a long vector of pixels. The faces are stacked into a matrix, the mean is subtracted, SVD finds a few most important directions (eigenfaces), and each face is represented and compared by its weights on those few directions.
31.7.2Topics over the semester
- Vectors, linear combinations and dot products
- Linear systems and Gaussian elimination
- Matrix operations, inverses and LU factorization
- Vector spaces and the four fundamental subspaces
- Linear independence, basis, dimension and rank
- Orthogonality, projections and least squares
- Gram-Schmidt and QR factorization
- Determinants and their properties
- Eigenvalues, eigenvectors and diagonalization
- Symmetric and positive definite matrices
- Singular value decomposition (SVD) and PCA
- Linear transformations and change of basis
This is a typical semester; the order and coverage vary between universities.
31.7.3Skills you will gain
- matrix computation with NumPy
- solving systems with scipy.linalg
- dimensionality reduction with SVD
- least squares fitting
- writing short proofs
31.7.4Try it yourself
The Try It: Augmenting a Digit Image slide in the presentation lets you solve a typical problem of this course yourself: A handwritten digit recognizer has few examples; making new ones by rotating and shearing each image (data augmentation) means multiplying every pixel by a 2×2 matrix. Change the matrix and watch the “7”.
31.8Are you ready for this course?
31.8.1Prerequisites
| Course | Why it is needed |
|---|---|
| High school mathematics | solving equations, functions and the coordinate plane |
| Programming | arrays and loops: trying matrix operations in code |
31.8.2Ask yourself
For every "no", the right-hand column shows where to start. If you can say "yes" to most of them, you are ready.
| Question | If not, start with |
|---|---|
| Can you solve a system of two equations in two unknowns by elimination? | Systems of equations from high school math |
| Can you find the distance between two points in the plane? | Coordinate geometry from high school math |
| Can you find an angle of a right triangle with sine and cosine? | High school trigonometry |
| Can you multiply two Python lists element by element in a loop and sum them? | An intro programming course, then a short NumPy tutorial |
31.9Neighboring courses
31.9.1Where it overlaps
| Relation | Course | Shared ground |
|---|---|---|
| builds on | Machine Learning builds on this course | feature vectors, matrix multiplication, PCA |
| builds on | Artificial Neural Networks builds on this course | weight matrices, vectorized computation |
| builds on | Computer Graphics builds on this course | transformation matrices, projection |
| builds on | Robotics and Robot Vision builds on this course | coordinate transforms, kinematics |
| builds on | Information Retrieval and Recommender Systems builds on this course | vector space model, matrix factorization |
| builds on | Social Network Analysis builds on this course | adjacency matrix, spectral methods |
| builds on | Optimization builds on this course | gradient, Hessian, convexity |
31.9.2Where it differs
- Optimization: Optimization searches for the best values; linear algebra supplies the gradients, Hessians and system solves used in that search.
- Probability and Statistics: Probability measures uncertainty; linear algebra represents and decomposes the data and the covariance matrix.
- Machine Learning: ML learns a model from data; linear algebra is the language of the computation inside that model and learns nothing itself.
- Computer Graphics: Computer graphics applies 3D transformation matrices; this course gives the general theory of those matrices.
31.10In practice
31.10.1Applications
| Area | What is done |
|---|---|
| Neural networks | Layer = matrix product plus activation. |
| PCA | Dimensionality reduction and visualization. |
| Recommender systems | Factorizing the user-item matrix. |
| Word embeddings | Similar meaning = nearby vectors. |
| PageRank | Dominant eigenvector of the link matrix. |
| Image processing | Transforms, compression and filters. |
31.10.2Risks and ethics
| Risk | Explanation |
|---|---|
| Ill-conditioning | With a large condition number, a tiny input error is magnified many times; the answer fills up with meaningless digits. |
| The normal equations trap | Forming AᵀA for least squares squares the condition number; solving with QR or SVD is safer. |
| Silent shape errors | NumPy broadcasting combines mismatched shapes without an error; the result is wrong but looks fine. |
| Misreading PCA | On unscaled features PCA favors the variable with the largest units; a component is not always a meaningful factor. |
These issues are discussed in depth in Explainable AI and AI Ethics.
31.10.3Tools and datasets
Tools: NumPy, SciPy (scipy.linalg), PyTorch, MATLAB, GNU Octave, LAPACK and BLAS.
Classic example problems: Line fitting by least squares, Eigenfaces, PageRank eigenvector, Image compression with SVD, Netflix Prize matrix factorization, Markov chain steady state.
Matrix operations are not coded by hand: they run on LAPACK and BLAS, the product of decades of work, which NumPy and PyTorch also call.
31.11Common misconceptions
Linear algebra is just solving equations.
Its real power is understanding transformations and decompositions: PCA, SVD and embeddings are built on them.
Computing the inverse and multiplying is the right way.
In practice you do not invert; you solve with LU, QR or Cholesky, which is faster and more stable.
High-dimensional space behaves like 3D.
In high dimensions points sit at similar distances from each other; intuition misleads (curse of dimensionality).
With libraries around, theory is unnecessary.
Rank deficiency, ill-conditioning and shape errors make sense only if you know the theory.
31.12Summary
- Data becomes vectors and tables become matrices; the dot product and cosine measure similarity, and matrix multiplication applies a transformation or a neural network layer.
- When Ax = b has no exact solution, least squares minimizes the error; the error is perpendicular to the column space, and the normal equations AᵀAx = Aᵀb express that perpendicularity.
- An eigenvector is a vector whose direction a matrix leaves unchanged; the eigenvalue is its scale factor. The trace is the sum of the eigenvalues and the determinant their product.
- The SVD splits every matrix into rotate, scale, rotate; the k largest singular values give the best rank-k approximation and underlie PCA and compression.
- Linear algebra is the language of the optimization, probability, machine learning and graphics courses; it does not learn from data itself, it carries out and explains their computation.
31.13Test Yourself
Find the cosine of the angle between a = (1, 0) and b = (1, 1). How many degrees is it?
Answer
a · b = 1, ‖a‖ = 1, ‖b‖ = √2. cos θ = 1/√2 ≈ 0.71; the angle is 45°.
For A = [[1, 2], [3, 4]] and S = [[0, 1], [1, 0]] compute AS and SA. Are the results equal?
Answer
AS = [[2, 1], [4, 3]] (the columns of A swap places), SA = [[3, 4], [1, 2]] (the rows swap places). They are not equal: matrix multiplication is not commutative.
Find the eigenvalues and eigenvectors of A = [[4, 1], [2, 3]].
Answer
The trace is 7 and the determinant 10: λ2 − 7λ + 10 = 0, so λ = 5 and λ = 2. For λ = 5: −v1 + v2 = 0, v = (1, 1). For λ = 2: 2v1 + v2 = 0, v = (1, −2). Check: A(1, −2) = (2, −4) = 2(1, −2).
A 1000 × 1000 grayscale image is approximated with the SVD using 50 singular values. How many numbers are stored, and what fraction of the original is that? (For each singular value we store a left vector, a right vector and the singular value itself.)
Answer
Each term needs 1000 + 1000 + 1 numbers: 50 · 2001 = 100,050 numbers. The original has 1,000,000; the fraction is about 10%. How good the approximation is depends on how small the discarded singular values are.
A student solves Ax = b with x = A−1b. Why is this not preferred in practice?
Answer
Computing the inverse costs more than solving the system directly and is numerically less stable. Solving directly with LU, QR or Cholesky is both faster and magnifies rounding error less. Also, if A is rectangular or singular the inverse does not exist; then least squares or the SVD is needed.
A team says it is searching for the best weights of a neural network. Is linear algebra or optimization the main course for this job? What does linear algebra contribute?
Answer
Searching for the weights is optimization (gradient descent). Linear algebra is the language of what is computed inside that search: the weights are matrices, a layer's output is a matrix product, the gradient and Hessian are vectors and matrices. The two courses complement each other; the difference is the goal.
31.14After this course
Linear algebra is a prerequisite for almost every course in the guide. After it you can move comfortably to optimization, machine learning, neural networks and computer graphics. Numerical linear algebra and GPU programming teach how to do the same computations fast at scale.
Courses that build on or extend this one: Machine Learning, Artificial Neural Networks, Computer Graphics, Robotics and Robot Vision, Information Retrieval and Recommender Systems, Social Network Analysis, Optimization.
Related careers: Machine learning engineer, Data scientist, Computer graphics developer, Numerical computing specialist.
31.15Further reading
- G. Strang, Introduction to Linear Algebra (6th ed., 2023): the textbook-level source for this course; explains the four fundamental subspaces, eigenvalues and the SVD with geometric intuition.
- M. P. Deisenroth, A. A. Faisal, C. S. Ong, Mathematics for Machine Learning (2020), Chapters 2–4: linear algebra, analytic geometry and matrix decompositions with machine learning examples.
- L. N. Trefethen, D. Bau, Numerical Linear Algebra (1997): shows how to compute the SVD, QR and least squares on a computer and why stability matters.
31.16References
- Strang, Introduction to Linear Algebra, 6th ed., Wellesley-Cambridge Press, 2023.
- Strang, Linear Algebra and Learning from Data, Wellesley-Cambridge Press, 2019.
- Trefethen and Bau, Numerical Linear Algebra, SIAM, 1997.
- Deisenroth, Faisal and Ong, Mathematics for Machine Learning, Cambridge University Press, 2020.
Related pages: Slides · Slides (PDF) · Course page