WhatsApp us
University Maths25 Nov 2026

Linear Algebra for Machine Learning: What You Actually Need, with Small Worked Examples

The linear algebra that computer science and data science students really use in machine learning, mapped to the topics of a standard course, with a small worked example for each idea.

Linear Algebra for Machine Learning: What You Actually Need, with Small Worked Examples

For machine learning you mainly need six pieces of linear algebra: vectors and dot products, matrix multiplication and shapes, linear systems and least squares, gradients of vector expressions, eigenvectors of symmetric matrices, and the singular value decomposition. Abstract proofs and big hand determinants matter much less day to day, but rank, null space and orthogonality matter a lot. This guide maps each ML idea to the course topic behind it and gives one small worked example you can check by hand.

The map: ML idea to linear algebra topic

ML ideaLinear algebra behind itWhere it sits in a typical first course
Embeddings, similarity searchDot product, norms, angle between vectorsFirst weeks: vectors in Rⁿ
A neural network layerMatrix–vector product Wx + bMatrix multiplication
Batches, tensors, shape errorsMatrix dimensions and transposesMatrix algebra
Linear regressionLeast squares, normal equations, projectionsOrthogonality
Ridge regularisationAᵀA + αI is always invertible for α > 0Invertibility, positive definite matrices
Gradient descent on a lossGradient of ‖Ax − b‖², matrix calculusUsually taught in multivariable calculus
PCAEigenvectors of the covariance matrixEigenvalues, symmetric matrices
Recommenders, compressionLow-rank approximation, SVDFinal weeks: SVD
Too many features, collinearityRank, null space, linear dependenceRank–nullity

If you are a CS or data science student working through this list, our linear algebra tutoring online page explains how sessions with Ajay Vatsyayan work.

1. Vectors and similarity

An embedding represents a word, image or user as a vector. Similar items should point in similar directions, measured by cosine similarity:

cos θ = (a·b) / (‖a‖‖b‖)

Example. a = (1, 2, 2) and b = (2, 0, 1). Then a·b = 2 + 0 + 2 = 4, ‖a‖ = 3 and ‖b‖ = √5, so cos θ = 4/(3√5) ≈ 0.596.

Norms also measure size and distance. For x = (3, −4), the Euclidean norm ‖x‖₂ = 5 and the L1 norm ‖x‖₁ = 7. Ridge regression penalises the squared L2 norm of the weights; lasso penalises the L1 norm, which tends to push some weights exactly to zero.

2. A layer is a matrix times a vector

A dense layer with 3 inputs and 2 outputs stores a 2×3 weight matrix W and a bias b.

Example. W = [[1, −1, 0], [2, 0, 1]], x = (3, 1, 2), b = (0, −1).

Wx = (3 − 1 + 0, 6 + 0 + 2) = (2, 8), so Wx + b = (2, 7)

A ReLU leaves both entries unchanged because they are positive. Stack 100 inputs as the rows of a 100×3 matrix X and the whole batch is XWᵀ + b, a 100×2 result. Most bugs in first ML projects are shape bugs, and they disappear once you read every product as (m×n)(n×p) = m×p.

3. Linear regression is least squares

With a design matrix A (a column of ones plus feature columns) and targets y, ordinary least squares picks the weights w that minimise ‖Aw − y‖². The answer solves the normal equations AᵀAw = Aᵀy.

Example. Fit y = w₀ + w₁x to (1, 1), (2, 3), (3, 4).

A = [[1, 1], [1, 2], [1, 3]], AᵀA = [[3, 6], [6, 14]], Aᵀy = (8, 19)

The determinant is 42 − 36 = 6, so w₀ = (14·8 − 6·19)/6 = −1/3 and w₁ = (3·19 − 6·8)/6 = 3/2. The fitted line is y = −1/3 + 1.5x.

Ridge version. Add αI before solving. With α = 1 (penalising both weights, for simplicity), (AᵀA + I)w = Aᵀy gives w = (1/4, 7/6). The slope shrinks from 1.5 to about 1.17, which is exactly what regularisation is meant to do. In practice libraries usually leave the intercept unpenalised.

Geometrically, Aw is the projection of y onto the column space of A, and the residual is orthogonal to every feature column. Our guide to Gram–Schmidt, QR and least squares works through that picture and the more stable QR route.

4. Gradients of vector expressions

Training means following the gradient of a loss. For the squared error L(w) = ‖Aw − y‖²,

∇L = 2Aᵀ(Aw − y)

Setting ∇L = 0 gives the normal equations again, so least squares and "gradient equals zero" are the same condition.

Example. For the data above, start at w = (0, 0). Then Aw − y = (−1, −3, −4) and ∇L = 2Aᵀ(−1, −3, −4) = (−16, −38). One gradient descent step with learning rate 0.05 gives w = (0.8, 1.9). Repeat and it converges towards (−1/3, 3/2).

The tools here are partial derivatives and the chain rule from multivariable calculus; our post on partial derivatives and the gradient covers the scalar version these formulas generalise.

5. Eigenvectors and PCA

Principal component analysis finds the directions in which centred data varies most. Those directions are the eigenvectors of the covariance matrix, and each eigenvalue is the variance along its direction.

Example. Take four centred points (3, 3), (−3, −3), (1, −1), (−1, 1). Stack them as the rows of X. Then

XᵀX = [[20, 16], [16, 20]], covariance C = XᵀX / 3 = [[20/3, 16/3], [16/3, 20/3]]

C has eigenvalues 12 and 4/3, with eigenvectors (1, 1) and (1, −1). The first principal component is (1, 1)/√2, and it explains 12/(12 + 4/3) = 90% of the variance. Projecting each point onto it reduces the data from two dimensions to one while keeping most of the spread.

Covariance matrices are symmetric, so their eigenvectors are orthogonal and the eigenvalues are real and non-negative. That is the spectral theorem behind orthogonal diagonalisation, and if the eigenvector steps are rusty, our eigenvalues and eigenvectors examples rebuild them from scratch.

6. The SVD and low-rank structure

Any data matrix can be written X = UΣVᵀ. The right singular vectors of a centred X are the PCA directions, and σᵢ²/(n − 1) are the variances, which is how libraries actually compute PCA. Keeping the largest few singular values gives the closest low-rank approximation: the core idea of matrix-factorisation recommenders and of compressing images or embeddings.

Example. A ratings matrix in which every row is a multiple of (2, 1, 2) has rank 1: one hidden "taste" explains every user. Real ratings are close to low rank, and a truncated SVD finds that structure. The SVD walkthrough with examples shows the hand calculation and the approximation error.

7. Rank and why features collide

If one feature is a combination of others (say, price in rupees and the same price in dollars), the columns of A are dependent, AᵀA is singular, and least squares has infinitely many solutions. The rank–nullity theorem counts exactly how many: the null space of A has dimension equal to the number of features minus the rank. Ridge regularisation is one fix, because AᵀA + αI is invertible for any α > 0.

What you can safely spend less time on

For ML work, these deserve less of your revision time than the course might give them: cofactor expansion of 4×4 and larger determinants, the Jordan canonical form, and long hand row reductions. Keep the ideas, though: a zero determinant means dependent columns, and row reduction is how you read off rank. Abstract vector spaces matter more than many CS students expect, because function spaces and kernels in ML are exactly that.

Mistakes CS and data science students make

  • Row versus column vectors. Libraries often store samples as rows, textbooks as columns. Decide once per problem and write the shapes beside every product.
  • Elementwise versus matrix product. In NumPy, the * operator multiplies entry by entry, while the @ operator gives the matrix product.
  • Forgetting to centre data before PCA. Without centring, the first "component" mostly points at the mean.
  • Inverting AᵀA explicitly. Fine on paper; in code, use a least squares or QR solver for accuracy.
  • Taking eigenvalues of a non-square data matrix. Use the covariance matrix or the SVD instead.
  • Mixing n and n − 1. Sample covariance divides by n − 1; some libraries divide by n. The eigenvectors are the same, the variances differ.

Practice questions

  1. Find the cosine similarity of (1, 0, 1) and (0, 1, 1).
  2. X is 64×20 and W is 20×5. What shape is XW, and what shape must a bias be to add to each row?
  3. For A and y in section 3, compute the gradient of ‖Aw − y‖² at w = (0, 1).
  4. Centred points (2, 0), (−2, 0), (0, 1), (0, −1): find the covariance matrix (divide by n − 1), the principal components and the share of variance on the first.
  5. A regression has 6 feature columns, but the design matrix has rank 4. How many independent directions of weights give the same predictions?

Answers.

  1. 1/(√2·√2) = 1/2.
  2. 64×5; the bias is a length-5 vector, broadcast across the 64 rows.
  3. Aw − y = (0, −1, −1), so ∇L = 2Aᵀ(0, −1, −1) = (−4, −10).
  4. C = [[8/3, 0], [0, 2/3]]; components (1, 0) and (0, 1); the first carries (8/3)/(10/3) = 80%.
  5. Nullity = 6 − 4 = 2, so a two-dimensional family of weight changes leaves the predictions unchanged.

A sensible study order

Learn vectors, dot products and matrix shapes first; then least squares and projections; then eigenvectors of symmetric matrices and PCA; then the SVD. Read each alongside a small coding exercise. For the probability side of ML, such as likelihoods, distributions and hypothesis tests, see our probability and statistics tutoring page.

How Maths Bodhi helps

CS and data science students often know the code but not why it works. In online sessions we connect your linear algebra course to the ML ideas above, use your own course questions and small examples, and review your attempts. We explain and practise; we don't complete graded work or projects.

Home tuition is available in Gurgaon (Gurugram). Students elsewhere in India and abroad learn with us online. You can book a free demo class.

Written and checked by the Maths Bodhi team (November 2026).

Frequently asked questions

How much linear algebra do I need for machine learning?
Vectors, matrix multiplication, least squares, eigenvectors of symmetric matrices and the SVD cover most of what standard ML methods use.
Is linear algebra or calculus more important for machine learning?
Both are needed; linear algebra describes the data and models, and calculus (gradients) is how the models are trained.
What linear algebra is used in neural networks?
Each layer is a matrix–vector product plus a bias, and training uses gradients built from matrix transposes.
Do I need eigenvalues for machine learning?
Yes for PCA, spectral methods and understanding optimisation; most libraries compute them through the SVD.
Which topics in a linear algebra course matter least for ML?
Large hand determinants, the Jordan form and long hand row reductions, though the ideas behind them still help.
Is linear regression the same as least squares?
Ordinary linear regression is least squares on a design matrix with a column of ones and the feature columns.
linear algebramachine learningdata sciencePCAuniversity maths

Related guides

Keep exploring this maths topic

University Maths25 Nov 2026

Singular Value Decomposition Explained, with Step-by-Step Examples

What the singular value decomposition A = UΣVᵀ means, how to compute it by hand for square and rectangular matrices, and how it gives low-rank approximations and the pseudo-inverse, with checked examples and practice.

singular value decompositionSVDlinear algebrapseudo-inverse

By Maths Bodhi Team

Read guide

University Maths25 Nov 2026

The Gram–Schmidt Process and Least Squares, Step by Step

How the Gram–Schmidt process builds an orthogonal basis, how it gives the QR factorisation, and how both solve least squares problems such as fitting a line, with six checked examples and practice.

Gram-Schmidtleast squaresQR factorisationlinear algebra

By Maths Bodhi Team

Read guide

University Maths25 Nov 2026

The Rank–Nullity Theorem Explained, with Examples for Matrices and Linear Transformations

What the rank–nullity theorem says, why it is true, and how to use it on matrices, polynomial maps and matrix spaces, with six checked examples, common mistakes and practice.

rank nullity theoremlinear algebranull spacelinear transformations

By Maths Bodhi Team

Read guide

University Maths25 Nov 2026

How to Find the Matrix of a Linear Transformation: Examples and Solutions

How to build the matrix of a linear transformation from a formula, from images of other vectors, from a geometric description, on polynomial and function spaces, and in a new basis, with six checked examples and practice.

linear transformationslinear algebrachange of basisstandard matrix

By Maths Bodhi Team

Read guide

University Maths25 Nov 2026

Diagonalization of a Matrix: The Test, the Method and 6 Worked Examples

How to diagonalise a matrix as A = PDP⁻¹, how to tell quickly whether it can be done, and how to use it for matrix powers, symmetric matrices and differential equations, with checked examples and practice.

diagonalizationlinear algebraeigenvaluesmatrix powers

By Maths Bodhi Team

Read guide

University Maths18 Nov 2026

Eigenvalues and Eigenvectors Step by Step, with 6 Worked Examples

How to find eigenvalues and eigenvectors of 2×2 and 3×3 matrices, step by step: repeated and complex eigenvalues, trace and determinant checks, common mistakes and practice with answers.

eigenvalueseigenvectorslinear algebracharacteristic polynomial

By Maths Bodhi Team

Read guide