Linear Algebra for ML
Machine learning runs on linear algebra. A dataset is a matrix, a model’s weights are a matrix, and a prediction is a matrix multiplication. You need a working feel for a handful of ideas.
Vectors
A vector is a list of numbers, for example a house described by its features:
Geometrically it’s a point (or an arrow) in -dimensional space. Key operations:
- Addition and scaling, element by element.
- Norm (length): . The L1 norm appears in Lasso regularisation.
- Dot product: .
The dot product is everywhere. A linear model’s prediction is a dot product of weights and features:
Cosine similarity, , measures how aligned two vectors are regardless of length. It is the standard way to compare embeddings (word, sentence and image vectors) in search and recommendations.
Matrices
A matrix is a grid of numbers. A dataset with examples and features is an matrix : row is example .
Matrix–vector multiplication applies a linear model to every example at once:
Matrix multiplication : entry is the dot product of row of and column of . Shapes must line up: . It is not commutative: in general.
A neural network layer is exactly this: . GPUs exist in ML because they do huge matrix multiplications fast.
Transpose, identity, inverse
- Transpose : flip rows and columns. .
- Identity : ones on the diagonal; .
- Inverse : . It exists only for square matrices with non-zero determinant.
These give the closed-form solution of linear regression (the normal equation):
In practice we rarely invert matrices (it is slow and numerically unstable); we use gradient descent or solvers. The formula is still a classic interview question.
Eigenvectors and eigenvalues
For a square matrix , an eigenvector only gets scaled (not rotated) by :
is its eigenvalue. Why ML cares: in PCA, the eigenvectors of the data’s covariance matrix are the directions of greatest variance, and their eigenvalues say how much variance each captures. Keeping the top few compresses the data with minimal information loss.
SVD (singular value decomposition) generalises this to any matrix, . It powers PCA, recommendation systems (matrix factorisation) and low-rank tricks like LoRA fine-tuning.
Shapes: the habit that saves hours
Most ML bugs are shape bugs. Write shapes next to every expression:
| Object | Shape |
|---|---|
| Data | (examples × features) |
| Weights | |
| Predictions | |
| Layer weights | |
| A batch of images | batch × channels × height × width |
Check yourself
A dataset has 1,000 examples with 20 features each. As a matrix X it has shape…
If A is 3×4 and B is 4×2, what is the shape of AB?
The dot product of two vectors is zero. The vectors are…
Item 2 of 24 · updated 2026-10-12