21.2 Matrices as Linear Maps
In Section 21.1 we read a matrix--vector product one row at a time: entry is the dot product of row with , a single hyperplane test. That row view tells us what a matrix computes for one input vector, but it hides what the matrix does to the entire input space at once. In particular, it does not tell us whether the map preserves information or throws it away, and whether its effect can ever be undone.
This question comes up as soon as a neural network layer is narrower than its input. A fully connected layer mapping the 784 pixels of a Fashion-MNIST image to 256 hidden features is a matrix. Because its output holds fewer numbers than its input, it must collapse space: by a count we will make precise shortly, at least independent input directions are sent to zero, so distinct images can produce identical features before any nonlinearity even sees them.
Even a square matrix can lose information. Consider the running matrix of this chapter, . It sends to , and there is another matrix that sends right back to . In fact, that second matrix undoes on every input, so loses nothing. Contrast this with , which sends both and to . Given only the output , we have no way to tell which input produced it, so no matrix can reverse .
Whether a linear map can be undone determines whether a layer discards information, whether a linear system has a unique solution, and how a probability density rescales under a change of variables (Section 24.2.3.1). To answer this question cleanly, we shift from rows to columns. Column of a matrix is simply where it sends the -th coordinate axis, and those images alone fix the entire map. Counting how many columns are linearly independent tells us how many input dimensions survive the map, while measuring the signed volume of the transformed unit cube gives a single number that detects whether any dimension was lost. We develop both ideas first in two dimensions, where every statement is a picture, and then extend them to dimensions.
Three results organize the section: the balance between surviving and collapsed dimensions, the exact conditions under which a square matrix has an inverse, and the rule for how volume scaling behaves when two maps are composed. The general -dimensional construction of the determinant (Section 21.2.3.2) is the most technical part and can be skimmed on a first reading.
import numpy as np21.2.1 Linear Maps#
21.2.1.1 Columns as Images of the Axes#
A matrix acts on infinitely many input vectors, yet it is stored as a finite table of numbers. How can just four numbers fix the output for every vector in the plane? Take a matrix with entries and apply it to . Collecting the terms that multiply and those that multiply gives
Thus is simply a weighted sum of the two columns of , using the coordinates of as weights. Because and , the columns are the images of the standard basis vectors and . Once we know where those two axes land, the image of every other vector in the plane is completely determined.
For our running matrix (, , , ), the two axes go to and . Since the input is , its image is the exact same combination of the columns:
Checking by rows confirms the result: and . Both views compute the same product, but the column view lets us see what does to the entire plane at once. Figure 21.2.1 illustrates this geometry: the unit square spanned by and is carried to the parallelogram spanned by the two columns, and the grid point lands on the corresponding point of the transformed grid.
The running matrix acting on the plane. (a) The input grid, shaded unit square, basis vectors, and input . (b) Its image: goes to , to , and to . Lines remain lines, the origin stays fixed, and equally spaced points stay equally spaced. The shaded square maps to the shaded parallelogram, whose area leads to the determinant. Panel (b) is drawn at one-third the scale of (a).
The same column picture holds in any dimension. An matrix maps vectors in to vectors in , and it is linear:
In words, the image of a weighted sum is the same weighted sum of the images. Writing any input as gives , where multiplying by picks out column . Conversely, every map that satisfies this linearity rule can be written as a matrix whose -th column is , because . Linear maps from to and matrices are therefore two ways of describing the same object.
Linearity is also what keeps the grid in Figure 21.2.1 looking like a grid. Every line maps to , which is again a line (or a single point if ), and the origin never moves: .
Nothing here requires the matrix to be square. A matrix maps into the span of its three columns in , filling the whole output plane as long as at least two columns are linearly independent. Going the other way, a matrix maps the plane into , where its outputs form a plane through the origin, a line, or the origin alone, depending on its two columns. Every fully connected layer in a neural network is a rectangular map of this kind, followed by a bias shift and a nonlinearity.
To build visual intuition, Figure 21.2.2 displays six matrices through their effect on the unit square. A counter-clockwise rotation sends to and to , so its columns are and . A horizontal shear leaves untouched and tilts to , sliding every horizontal line sideways in proportion to its height. The last two panels are qualitatively different: they lose a dimension, flattening the entire square, and with it the entire plane, onto a single line.
Six ways a matrix can transform the unit square (dashed). In each panel, the arrows show the columns, which are the images of (blue) and (orange), and the shaded region is the image of the square. Panels (e) and (f) collapse the plane onto a line; in (f) both columns are .
One familiar operation is noticeably absent from this gallery: a translation with . Because it moves the origin, it is not linear. An affine layer in a neural network is therefore a linear map followed by a translation.
21.2.1.2 Composition#
Two linear layers placed back to back, with no nonlinearity between them, collapse into a single linear map. Which matrix represents that combined map? Let us test this on two concrete maps from Figure 21.2.2: the rotation and the shear (named for how it tilts the vertical axis),
Both matrices will reappear throughout the chapter. Let us track where the standard basis vectors go under each ordering. If we shear first, stays at and the rotation sends it to ; meanwhile shears to and rotates to . Thus "shear, then rotate" has columns and . In the opposite order, rotating sends to , which the shear moves to , and sends to , which the shear leaves unchanged. The two composites are therefore
They are not the same map, as Figure 21.2.3 makes clear.
The order of composition matters. (a) Applying the shear (dotted outline) followed by the rotation produces . (b) Applying the rotation (dotted outline) followed by the shear produces . The labels show the final images of (blue) and (orange). Matrix products are always read from right to left.
Matrix multiplication is the algebraic rule that computes such composites. For any two matrices and whose dimensions match, apply to , then to the result, and inspect entry :
Applying the two maps in sequence is identical to applying the single matrix , whose entry is the dot product of row of with column of . Notice the order: the product means "apply first, then ," read from right to left just like function composition . Setting in (21.2.1) also gives a useful column rule: column of is , the image under of column of . We will lean on this fact when we study the determinant.
Seeing multiplication as composition explains its seemingly odd definition.
The row-times-column formula is not an arbitrary convention; it is simply what
composing two linear maps produces. It also makes the algebraic properties
immediate. Matrix multiplication is associative,
, because
function composition is associative: both sides apply , then
, then . And it is not commutative in general, because
performing two geometric operations in opposite orders usually leads to
different results. In NumPy, matrix multiplication uses the @ operator. Let
us check that it reproduces both composites of the rotation and the shear
(stored as R90 and S below).
R90 = np.array([[0.0, -1.0], [1.0, 0.0]]) # rotation by 90 degrees
S = np.array([[1.0, 1.0], [0.0, 1.0]]) # shear
print(R90 @ S)
print(S @ R90)
[[ 0. -1.]
[ 1. 1.]]
[[ 1. -1.]
[ 1. 0.]]
Of course, some pairs of matrices do commute. Two rotations in the plane commute, since rotating by and then by yields a rotation by in either order. Two diagonal matrices commute as well, since each scales the coordinate axes independently. Exercise 3 characterizes every matrix that commutes with .
21.2.1.3 Orthogonal Matrices#
Some linear maps move space rigidly, leaving every length and every angle untouched. Which matrices have this property? Consider a counter-clockwise rotation by an angle in the plane. It sends to and to , so its matrix is
Its columns have unit length, , and zero dot product, . They are orthonormal, a condition we wrote in Section 21.1 as . Setting recovers , which sends to ; both vectors have length . The reflection across the -axis has orthonormal columns as well.
In any dimension, a square matrix is called orthogonal when its columns are orthonormal, that is,
Two subtleties in this definition are worth flagging. First, columns that are merely perpendicular are not enough: has perpendicular columns of lengths and , yet it bends the angle between and into (1). Second, the name "orthogonal" is reserved for square matrices. A tall matrix with orthonormal columns still preserves lengths, but it embeds into a larger space and therefore has no two-sided inverse (Section 21.2.2.3).
An orthogonal map preserves every dot product:
Setting gives , so lengths are unchanged; and because angles depend only on dot products and lengths, angles are unchanged as well. If you rotate an entire set of embedding vectors by the same orthogonal matrix, every pairwise cosine similarity stays identical.
The defining equation says that applying after undoes it. For a square matrix , it turns out that also undoes when applied before it, , meaning the rows of are orthonormal too and . This is not obvious from the definition alone; it follows from a general theorem on square matrices that we prove in Section 21.2.2.3.
In two dimensions, rotations and reflections are the only orthogonal matrices. The first column must be a unit vector , which leaves only two unit vectors perpendicular to it for the second column: . The plus sign gives the rotation . The minus sign gives , a reflection across the -axis followed by a rotation, which is itself a reflection across a line through the origin. Later, the sign of the determinant will separate rotations from reflections at a glance (Section 21.2.3.3).
21.2.1.4 Tensors and Einstein Summation#
In a transformer, self-attention compares every query with every key, across every attention head and every sequence in a batch. Labeling the batch by , the head by , the query position by , the key position by , and the feature dimension within a head by , the attention scores are
where and are entries of the four-axis query and key tensors (Section 1.1). Each score is a dot product along the feature axis , evaluated for every combination of the other four indices. Standard matrix notation has no clean way to write this four-index contraction; calling it "a batched matrix multiplication with a transpose on the last two axes" obscures which axis is actually being summed.
Step back, and notice that every product we have met so far follows the exact same pattern. The dot product, the matrix--vector product, the matrix product, and the trace (the sum of the diagonal entries of a square matrix) all read
The trace is new here and will return in Section 21.3 as the sum of a matrix's eigenvalues. Each of these four formulas multiplies entries together and sums over an index that appears twice. Einstein notation turns that pattern into a convention: drop the summation sign and automatically sum over every repeated index. Under this rule, and .
The attention scores reveal where the classical convention falls short: the
batch and head indices and appear in both factors, yet we want to keep
them rather than sum them out. Numerical libraries solve this in einsum by
having you name the kept indices explicitly. You pass a string listing the
input indices, an arrow ->, and the output indices; any index omitted from
the right-hand side is summed over. Let us express our four basic products
this way and check them on our running matrices.
A = np.array([[1.0, 2.0], [-1.0, 3.0]]) # the running matrix
v = np.array([2.0, -1.0])
(np.einsum('i,i->', v, v), # dot product: v.v
np.einsum('ij,j->i', A, v), # matrix-vector product: Av
np.einsum('ij,jk->ik', R90, S), # matrix product: R90 S
np.einsum('ii->', A)) # trace: tr(A)(np.float64(5.0),
array([ 0., -5.]),
array([[ 0., -1.],
[ 1., 1.]]),
np.float64(4.0))
Every output matches our hand calculations from earlier, including
. The attention scores take just one
line in the same notation. Below, we compute them with einsum, verify that
they agree with a batched matrix product against the transposed keys, and
count the total number of multiply--adds.
rng = np.random.default_rng()
queries = rng.standard_normal((2, 3, 4, 8)) # (batch, heads, queries, width)
keys = rng.standard_normal((2, 3, 5, 8)) # (batch, heads, keys, width)
scores = np.einsum('bhij,bhtj->bhit', queries, keys)
(scores.shape, np.allclose(scores, queries @ keys.swapaxes(-1, -2)),
scores.size * queries.shape[-1]) # multiply-adds
((2, 3, 4, 5), True, 960)
The output has shape , giving one score table per sequence and head. Both expressions agree, and the contraction takes multiply--adds, which is simply the product of the sizes of all five indices.
Beyond code, index notation yields effortless one-line proofs. For any and , both and are square, and their traces satisfy
The middle step merely swaps two scalar numbers while leaving the indices alone. Surprisingly, the trace of a product does not depend on the order of the two factors, even when and even when the two products do not have the same dimensions. One immediate consequence will matter when we study eigenvalues: if has an inverse (Section 21.2.2.3), then . Because represents the same linear map written in a different coordinate system, the trace is an intrinsic property of the map rather than an artifact of the coordinates we chose. The determinant will turn out to share this invariance (Section 21.2.3.3).
One practical warning: when an einsum expression combines three or more
tensors, the string specifies the mathematical result but not the order in
which pairwise contractions are carried out, and that order can make a huge
difference in speed. For matrices, computing
takes roughly multiply--adds, whereas
computing takes only .
21.2.2 Rank and Invertibility#
21.2.2.1 Column Space and Null Space#
Which outputs can a matrix actually produce, and which inputs does it erase? To see both at once, examine our singular example
Its columns are and , so one is simply twice the other: . Because every output of is a weighted sum of its columns, every output collapses to a scalar multiple of :
Thus sends the entire two-dimensional plane onto the single line through . Inevitably, distinct inputs collide on that line: both and land on . By linearity, their difference must map to the difference of their outputs, . The row view gives a second way to see why: both rows of , and , are perpendicular to , so both hyperplane tests return zero. Figure 21.2.4 shows both lines side by side.
The matrix collapsing the plane. (a) In the input plane, the dashed null-space line through is perpendicular to the row direction ; three inputs are marked: , , and on the null-space line. (b) In the output plane (same scale), every output lands on the column space, the line spanned by and ; both and map to , while collapses to the origin. Because distinct inputs share the same image, no inverse can exist.
This example illustrates two fundamental subspaces attached to every matrix . The column space, written , is the span of the columns of . Since is a weighted combination of the columns with weights , the column space is precisely the set of all reachable outputs. The null space, also called the kernel and written , is the set of all inputs that sends to zero:
It is a subspace of : if , then . For , the column space is the line in the output plane, and the null space is the line through in the input plane. (That both live in is just an accident of being square; in general, and .)
Three general facts carry straight over from this example:
- The null space consists of all inputs perpendicular to every row. In the row view, is the dot product of row with , so all entries of vanish if and only if is orthogonal to every row.
- The columns are linearly dependent if and only if the null space contains a nonzero vector. A nontrivial dependence among the columns simply says for a nonzero vector , and reading the equation backwards gives the converse. For , the relation yields the null vector .
- Two inputs produce the same output if and only if they differ by a null vector. Indeed, is equivalent to . The set of all inputs that maps to is the shifted line , which passes through at . Whenever contains a nonzero vector, distinct inputs collide and no inverse can exist.
21.2.2.2 Rank#
How many input dimensions survive a linear map? The rank of a matrix is the dimension of its column space, or equivalently the maximum number of linearly independent columns:
Our matrix has rank : its two columns are dependent, and neither is zero. For a richer example, consider the matrix
which has rank : its first two columns are linearly independent, yet every one of the triples of columns is linearly dependent.
Remarkably, the number of dimensions that survive the map and the number of dimensions crushed to zero always add up to the dimension of the input space.
Proposition (rank--nullity). For an matrix ,
Proof. Pick a basis of and extend it to a basis of . (That any linearly independent list can be extended to a basis, and that all bases of a subspace have the same size, are standard facts we use without proof.) The images span , because any input is a combination of the full basis and the vanish under . They are also linearly independent: if , then lies in and can therefore be written as a combination of . Within a basis, that is impossible unless every . Hence has dimension .
Figure 21.2.5 shows the basis that the proof builds. Each of its vectors either vanishes under or contributes one dimension to the column space, and no vector does both.
The basis in the proof of rank--nullity. The vectors span and are sent to . The vectors complete them to a basis of , and their images form a basis of .
Let us check this conservation of dimensions on our examples. For
we get . For the Fashion-MNIST layer from the
opening, the rank cannot exceed the output coordinates, so the null
space must have dimension at least . For , the
null space must have dimension , meaning any three linearly
independent null vectors form a basis of . Below, we verify
that , , and all map to
zero under and check the rank of the matrix Z holding them as
columns.
B = np.array([[2.0, 1.0], [4.0, 2.0]])
C = np.array([[1, 3, 0, -1, 0], [-1, 0, 1, 1, -1],
[0, 3, 1, 0, -1], [2, 3, -1, -2, 1]], dtype=float)
Z = np.array([[3, -1, 3, 0, 0], [1, 0, 0, 1, 0],
[0, 0, 1, 0, 1]], dtype=float).T # candidate null vectors
rank_C, rank_Z = np.linalg.matrix_rank(C), np.linalg.matrix_rank(Z)
np.linalg.matrix_rank(B), rank_C, np.abs(C @ Z).max(), rank_Z, rank_C + rank_Z(np.int64(1), np.int64(2), np.float64(0.0), np.int64(3), np.int64(5))
The ranks of and come out to and , the
maximum entry of is zero, and the three columns of
Z have rank , confirming .
What if we read a matrix by rows instead of columns? Its row rank, the maximum number of linearly independent rows, counts how many independent hyperplane tests the matrix performs. In , row 3 is row 1 plus row 2 and row 4 is row 1 minus row 2, so the row rank is , matching the column rank. That agreement is universal.
Proposition (row rank equals column rank). For every matrix , the largest number of linearly independent rows equals the largest number of linearly independent columns.
Proof. Let , and place a basis of into the columns of an matrix . Since every column of is a linear combination of the columns of , storing the coefficients for column of in column of an matrix gives the factorization
Now read the same product by rows. Row of is , so every row of lies in the span of the rows of . Thus the row rank of is at most . Repeating the argument for , whose columns are the rows of , shows that the column rank is at most the row rank, so the two must be equal.
The factorization is more than a proof device. It reveals that any rank- matrix passes its input through a bottleneck of width : compresses to numbers, and expands those numbers back to . When is much smaller than and , storing and requires only parameters instead of , which is the core idea behind the low-rank updates of Section 21.5.4.1.
In practice, finding rank by testing subsets of columns would take
exponentially long. By hand one uses Gaussian elimination (which this chapter
does not cover). Numerical libraries like np.linalg.matrix_rank instead
count how many singular values (Section 21.5) exceed a
small tolerance. A tolerance is unavoidable because rank is not a continuous
function of the matrix entries: a tiny perturbation can jump the rank from
deficient to full (Section 21.2.3.6).
21.2.2.3 Inverses#
Given an output , when can we reliably recover the input ? An inverse of a square matrix is a matrix that undoes from both sides:
so that for every input . For a matrix with entries satisfying , there is an explicit formula:
A quick multiplication confirms it: multiplying by in either order yields , and dividing by leaves . The condition cannot be dropped. If , that product is the zero matrix; multiplying both sides by a hypothetical inverse would force , and hence , which plainly has no inverse. We will meet the quantity again as a signed area in Section 21.2.3.1. For our running matrix, , so
Sure enough, reverses the worked example of Section 21.2.1.1.
Whenever an inverse exists, it is unique. Even better, any left inverse and any right inverse of the same matrix must coincide: if and , then by associativity,
When does an inverse exist in general? For a square matrix, the answer requires only the null space and rank--nullity, and the rest of this chapter relies on it more than on any other result in this section.
Proposition (invertible matrices). For an matrix , the following are equivalent: (i) is invertible; (ii) the columns of are linearly independent; (iii) ; (iv) .
Proof. Statements (ii) and (iii) are equivalent by fact 2 of Section 21.2.2.1, and (iii) and (iv) are equivalent by rank--nullity. If is invertible and , multiplying on the left by gives , so (i) implies (iii).
The converse takes more work because we must actually construct the inverse. By (iv), the column space is an -dimensional subspace of , which must be all of : appending any vector outside it to a basis of would produce linearly independent vectors in , which is impossible. Thus every target vector in is reached. By (iii) and fact 3, no two inputs map to the same output. We can therefore define column of a matrix to be the unique solution of . By construction, . To see that also works on the left, take any : since and no two inputs collide, we must have . Hence as well, and .
This immediately settles the claim left open in Section 21.2.1.3. For a square orthogonal matrix (satisfying ), if , then , so . By the proposition, is invertible, its left inverse must equal , and therefore .
A square matrix that has no inverse is called singular; is our standard example. Rectangular matrices never have a two-sided inverse at all. The rank of an matrix is at most . When , the column space has dimension at most , so the map is not onto: some targets in can never be hit. When , rank--nullity forces a null space of dimension at least , so the map is not one-to-one: distinct inputs collide. Running a map backwards requires both properties, and the beauty of the proposition above is that for a square matrix, either one guarantees the other.
21.2.2.4 Solving Linear Systems in Practice#
The matrix inverse is an indispensable tool for algebra and proofs, yet in
numerical computation we almost never form it explicitly. When you need to
solve , use np.linalg.solve(A, b) rather
than np.linalg.inv(A) @ b.
There are two main reasons: speed and accuracy. First, solve factors
once into triangular matrices (an LU factorization, costing
about multiply--adds) and solves two fast triangular systems. Forming
explicitly costs roughly multiply--adds, three times
as much work, before you even multiply by . Second, solve is
backward stable: its computed solution is the exact solution to a slightly
perturbed system whose entries differ from and only
at the level of floating-point rounding. Consequently, its residual
stays on the order of machine
precision times (using the spectral norm of
Section 1.3.4). Computing inv(A) @ b carries no such
guarantee; its residual can be larger by a factor up to the condition number
, which measures how close is to being
singular (Section 21.5.3.2).
How close a matrix sits to singularity is a property of the problem itself, not of the algorithm. In double precision (roughly sixteen decimal digits), both methods can lose up to about digits of accuracy in the solution . That is a worst-case bound rather than an exact prediction for any single right-hand side, so let us see how close a notorious example comes to it. The Hilbert matrix, with entries , is a classic test case of a nearly singular matrix. We take , form for the Hilbert matrix , and attempt to recover both ways.
H = 1 / (np.arange(10)[:, None] + np.arange(10) + 1) # Hilbert matrix
x_true = np.ones(10)
b = H @ x_true
for x in (np.linalg.solve(H, b), np.linalg.inv(H) @ b):
print(f'residual {np.linalg.norm(H @ x - b):.1e}, '
f'error {np.linalg.norm(x - x_true):.1e}')
np.linalg.cond(H)residual 5.7e-16, error 2.7e-04
residual 4.8e-05, error 9.0e-03
np.float64(16024416987428.36)
The condition number is ,
warning us that up to thirteen digits can vanish. As promised, solve keeps
its residual near machine precision, while inv suffers a residual roughly
eleven orders of magnitude larger, right in line with the factor .
Notice, however, that a tiny residual does not guarantee an accurate
solution. Both routes lose twelve or more of the sixteen digits, approaching
the worst-case bound, with inv still worse by more than an order of
magnitude.
Sparse matrices add a third, decisive reason never to invert. A million-by-million matrix with only five million nonzero entries fits comfortably in memory, whereas its inverse is typically completely dense, requiring roughly entries.
21.2.3 The Determinant#
21.2.3.1 Area of a Parallelogram#
By what factor does a matrix scale areas? Look back at Figure 21.2.1: our running matrix sends the unit square (edges and , area ) to the parallelogram with edges and and corners , , , and . That parallelogram sits snugly inside the bounding box of area . The unused portion of the box consists of four right triangles with legs and , and , and , and and , whose areas sum to . Subtracting leaves an area of (Figure 21.2.6, panel (a)). The matrix multiplies the area of the unit square by .
The image of the unit square under has area . (a) Bounding-box method: the box of area minus four right triangles of total area . (b) Base times height: the base has length , the unit normal is perpendicular to it, and the height of above the base line is .
Carving out triangles works for one picture, but every new arrangement of corners would need a new diagram. Base times height handles every case in one stroke. Let the parallelogram have edges and , the two columns of a general matrix. Its base has length . Rotating counter-clockwise by gives , so
is a unit vector perpendicular to the base. From Section 21.1, the signed component of along a unit vector is the dot product . Geometrically, this is the height of the parallelogram above its base, equipped with a sign: positive when lies on the counter-clockwise side of , and negative when it lies on the clockwise side. Multiplying base by signed height gives
Conveniently, the lengths cancel out, leaving a clean polynomial in the four matrix entries with no sign cases to split. For our running matrix, , , and , giving a signed area of (panel (b)), positive because lies counter-clockwise from .
We define the determinant of a matrix to be this signed area of the image of the unit square:
Its magnitude is the factor by which the map scales area, and its sign records whether the images of and preserve their counter-clockwise orientation. For , we get . Swapping the two columns of produces , which spans the exact same parallelogram with its edges listed in the reverse order, and its determinant flips sign to . For the singular matrix , we get : the unit square flattens onto the line segment from to , which has zero area.
Figure 21.2.7 contrasts all three regimes: a positive determinant preserves orientation, a negative determinant reverses it, and a zero determinant collapses the square.
The determinant as signed area for our three examples. The unit square (dashed) maps to the region spanned by the columns. (a) , with determinant : the columns keep their counter-clockwise order (curved arrow). (b) with its columns swapped, determinant : the same parallelogram with reversed orientation. (c) , determinant : the square collapses onto a segment of the line . Panel (c) is drawn at half the scale of (a) and (b).
Base times height gives us the plane. To move to dimensions, we need the signed volume of an -dimensional box.
21.2.3.2 The Determinant in General#
How do we define the signed volume of the box spanned by columns in ? Rather than trying to compute high-dimensional volumes by chopping up shapes, we take a cleaner route: we write down the three geometric properties any signed volume must satisfy, and let those properties uniquely determine the formula. Viewed as a function of the columns of an matrix, the determinant is:
- Multilinear: linear in each column separately while the other columns are held fixed. (Scaling one edge of a box scales its volume by the same factor; writing one edge as a sum splits the volume accordingly.)
- Alternating: equal to zero whenever two columns are identical. (When two edges coincide, the box collapses into a lower-dimensional slab of zero volume.)
- Normalized: . (The unit cube has volume .)
Check that our formula satisfies all three: it is linear in and in , it vanishes whenever , and it equals on . Two powerful consequences follow immediately from these three axioms alone: a rule for swapping columns, and an explicit formula proving that at most one function can satisfy all three.
First, swapping any two columns flips the sign of the determinant. To see why, place in two column slots and expand using multilinearity:
The left-hand side, the first term, and the last term all have two identical columns, so they vanish by the alternating property. What remains is
Exchanging two edges of the box reverses its orientation, just as we saw in panel (b) of Figure 21.2.7.
Second, the three properties completely determine a formula. Expand each column in the standard basis as and apply multilinearity column by column. This turns into a large sum of terms , one for every choice of a row index in each column . Whenever two chosen row indices are equal, the term vanishes by the alternating property. When all row indices are distinct, the list is just a reordering of the columns of , so repeated column swaps reduce to .
In the case, with columns and , the expansion has four terms. The two with a repeated basis vector drop out, leaving
recovering the signed area we derived by hand. In general, is a signed sum over all ways of picking one entry from every row and every column. Writing for the row chosen in column , we obtain the permutation formula:
where ranges over all permutations of , and is if requires an even number of swaps and if it requires an odd number. Because any function satisfying the three axioms must equal this formula, there can be at most one determinant.
We do not prove existence in full here. The subtle point is that is well defined (no permutation can be built from both an even and an odd number of swaps), a standard fact we take from (Horn and Johnson, 2012). Once that parity fact is in hand, the formula satisfies all three axioms: each term contains one entry from each column (giving multilinearity), only the identity permutation survives for (giving normalization), and the alternating property follows from the same parity argument (which we omit).
Notice that normalization entered only at the very end of the derivation. That observation gives us a sharper tool that we will use in the next subsection: if is any multilinear and alternating function of the columns, the same swap rule and expansion apply, turning every factor into . Consequently,
In short, every multilinear alternating function of the columns is just a scalar multiple of the determinant.
For small hand calculations, grouping the terms of (21.2.7) by the row picked in column produces the cofactor expansion: each entry multiplies the determinant of the submatrix formed by deleting row and column , weighted by the alternating sign . For the matrix
expanding along the first column gives
Thus maps the unit cube in to a box of volume .
For a triangular matrix, the determinant simplifies dramatically: it is just the product of the diagonal entries. Of all the rules for computing determinants, this is the one to remember. Suppose is upper triangular, so whenever . In the permutation formula, a nonzero term must pick one entry from every column, all in distinct rows. From column , the only nonzero entry sits in row . From column , row is already taken and rows are zero, forcing us to pick row . Continuing across the columns, only the diagonal permutation survives, and it requires zero swaps, so
Running the same argument backwards from column covers lower triangular matrices. Better still, it extends to blocks. Consider a block upper triangular matrix whose square diagonal blocks and need not be triangular themselves. Any nonzero permutation term must pick its entries in the columns of from the rows of , because everything underneath is zero. That consumes all rows of , forcing the remaining columns to pick from the rows of ; the off-diagonal block never contributes at all. Every surviving permutation splits into a pair of independent permutations on the two blocks, their signs multiply, and the sum factors cleanly:
Figure 21.2.8 marks the entries that survive in each case.
Entries that enter the determinant. (a) In an upper triangular matrix, the zeros below the diagonal rule out every permutation except the diagonal one, so the determinant is the product of the diagonal entries. (b) In a block upper triangular matrix, the zero block confines every surviving permutation to the diagonal blocks and . The entries marked never enter.
These two rules are essential in modern machine learning, not just in hand calculations. A normalizing flow transforms a simple random variable through an invertible neural network and must evaluate the log-determinant of the network's Jacobian at every step, because a change of variables divides the probability density by the local volume scaling factor (Section 24.2.3.1). Flows are therefore designed so that each layer has a triangular or block-triangular Jacobian: the log-determinant then reduces to a sum of scalar logarithms, avoiding the roughly multiply--adds required for a general matrix.
Another useful symmetry is that transposing leaves the determinant unchanged: . In the permutation formula for , each term is . Setting rewrites the product as , which is the term for corresponding to the inverse permutation . Since undoing a sequence of swaps takes the exact same number of swaps, . The two sums therefore contain the exact same terms, which means every statement about columns of a determinant applies equally well to rows.
With terms, the permutation formula is strictly a theoretical tool and is
never used numerically beyond tiny matrices. Libraries compute determinants by
factoring the matrix into triangular factors (as in solve) and multiplying
their diagonal entries, adjusting the sign for any row exchanges, at a cost
of roughly multiply--adds.
21.2.3.3 Multiplicativity#
If scales areas by and scales them by , then applying followed by should scale areas by the product of the two factors. Let us check two examples. For our running matrix, , which has . For the composite of Section 21.2.1.2, , matching .
A simple tiling picture explains why this should hold in general. Cover any planar region with a fine grid of tiny squares. Because a linear map acts uniformly across space, it carries every square to a parallelogram whose area is times that of the original square. Consequently, a linear map scales the area of every shape by . Applying to a region of area produces area , and applying next scales it to . Since the composite is itself a single linear map, its scaling factor must be this product. Using the characterization from Section 21.2.3.2, we can turn that intuition into a three-line proof that handles the signs as well.
Proposition (multiplicativity of the determinant). For square matrices and of the same size,
Proof. Fix and treat as a function of the columns of . By Section 21.2.1.2, column of is . Because is linear and is multilinear, is multilinear in the columns of . If two columns of coincide, the matching columns of coincide too, so and is alternating. Every multilinear alternating function of the columns is a scalar multiple of the determinant (Section 21.2.3.2), which gives
Four consequences of (21.2.9) appear repeatedly throughout the rest of this chapter:
- Determinants commute even when matrices do not. Because determinants are ordinary scalars, . For our rotation and shear, , yet both products have determinant .
- Similarity invariance. For any invertible matrix , applying consequence 1 to the factors and gives . The matrix is simply the map written in the coordinate system whose axes are the columns of , and changing coordinates cannot alter the volume scaling factor.
- Inverses. If is invertible, setting yields . Therefore every invertible matrix satisfies and (for our running matrix, ).
- Orthogonal matrices. Combining multiplicativity with on gives
so . Rigid motions never change volume, and the sign distinguishes orientation-preserving rotations () from orientation-reversing reflections () in the plane (Section 21.2.1.3).
21.2.3.4 Invertibility and the Determinant#
The determinant adds a fifth equivalent condition to the invertibility theorem of Section 21.2.2.3, and it is the only one expressed as a single number. In two dimensions the equivalence is immediate: the signed area vanishes if and only if the two columns lie on the same line through the origin (or one of them is ), which is to say, if and only if the columns are linearly dependent. The same holds in every dimension.
Proposition (invertibility and the determinant). An matrix is invertible if and only if . Equivalently, if and only if the columns of are linearly dependent.
Proof. If is invertible, then by consequence 3 of multiplicativity, so . Conversely, suppose is not invertible. By the proposition in Section 21.2.2.3, its columns are linearly dependent, so some column is a combination of the others: . Expanding column by multilinearity gives , where now appears both in slot and in slot . Every term has two identical columns and therefore vanishes by the alternating property.
For our running matrix, certifies invertibility; for , confirms singularity. Keep in mind, however, what this theorem does not promise: a nonzero determinant guarantees that exists mathematically, not that it is safe to compute numerically (Section 21.2.3.6).
21.2.3.5 Block Matrices and Low-Rank Updates#
Often we already know the inverse of a part of a matrix: of one block, or of the matrix as it was before a small change. Can we reuse it? The answer comes from a single step of elimination, carried out on blocks instead of numbers. Split a square matrix into four blocks , , , and , with square and invertible. Subtracting times the first block row from the second clears the lower-left block, and the same step on the columns clears the upper-right one. Written as a product, this reads
as multiplying out the three factors confirms. The matrix is the Schur complement of : it is what remains of once the first block has been eliminated. For our running matrix with blocks, .
Both outer factors are triangular with ones on the diagonal, so each has determinant . Multiplicativity and the block rule then give (in the example, ), and is invertible if and only if is. An outer factor is inverted by flipping the sign of its off-diagonal block. Inverting the three factors in reverse order therefore yields
The lower-right block of is simply , and the upper-left block is . Nothing forces us to start in the upper-left corner, however. Eliminating first exchanges the roles of the blocks, and the upper-left block of then appears as the inverse of the other Schur complement, . That matrix returns as the conditional covariance of a Gaussian in Section 24.3.3.3.
The two expressions for the upper-left block must agree, and this is surprisingly useful. Suppose that we know for an matrix , and that then changes by a matrix of rank , which we write as with . Choose the blocks , , , and . One Schur complement is then , and the other is the matrix . Equating the two upper-left blocks gives the Woodbury identity
A change of rank in a matrix changes its inverse by a matrix of rank at most , and finding that change requires only a inverse. With in hand, the update costs on the order of multiply--adds instead of the of a fresh inversion. When is diagonal, solving a system with costs only on the order of . The two eliminations also give two expressions for , and hence . For the inner inverse is a division, and the identity is known as the Sherman--Morrison formula:
This formula is why a least-squares fit can absorb or drop one example at a time: each example changes by a rank-one term. Exercise 6 applies both the determinant and the inverse to a normalizing flow.
21.2.3.6 Limits of the Determinant#
Knowing that tells us a matrix can be inverted, but it says nothing about how close the matrix is to collapsing space, or along which directions. Two stark examples make the point from opposite extremes. First, the scaled identity is as well-behaved as a matrix can be, with inverse , yet its determinant is so tiny that it underflows beneath the smallest positive double-precision floating-point number. Second, the extreme shear has determinant , yet changing its lower-left entry by just makes it singular (5).
Below, we compute both determinants (using slogdet for the first to obtain
its sign and log-magnitude safely) along with the singular values of the
shear. Before running the cell, guess what rank NumPy will report for the
unchanged shear.
sign, logdet = np.linalg.slogdet(0.1 * np.eye(400))
print(np.linalg.det(0.1 * np.eye(400)), sign, logdet)
shear = np.array([[1.0, 1e8], [0.0, 1.0]])
print(np.linalg.det(shear), np.linalg.matrix_rank(shear),
np.linalg.svd(shear, compute_uv=False))
shear[1, 0] = 1e-8
print(np.linalg.det(shear), np.linalg.matrix_rank(shear))
0.0 1.0 -921.0340371976151
1.0 1 [1.e+08 1.e-08]
0.0 1
As expected, det on underflows to 0.0, while
slogdet computes effortlessly. The unchanged
shear has determinant , and the perturbed shear has determinant up to
rounding, yet matrix_rank reports rank for both. In exact arithmetic
the unchanged shear has rank , but its two singular values are roughly
and . NumPy treats any singular value as zero once it falls
below the largest singular value times the matrix size times machine
precision, here . Even though the shear's entries are stored exactly, floating-point
arithmetic with numbers of size introduces rounding errors around
, so numerically the shear is indistinguishable from a singular
matrix.
A single number simply cannot capture how a matrix stretches and compresses space along different directions. To see those directions, we need eigenvalues and singular values. For our running matrix , the eigenvalues are , whose product is (Section 21.3), and the singular values are roughly and , whose product is (Section 21.5). In fact, for every square matrix, the determinant is the product of its eigenvalues (counted with multiplicity, including complex pairs), and is the product of its singular values. It is the ratio of the largest to the smallest singular value, not the determinant, that measures how close a matrix is to collapsing space, and finding those directional factors is our next task.
21.2.4 Summary#
A matrix is a linear map completely determined by its columns, which record
where the standard coordinate axes land, and matrix multiplication is simply
the composition of linear maps read from right to left. Einstein notation and
einsum unify dot products, matrix products, traces, and multi-axis tensor
contractions such as transformer attention under a single index rule.
Every matrix defines a column space of reachable outputs and a null space of inputs sent to zero, linked by the rank--nullity theorem : a layer necessarily erases at least input dimensions. For a square matrix, having independent columns, trivial null space, full rank, a nonzero determinant, and an inverse are all equivalent. The determinant measures the signed factor by which a map scales volume; it multiplies under composition and equals the product of the diagonal entries for any triangular matrix. One step of block elimination produces the Schur complement, which gives the determinant and the inverse of a block matrix and, through the Woodbury identity, the inverse of a matrix after a low-rank change. Still, while a nonzero determinant guarantees that an inverse exists, it cannot tell us how close a matrix is to singularity, a question that leads directly to eigenvalues and singular values.
21.2.5 Exercises#
-
Maps that preserve angles. Rotating every embedding vector by the same orthogonal matrix leaves all cosine similarities unchanged. This problem finds every linear map with that property.
- Find the condition on the columns of a square matrix under which and are orthogonal. Show that satisfies it but changes the angle between and .
- Suppose that an invertible preserves the angle between every pair of nonzero vectors. Apply this to the pairs and for to show that for some , so that with orthogonal. Conversely, show that every such matrix preserves all cosine similarities.
- Suppose instead that for every . Expand and to show that preserves every dot product, and conclude that is orthogonal.
-
Rank of a product. A linear autoencoder sends a -dimensional input through a hidden layer of width , with and .
- Let be an matrix and an matrix. Show that the column space of lies in the column space of , and that the null space of lies in the null space of . Use the first fact, and rank--nullity with the second, to prove .
- Conclude that has rank at most . What is the smallest possible dimension of its null space? What is the largest dimension of a subspace on which the autoencoder reconstructs every input exactly?
- Construct a matrix and a matrix, both of rank two, whose product has rank one.
-
Matrices that commute with a rotation. Matrix products do not commute in general. This problem finds the exceptions for .
- Find all matrices with , and show that they are .
- Using , show that , so these matrices multiply like the complex numbers .
- For , show that for the angle with , a scaled rotation. Compute its determinant, and conclude that it is invertible unless .
- Does the running matrix commute with ? Compute both products.
-
Householder reflections. Let be a unit vector in and .
- Show that is symmetric and orthogonal, that , and that for every perpendicular to , so that reflects in the hyperplane with normal .
- Write with , and explain the formula with the projection onto from Section 21.1: what does do to the component of along ?
- Prove . Extend to an orthonormal basis, the columns of an orthogonal matrix , compute , and use multiplicativity.
- Find the unit vector whose reflection sends to (hint: is parallel to ), write down , and check . Reflections of this kind, applied column by column, are how libraries factor a matrix into an orthogonal and a triangular factor.
-
[code] Determinant and near-singularity. A square matrix is invertible if and only if its determinant is nonzero. How well does the size of the determinant measure how close a matrix is to being singular?
- Use multilinearity to prove for an matrix and a scalar , and check the identity in code for the matrix of (21.2.8) with .
- Draw an lower triangular matrix with independent standard
Gaussian entries on and below the diagonal, for , , and
. Compare the logarithm that
np.linalg.slogdetreturns with the sum of the logarithms of the absolute diagonal entries, which the triangular rule makes exact up to rounding. From which on do the two disagree, and by how much at ? Computenp.linalg.condfor and , and explain the failure. (The routine does not know that the matrix is triangular. It factors it with row exchanges, like any other matrix.) - The text states that a change of in the lower left entry makes the shear singular. Verify it, and show that no smaller change of a single entry does.
-
Determinant of a rank-one update. ● A planar flow (Rezende and Mohamed, 2015) transforms by for vectors , a scalar , and a scalar nonlinearity . Computing the density of requires the determinant of the Jacobian .
- Use multilinearity and the alternating property to show for matrices with .
- Verify the two factorizations
Use the permutation formula (21.2.7) to show that a matrix whose last column is has the determinant of its upper-left block. Deduce from (21.2.9) and the triangular rule.
- Write the logarithm of the absolute Jacobian determinant of a planar flow, and compare the cost of evaluating it with the cost of a general determinant. For , which values of keep the Jacobian invertible at every ?
- Use the Sherman--Morrison formula (21.2.13) to write the inverse of the Jacobian , where . Check that the formula breaks down at the same values of at which the determinant vanishes, and count the multiply--adds needed to apply the inverse to a vector. The inverse Jacobian does not invert itself: show that recovering from reduces to solving one scalar equation for .
- [code] Einstein summation for attention. Let the query, key and value
tensors have the shapes , and
.
- Write the
einsumstrings for the scores and for the weighted sum of values , where are the attention weights, and check both against@withswapaxes. - Count the multiply--adds of each contraction as a product of the sizes. Compare them with the multiply--adds of applying one linear map to every query, and find the number of keys beyond which the scores cost more.
- Write ,
and as one
einsumeach for a random matrix, and check that they agree. Which of the two equalities is an instance of (21.2.2), and why does the other one hold?
- Write the