Linear Algebra
Every quantity a network touches is a tensor, and every layer is a matrix acting on one. This lesson compiles the linear algebra deep learning actually uses: products and norms, the system and when it is solvable, the two decompositions (eigen and SVD) that diagonalize a transformation, and the pseudoinverse that solves what cannot be solved exactly.
╌╌╌╌
A neural network is a pipeline of linear maps interleaved with nonlinearities. Strip the nonlinearities and what remains, the weight matrices, the activations, the gradients, is pure linear algebra: a composition of matrix products acting on arrays of numbers. This lesson is the working vocabulary, distilled to the objects a network manipulates and the two decompositions that explain what those objects do to space.1
Objects: scalars, vectors, matrices, tensors
The data structures form a ladder by number of indices.
| Object | Indices | Notation | Example in a network |
|---|---|---|---|
| scalar | a learning rate, a single loss value | ||
| vector | one input example, a bias | ||
| matrix | a weight layer, a batch of vectors | ||
| tensor | , entry | a batch of RGB images |
A vector is a point in -dimensional space; its entries are coordinates. A matrix has entry in row , column . The transpose mirrors across the main diagonal, , turning an matrix into an one; for a product it reverses order, .
Broadcasting lets operations on mismatched shapes proceed by implicitly replicating along missing or size- axes. Adding a bias vector to every column of is the broadcast ; Goodfellow writes this , with added to each row. The rule is mechanical: align shapes from the right, and any axis of size (or absent) is stretched to match.2 The same tensor objects and shape rules are what every framework's array type exposes directly.3
Two products
There are two different multiplications
of arrays, and conflating them is the
most common shape bug in practice.
A single dense layer is the matrix product with ; the elementwise activation and the gradient masks of backpropagation are Hadamard products. The dot product of two vectors is the special case , a scalar measuring alignment.4
For example, for and the shared inner dimension is summed away, leaving a result:
Entry is the dot product of row of the left factor with column of the right factor. When a layer processes a batch of examples at once, the same rule applies with the batch stacked as rows: times yields , one output row per example, and the bias broadcasts down the rows. Reading a layer as a shape transformation is the fastest way to catch a bug before it runs:
Linear systems:
A matrix times a vector is a system of linear equations. Solving asks which input the map sends to a target . The answer is governed by three intertwined notions: span, linear independence, and rank.
For to have a solution for every , the columns must span , requiring and . For the solution to be unique, the columns must be linearly independent, requiring . Both at once force square () and full rank, the condition under which the inverse exists.
A matrix as a transformation of space
Geometrically, is a linear map: it sends the unit square (spanned by the basis vectors ) to the parallelogram spanned by 's columns. Full rank means the parallelogram has nonzero area: the map does not collapse a dimension.
The signed area of that parallelogram is the determinant, met below. It records exactly how much scales volumes, and it is zero precisely when is singular.
Norms: measuring size
A norm assigns a nonnegative length to a vector, with only at , scaling , and the triangle inequality . The family covers most of what a network needs.
| Norm | Formula | Geometry / use |
|---|---|---|
| sparsity-inducing; grows linearly near | ||
| (Euclidean) | ordinary distance; | |
| , | interpolates the family | |
| (max) | largest coordinate; the limit | |
| Frobenius | the norm of a matrix's entries |
The squared norm is preferred in objectives because its gradient is cheap and it is differentiable everywhere, unlike , whose derivative misbehaves at the origin. The norm is what induces sparsity: because it grows at the same rate ( per unit) no matter how close a coordinate is to zero, it pushes coordinates exactly to zero, which does not.
Unit balls
The set , the surface of the unit ball, pictures each norm. The shapes explain the sparsity behavior: regularizing toward the origin pulls a solution to the boundary of one of these balls, and the diamond's corners sit on the axes, where coordinates vanish.
Special matrices
Three structured forms recur because each makes a hard operation cheap.
| Type | Definition | Why it matters |
|---|---|---|
| diagonal | for | scales coordinate by ; inverse is |
| symmetric | real eigenvalues, orthogonal eigenvectors (spectral theorem) | |
| orthogonal | ; preserves lengths and angles |
An orthogonal matrix is a rotation or reflection: it moves points without distorting them, since . Diagonal matrices are the cheap case of every operation (multiply, invert, take powers), and that cheapness drives the decompositions below, which aim to turn a general matrix into a diagonal one in the right coordinates.
Eigendecomposition
An eigenvector of a square is a direction the map only stretches, never rotates; the stretch factor is its eigenvalue.
Stacking the eigenvectors as columns of and the eigenvalues on the diagonal of , the relations assemble into the eigendecomposition:
This says does nothing more than: change to the eigenbasis (), scale each axis (), change back (). The picture is a space stretched along its eigenvector axes.
Eigenvalues come from the condition that have a nonzero solution, i.e. that collapse a direction to zero, i.e. that — the characteristic polynomial. For ,
so , . Substituting into gives , the direction ; gives . Normalizing, the eigenvectors are and — orthogonal, as the spectral theorem promises for a symmetric . The map stretches the direction by and leaves fixed. The trace equals , and the determinant equals , the two scalar checks below.
Quadratic forms and positive-definiteness
The eigenvalues classify the quadratic form (for symmetric ). In the eigenbasis, writing ,
so the sign of the form is decided entirely by the signs of the eigenvalues.
| Condition on eigenvalues | Name | Quadratic form |
|---|---|---|
| all | positive definite | for all |
| all | positive semidefinite | for all |
| all | negative definite | for all |
| mixed signs | indefinite | both signs occur |
Positive-definiteness is the multivariate second derivative is positive
: a
critical point where the Hessian is positive definite is a local minimum, where
it is negative definite a maximum, and where it is indefinite a saddle point. This is the
classification that drives the entire study of the
optimization landscape.
Singular value decomposition
Eigendecomposition needs a square, diagonalizable matrix. The singular value decomposition has no such restriction; it factors any matrix.5
The columns of are left-singular vectors (eigenvectors of ), the columns of are right-singular vectors (eigenvectors of ), and the singular values are the square roots of the shared nonzero eigenvalues, . Geometrically the factorization reads right-to-left as rotate, scale, rotate: rotates the input, scales along axes, rotates the output. A unit circle becomes an ellipse whose axis lengths are the singular values.
In the caption, stand for the singular values , the ellipse's semi-axis lengths. (Greek sigma is spelled out in the figure to keep the node text renderable.)
The Moore–Penrose pseudoinverse
When is not square, is over- or under-determined and has no exact inverse. The SVD supplies the next best thing: the pseudoinverse, where inverts each nonzero singular value () and transposes. It returns the least-error, smallest-norm answer.
| Shape of | System | What gives |
|---|---|---|
| tall (), full rank | over-determined, no exact | the least-squares solution minimizing |
| wide (), full rank | under-determined, many | the solution of minimum |
| square, full rank | unique | exactly |
The least-squares case is the normal-equations solution seen for linear regression, now derived through the SVD and valid even when is singular.
Trace and determinant
Two scalar summaries of a square matrix close the toolkit.
Worked example: principal components analysis
PCA is the canonical application of this machinery: a derivation in which the answer to a geometric optimization is a set of eigenvectors.6 The setup: points in (assume centered, mean zero), to be compressed to dimensions with the least reconstruction error.
Encode each point by projecting onto an orthonormal set of directions stacked as columns of (), and decode by projecting back:
Choose to minimize the total squared reconstruction error, .
The covariance is symmetric, so the spectral theorem guarantees a real, orthonormal eigenbasis: the principal axes. The first principal component is the direction of greatest variance; projecting onto it loses the least information.
The compression keeps the top axes and discards the rest. Because variance along the discarded axes is smallest, the data, projected onto an -dimensional subspace, loses the least possible squared error, which is exactly the SVD's low-rank approximation guarantee restated for data.
Low rank as a design principle
Low rank has also become a design principle for large models, not only an analysis tool.
Low-rank adaptation. Fine-tuning a large model by updating every weight is expensive. LoRA (Hu et al., 2021) freezes a pretrained weight matrix and learns only a low-rank correction , where and with . The update has rank at most , so it costs parameters instead of — for a layer and , that is trainable numbers instead of million. The hypothesis, borne out empirically, is that the adaptation a task needs lies on a low-dimensional subspace even when the model does not: the SVD's rank structure applied to a weight update.
Randomized SVD. The exact SVD costs , prohibitive for the huge matrices in modern pipelines. Randomized SVD (Halko, Martinsson, Tropp, 2011) projects the matrix onto a small random subspace, computes an exact decomposition of the tiny result, and recovers the top- singular vectors in — the standard route to PCA on data too large for the full factorization.
Attention as a matrix product. Transformer attention is : two matrix products with a row-wise softmax between them (Vaswani et al., 2017). Every idea in this lesson — shapes that must line up, the contraction that sums an inner dimension away, the scaling that keeps the dot products in a stable range — appears in this one operation at the center of the field.78
Takeaways
- Every quantity in a network is a tensor; layers are matrix products (), gates and gradient masks are Hadamard products ().
- is solvable iff lies in the column space; the inverse exists iff is square and full rank. Geometrically maps the unit square to a parallelogram whose signed area is .
- Norms measure size; (diamond, sparsity), (circle, distance), (square, max), Frobenius (matrix). The unit-ball corners of explain why it zeroes coordinates.
- Eigendecomposition diagonalizes a square map along its invariant axes; the spectral theorem makes this orthogonal for symmetric , and the eigenvalue signs classify the quadratic form (positive-definite local minimum).
- SVD exists for any matrix and reads as rotate–scale–rotate; it yields the pseudoinverse , the least-squares / minimum-norm solver for non-invertible systems.
- PCA is the worked example: minimizing reconstruction error is maximizing projected variance, whose optimum is the top eigenvectors of , the same statement as the SVD's low-rank approximation.
Footnotes
- Goodfellow, Deep Learning, Ch. 2 — Linear Algebra: the minimal algebra a network needs, framed as the objects (tensors) and the operations (products, decompositions) that move them through a model. ↩
- Goodfellow, Deep Learning, §2.1 — Scalars, Vectors, Matrices and Tensors: implicit broadcasting of a bias vector across a matrix, , as the convenient shape-shorthand frameworks adopt. ↩
- Stevens, Deep Learning with PyTorch, Ch. 3 — It Starts with a Tensor: the tensor as the fundamental storage type, with shape, stride, and dtype the first things any operation must reconcile. ↩
- Goodfellow, Deep Learning, §2.2–§2.3 — Multiplying Matrices and Vectors: the contraction (matrix) product versus the elementwise (Hadamard) product, and the dot product as the alignment special case. ↩
- Goodfellow, Deep Learning, §2.8 — Singular Value Decomposition: for any real matrix, generalizing eigendecomposition to non-square and non-diagonalizable maps. ↩
- Goodfellow, Deep Learning, §2.12 — Example: Principal Components Analysis: deriving PCA as the linear code that minimizes reconstruction error, whose optimum is the top eigenvectors of the covariance. ↩
- Hu, Shen, Wallis, Allen-Zhu, Li, Wang, Wang, Chen (2021), LoRA: Low-Rank Adaptation of Large Language Models, arXiv:2106.09685 — a rank- additive update to a frozen weight matrix; and Halko, Martinsson, Tropp (2011), Finding Structure with Randomness, SIAM Review 53, the randomized range-finder behind fast approximate SVD/PCA. ↩
- Vaswani, Shazeer, Parmar, Uszkoreit, Jones, Gomez, Kaiser, Polosukhin (2017), Attention Is All You Need, NeurIPS — scaled dot-product attention as the matrix-product core of the transformer. ↩
╌╌ END ╌╌