Matrices as transformations
A matrix is what happens to a vector
A matrix is the thing that happens to a vector. Every linear layer, every attention-score matrix, every covariance and every rotation of an image is a matrix acting on vectors, and "training" mostly means adjusting the entries of such matrices. This lesson teaches you to see as a transformation, matrix multiplication as composition, the determinant as a volume scale and the inverse as undoing — and then reads the linear layer of 4.1 From perceptron to MLP; universal approximation and the attention scores of 7.2 Scaled dot-product and multi-head attention, fully derived in exactly those terms.
You'll be able to
- Compute matrix–vector and matrix–matrix products in both the column and the row picture, and track shapes
- Interpret determinant, inverse, rank, column space and null space geometrically
- Recognize the special matrices (diagonal, orthogonal, symmetric, positive definite, projection) and what each does
- Read a batched linear layer as a matrix product and count its parameters and floating-point operations
Key ideas
- Ax is a linear combination of the columns (column picture) and a stack of dot products with the rows (row picture); the columns are where the basis vectors land.
- Matrix multiplication is composition of transformations, read right to left: associative, not commutative, shapes (m×n)(n×p) = m×p.
- Determinant = signed area/volume scale factor; det = 0 ⇔ space is squashed ⇔ not invertible; det(AB) = det A · det B.
Show 4 more key ideas
- Column space = reachable outputs (dimension = rank); null space = inputs squashed to zero; rank + nullity = n.
- Orthogonal matrices preserve lengths and angles; symmetric PSD matrices are bowls (covariances, Hessians at minima).
- A batched linear layer is Z = XWᵀ + b with kd + k parameters and about 2ndk flops; attention scores QKᵀ are the same operation.
- Solve linear systems with a solver, never with an explicit inverse.
Suggested path through this lesson
A matrix is a function
A matrix has rows and columns and defines a function from to . There are two ways to compute the product, and you need both:
The column picture says: the -th column is where the basis vector lands, and every other input lands on the corresponding combination. The row picture says: each output coordinate is a dot product of the input with one row — a template match (1.1 Vectors, dot products and norms). The function is linear, : lines stay lines, the origin stays put, grid lines stay parallel and evenly spaced. That is exactly what the demo above draws when you move the sliders.
Example: sends to and to — a horizontal stretch combined with a shear.
Intuition. To know what a matrix does, you only need to know where it sends the basis vectors. The columns are the transformation.
Composition is multiplication
Apply and then : . The product's entries are
defined only when the inner dimensions agree: . Read right to left — acts first. Multiplication is associative, , but not commutative: rotating then stretching is not stretching then rotating. With above and the 90° rotation ,
A deep network is a long composition ; between the nonlinearities it is exactly matrix products, which is why shapes must chain and why gradients multiply along the chain (4.4 Backpropagation, fully derived, 6.4 Recurrent neural networks and BPTT).
Transpose and the special matrices
The transpose flips rows and columns, , and reverses products: . Two products of vectors look alike and are opposites: is the dot product (a scalar) while is the outer product, a rank-one matrix whose every column is a multiple of . The matrices with names are the ones whose geometry you should recognize on sight:
| name | definition | what it does | where you meet it |
|---|---|---|---|
| identity | nothing | residual connections 5.3 Architectures: LeNet → AlexNet → VGG → Inception → ResNet → EfficientNet → ConvNeXt | |
| diagonal | zeros off the diagonal | scales each axis independently | feature scaling, Adam's per-parameter steps 1.10 Optimization: from gradient descent to Adam |
| orthogonal | rotation or reflection; preserves lengths and angles | SVD factors 1.3 Eigen-things, SVD and low rank, rotary embeddings 7.3 Positional information: sinusoidal, learned, RoPE, ALiBi | |
| symmetric | real eigenvalues, perpendicular eigenvectors | covariance, Hessian, kernel matrices | |
| positive (semi)definite | () for all | a bowl; no direction is flipped | covariance 1.7 Probability II: Bayes, independence, MLE and MAP, convex Hessians 1.5 Multivariable and matrix calculus |
| projection | flattens onto a subspace | least squares 3.2 Linear regression, PCA 3.12 Dimensionality reduction: PCA, t-SNE and UMAP | |
| permutation | one 1 per row and column | reorders coordinates | shuffling data, reordering tokens |
Inverse, rank, column space and null space
The column space is the span of the columns — the set of outputs the transformation can reach. Its dimension is the rank. The null space is everything squashed to the origin. They are tied by rank–nullity: . A square matrix is invertible when there is an with , which happens exactly when the rank is full: nothing is squashed and every output is reachable, so the transformation can be undone. Solving then has one solution; if there is none, and if the null space is nontrivial and is reachable there are infinitely many. For matrices,
In practice you almost never form an inverse explicitly: you solve the system (np.linalg.solve), which is faster and more numerically stable. Data matrices in ML are tall and rectangular, so "inverse" becomes "least squares" (3.2 Linear regression).
The determinant: how much area scales
For a square matrix, is the signed factor by which areas (volumes in higher dimensions) scale: the unit square becomes a parallelogram of area , and a negative sign means orientation flipped. For , . The rules follow from the geometry: (areas multiply under composition), , and . The crucial fact: exactly when squashes space into a lower dimension, which is exactly when it is not invertible. For the matrix above, : areas double. Determinants of covariance matrices normalize the Gaussian density (1.7 Probability II: Bayes, independence, MLE and MAP), and the eigenvalues of 1.3 Eigen-things, SVD and low rank multiply to the determinant.
Data as a matrix, and the linear layer
Stack examples with features as rows: . A linear layer with outputs has weights and bias (PyTorch's convention) and computes, for the whole batch at once,
where the bias is added to every row (broadcasting, 2.2 NumPy and vectorized thinking). Each output column is a template match of every example against one row of : neurons evaluated on inputs in a single product. Shapes: . Parameters: . Cost: about floating-point operations (one multiply and one add per term). For a batch of 32 MNIST images () and hidden units, is , the layer has parameters and costs million flops. A transformer is mostly this operation (7.4 Inside the block: residuals, LayerNorm, FFN and embeddings); attention scores are the same product between queries and keys, (7.2 Scaled dot-product and multi-head attention, fully derived).
Worked example, end to end
Take and .
- Column picture: . Row picture: . ✓
- and . Check: . ✓
- Rank 2, null space , column space all of .
- is symmetric and positive definite, because for — the pattern behind the normal equations (3.2 Linear regression) and the SVD (1.3 Eigen-things, SVD and low rank).
Math check. . ✓
Where this shows up later
- NumPy broadcasting,
@andeinsum— 2.2 NumPy and vectorized thinking; PyTorch linear layers — 2.4 PyTorch I: tensors, autograd and the training loop, 4.1 From perceptron to MLP; universal approximation. - Normal equations and projections — 3.2 Linear regression; eigenvectors, SVD and low rank — 1.3 Eigen-things, SVD and low rank; PCA — 3.12 Dimensionality reduction: PCA, t-SNE and UMAP.
- Attention is a matrix product of queries, keys and values — 7.2 Scaled dot-product and multi-head attention, fully derived; parameter counting — 7.4 Inside the block: residuals, LayerNorm, FFN and embeddings; products of Jacobians cause vanishing gradients — 6.4 Recurrent neural networks and BPTT.
Common pitfalls (4)
- Multiplying matrices in the wrong order or forgetting that AB ≠ BA.
- Confusing the dot product xᵀy (scalar) with the outer product xyᵀ (rank-one matrix).
- Computing np.linalg.inv(A) @ b instead of np.linalg.solve(A, b) — slower and less stable.
- Forgetting PyTorch's convention that a Linear layer stores W as (out_features, in_features), so the layer computes XWᵀ.
Recap: all 7 key points
- Ax is a linear combination of the columns (column picture) and a stack of dot products with the rows (row picture); the columns are where the basis vectors land.
- Matrix multiplication is composition of transformations, read right to left: associative, not commutative, shapes (m×n)(n×p) = m×p.
- Determinant = signed area/volume scale factor; det = 0 ⇔ space is squashed ⇔ not invertible; det(AB) = det A · det B.
- Column space = reachable outputs (dimension = rank); null space = inputs squashed to zero; rank + nullity = n.
- Orthogonal matrices preserve lengths and angles; symmetric PSD matrices are bowls (covariances, Hessians at minima).
- A batched linear layer is Z = XWᵀ + b with kd + k parameters and about 2ndk flops; attention scores QKᵀ are the same operation.
- Solve linear systems with a solver, never with an explicit inverse.
Watch
Why the product formula is what it is — composition read right to left.
Read
Try it live
Interactive demo
runs in your browserExercises
- By hand: three transformations
For , a 45° rotation, and : compute where land, the determinant, the inverse (if it exists), the rank and the null space. Expected: the third matrix has rank 1, determinant 0, and a null space spanned by .
- NumPy: a linear layer with shape and flop checks
Implement
linear(X, W, b)returning forXof shape (32, 784),Wof shape (128, 784),bof shape (128,). Assert the output shape is (32, 128), count parameters, and time the product for batch sizes 32, 256, 2048. Expected: time grows roughly linearly with the batch size, matching the estimate. - Experiment: when inverses go bad
Build matrices for . Solve with
np.linalg.solveand with an explicit inverse, and compare to the true answer . Expected: the error grows as shrinks (the matrix approaches rank 1), and the explicit inverse is the worse of the two.
Quiz
Flashcards
These cards are now in your spaced-repetition queue. Review all due cards →