Course contents 01 / 16

01 / 16 · Linear Algebra

Vectors, spaces and linear maps

What a vector is beyond a list of numbers, how many numbers a space really needs, and why every linear map is a matrix once a basis is fixed, with composition as multiplication and rank–nullity.

On this page 14

A flat with 70 square metres, 3 rooms and an age of 25 years becomes the list x=(70,3,25)x = (70, 3, 25). A word becomes a row of 768 numbers, an image a grid of pixel intensities. Machine learning works with such lists, and its simplest building block, inside every regression and every layer of a network, multiplies them by weights and adds up the results.

Lists are enough to compute with, but they leave three questions open. The same arrow in the plane has different coordinates in different coordinate systems, so which properties belong to the arrow and which to its list? Polynomials, images and matrices are not lists of features, yet they can be added and scaled in the same way. And how many numbers does a dataset really need? If every flat had exactly 20 square metres per room, the area and the number of rooms would carry the same information, and three columns would hold two numbers’ worth of data.

The answers take three definitions: a vector space, a basis and a linear map. They pay off in one fact. Once a basis is fixed, every linear map is a table of numbers, and composing maps is multiplying tables.

Vector spaces: what can be added and scaled#

Two flats can be added entry by entry, (70,3,25)+(50,2,5)=(120,5,30)(70, 3, 25) + (50, 2, 5) = (120, 5, 30), and the sum can be scaled by 12\tfrac12 to give their average, (60,2.5,15)(60, 2.5, 15). Arrows in the plane are added tip to tail and stretched by a number, and the coordinates of a sum of arrows are the sums of their coordinates. Write R\mathbb R for the real numbers and Rn\mathbb R^n for the lists of nn of them, written as columns.

A vector space keeps only these two operations. It is a set VV with an addition u+vu + v and a scaling avav by real numbers, both giving elements of VV, such that for all u,v,w∈Vu, v, w \in V and a,b∈Ra, b \in \mathbb R:

  • addition is commutative and associative: u+v=v+uu + v = v + u and (u+v)+w=u+(v+w)(u + v) + w = u + (v + w);
  • there is a zero vector 00 with v+0=vv + 0 = v, and every vv has a negative −v-v with v+(−v)=0v + (-v) = 0;
  • scaling is compatible with numbers: 1v=v1 v = v and (ab)v=a(bv)(ab) v = a(bv);
  • the two distributive laws hold: a(u+v)=au+ava(u + v) = au + av and (a+b)v=av+bv(a + b) v = av + bv.

These are the rules that lists obey entry by entry, and nothing more is assumed. Everything that follows uses only these rules, so it applies at once to Rn\mathbb R^n; to the polynomials of degree at most 2, c0+c1t+c2t2c_0 + c_1 t + c_2 t^2, added coefficient by coefficient; to the m×nm \times n matrices, added entry by entry; and to the real functions on an interval, with (f+g)(t)=f(t)+g(t)(f + g)(t) = f(t) + g(t).

Small facts follow from the rules alone. For instance 0v=00v = 0 for every vv: by the second distributive law 0v=(0+0)v=0v+0v0v = (0 + 0)v = 0v + 0v, and adding −0v-0v to both sides leaves 0=0v0 = 0v.

Subspaces#

A subspace of VV is a subset UU that contains 00 and is closed under the two operations: u+w∈Uu + w \in U and au∈Uau \in U whenever u,w∈Uu, w \in U. A subspace is a vector space in its own right.

The plane U={x∈R3:x1+x2−x3=0}U = \{x \in \mathbb R^3 : x_1 + x_2 - x_3 = 0\} is a subspace, where xix_i is the ii-th entry of xx. It contains 00. If xx and yy satisfy the equation, so does x+yx + y, whose left side is 0+00 + 0, and so does axax, whose left side is a⋅0a \cdot 0. The parallel plane x1+x2−x3=1x_1 + x_2 - x_3 = 1 is not a subspace: it misses 00, and the sum of two of its points has 2 on the right.

Lines and planes through the origin are subspaces; lines and planes that miss it are not. Neither is the set of probability vectors, pi≥0p_i \ge 0 with ∑ipi=1\sum_i p_i = 1, which contains no negatives; it is convex, the subject of the convexity note. The set of all predictions XwXw of a linear model, as ww varies, is a subspace: the column space of the least-squares note.

Span and linear independence#

A linear combination of v1,…,vkv_1, \dots, v_k is a vector c1v1+⋯+ckvkc_1 v_1 + \dots + c_k v_k with numbers cic_i. The set of all of them is the span, span⁡(v1,…,vk)\operatorname{span}(v_1, \dots, v_k). It is a subspace, since sums and multiples of combinations are combinations, and it is the smallest subspace containing the viv_i, since any subspace that contains them contains all their combinations.

Take v1=(1,0,1)v_1 = (1, 0, 1) and v2=(0,1,1)v_2 = (0, 1, 1). Every combination is c1v1+c2v2=(c1,c2,c1+c2)c_1 v_1 + c_2 v_2 = (c_1, c_2, c_1 + c_2), with the third entry equal to the sum of the first two. So (2,3,5)=2v1+3v2(2, 3, 5) = 2v_1 + 3v_2 is in the span, (1,1,1)(1, 1, 1) is not, and the span is exactly the plane UU of the previous section.

Vectors v1,…,vkv_1, \dots, v_k are linearly independent if the only combination that gives zero is the trivial one:

c1v1+⋯+ckvk=0  ⟹  c1=⋯=ck=0.c_1 v_1 + \dots + c_k v_k = 0 \;\Longrightarrow\; c_1 = \dots = c_k = 0 .

Otherwise they are dependent, and one of them is a combination of the others: if cj≠0c_j \ne 0 in a combination that gives zero, divide by cjc_j and solve for vjv_j. Removing that vjv_j does not shrink the span.

The vectors (1,2)(1, 2), (3,4)(3, 4) and (5,6)(5, 6) are dependent, since (1,2)−2 (3,4)+(5,6)=(0,0)(1, 2) - 2\,(3, 4) + (5, 6) = (0, 0). That any three vectors in the plane are dependent follows from the exchange lemma below, applied with the spanning list e1,e2e_1, e_2: an independent list in R2\mathbb R^2 has at most 2 vectors (Axler, 2024, 2.22).

Exchange lemma. If w1,…,wmw_1, \dots, w_m span VV, then every independent list in VV has at most mm vectors.

Proof

Let u1,…,uku_1, \dots, u_k be independent. Since the ww‘s span VV, u1u_1 is a combination of them, with some nonzero coefficient because u1≠0u_1 \ne 0 (an independent list contains no zero vector, since 1⋅0=01 \cdot 0 = 0 is a nontrivial combination); replace that ww by u1u_1. The new list still spans VV, because the removed ww can be solved for from the expression of u1u_1. Repeat: at step jj, uju_j is a combination of the current list, and some remaining ww has a nonzero coefficient, since otherwise uju_j would be a combination of u1,…,uj−1u_1, \dots, u_{j-1}, against independence; replace that ww by uju_j. After jj steps the list holds u1,…,uju_1, \dots, u_j and m−jm - j of the ww‘s and still spans VV. If k>mk \gt m, after mm steps the list u1,…,umu_1, \dots, u_m spans VV, so um+1u_{m+1} is a combination of it, against independence. So k≤mk \le m.

Basis, dimension and coordinates#

A basis of VV is a list b1,…,bnb_1, \dots, b_n that is independent and spans VV. The standard basis e1,…,ene_1, \dots, e_n of Rn\mathbb R^n, where eie_i has a 1 in position ii and zeros elsewhere, is one of infinitely many.

Why ask for both conditions? Spanning guarantees that every vector vv can be built from the basis, v=c1b1+⋯+cnbnv = c_1 b_1 + \dots + c_n b_n. Independence guarantees that it can be built in only one way, because two lists of coefficients would give

c1b1+⋯+cnbn=d1b1+⋯+dnbn(c1−d1) b1+⋯+(cn−dn) bn=0ci−di=0for every i,\begin{aligned} c_1 b_1 + \dots + c_n b_n &= d_1 b_1 + \dots + d_n b_n \\ (c_1 - d_1)\, b_1 + \dots + (c_n - d_n)\, b_n &= 0 \\ c_i - d_i &= 0 \quad \text{for every } i , \end{aligned}

by the distributive laws and then by independence. The unique numbers cic_i are the coordinates of vv in the basis, and the vector and its list of coordinates carry the same information.

In the basis b1=(1,1)b_1 = (1, 1), b2=(1,−1)b_2 = (1, -1) of the plane, the vector v=(3,1)v = (3, 1) has coordinates (2,1)(2, 1): the equations c1+c2=3c_1 + c_2 = 3 and c1−c2=1c_1 - c_2 = 1 give c1=2c_1 = 2 and c2=1c_2 = 1. In the standard basis the same vector has coordinates (3,1)(3, 1). Coordinates describe a vector relative to a basis; the vector itself does not change.

When VV is spanned by finitely many vectors, every basis of VV has the same number of vectors. The exchange lemma, applied with one basis as the spanning list and the other as the independent one, bounds each length by the other. That common number is the dimension, dim⁡V\dim V. So dim⁡Rn=n\dim \mathbb R^n = n; the plane UU has dimension 2, with basis v1,v2v_1, v_2; the polynomials of degree at most 2 have dimension 3, with basis 1,t,t21, t, t^2, in which 3+2t+5t23 + 2t + 5t^2 has coordinates (3,2,5)(3, 2, 5); and the m×nm \times n matrices have dimension mnmn, with the basis of matrices EijE_{ij} that have a single 1 in row ii and column jj (Axler, 2024, 3.40).

Two consequences are used constantly. Adding a vector ww outside the span of an independent list keeps the list independent: in a combination c w+c1v1+⋯+ckvk=0c\,w + c_1 v_1 + \dots + c_k v_k = 0, a nonzero cc would put ww in the span, so c=0c = 0, and then every ci=0c_i = 0. Hence, in a space of dimension nn, any nn independent vectors are a basis: a vector outside their span would give n+1n + 1 independent vectors, more than a spanning basis of nn vectors allows. And any nn vectors that span are a basis: if they were dependent, removing one that is a combination of the others would leave n−1n - 1 spanning vectors, and the nn independent vectors of a basis would break the exchange lemma (Axler, 2024, 2.38 and 2.42).

Once a basis is fixed, coordinates turn every nn-dimensional space into Rn\mathbb R^n: adding vectors adds their coordinates. Computations can always be done with lists, and the choice of basis changes the numbers but not the conclusions.

Linear maps#

A map T:V→WT: V \to W takes each element of VV to an element of WW. It is linear if it respects both operations:

T(u+v)=T(u)+T(v),T(av)=a T(v).\begin{aligned} T(u + v) &= T(u) + T(v), \\ T(av) &= a\, T(v) . \end{aligned}

Together, T(au+bv)=a T(u)+b T(v)T(au + bv) = a\,T(u) + b\,T(v): the image of a combination is the same combination of the images. Rotations of the plane about the origin are linear. A rotation carries the parallelogram with sides uu and vv to the parallelogram with sides T(u)T(u) and T(v)T(v), so it sends the diagonal u+vu + v to T(u)+T(v)T(u) + T(v); and it sends avav, the arrow on the line of vv that is aa times as long, to a T(v)a\,T(v). The same picture works for stretches along an axis and for reflections in a line through the origin. Differentiation of polynomials is linear too, D(p)=p′D(p) = p', since (p+q)′=p′+q′(p + q)' = p' + q' and (ap)′=ap′(ap)' = ap'; so are the predictions of a linear model as a function of its weights, w↦Xww \mapsto Xw; and so is expectation, E[aX+bY]=a E[X]+b E[Y]\mathbb E[aX + bY] = a\,\mathbb E[X] + b\,\mathbb E[Y].

A shift x↦x+bx \mapsto x + b with b≠0b \ne 0 is not linear, because a linear map sends 00 to 00: T(0)=T(0⋅0)=0⋅T(0)=0T(0) = T(0 \cdot 0) = 0 \cdot T(0) = 0. A linear map followed by a shift is called affine. The ReLU x↦max⁡(0,x)x \mapsto \max(0, x) is not linear either, since max⁡(0,−1)=0\max(0, -1) = 0 while −max⁡(0,1)=−1-\max(0, 1) = -1. Neither is the length of a vector.

A linear map is fixed by what it does to a basis. If v=c1b1+⋯+cnbnv = c_1 b_1 + \dots + c_n b_n, linearity gives T(v)=c1T(b1)+⋯+cnT(bn)T(v) = c_1 T(b_1) + \dots + c_n T(b_n). The nn vectors T(b1),…,T(bn)T(b_1), \dots, T(b_n) determine TT everywhere. Conversely, any vectors w1,…,wnw_1, \dots, w_n of WW define a linear map by T(c1b1+⋯+cnbn)=c1w1+⋯+cnwnT(c_1 b_1 + \dots + c_n b_n) = c_1 w_1 + \dots + c_n w_n. The rule is well defined because coordinates are unique, and linear because the coordinates of au+bvau + bv are aa times those of uu plus bb times those of vv.

The matrix of a linear map#

Take T:Rn→RmT: \mathbb R^n \to \mathbb R^m and collect the images of the standard basis vectors as the columns of a table, aj=T(ej)a_j = T(e_j). This table is a matrix A∈Rm×nA \in \mathbb R^{m \times n}, with mm rows, nn columns and the entry aija_{ij} in row ii and column jj. Where does TT send an arbitrary xx? Write xx in the standard basis and use linearity:

T(x)=T(x1e1+⋯+xnen)entries are coordinates=x1 T(e1)+⋯+xn T(en)linearity=x1 a1+⋯+xn an=Ax.\begin{aligned} T(x) &= T(x_1 e_1 + \dots + x_n e_n) && \text{entries are coordinates} \\ &= x_1\, T(e_1) + \dots + x_n\, T(e_n) && \text{linearity} \\ &= x_1\, a_1 + \dots + x_n\, a_n \\ &= Ax . \end{aligned}

The last line defines the matrix–vector product: AxAx is the combination of the columns of AA with weights xjx_j. Applying a linear map is multiplying by its matrix, and the jj-th column of the matrix is the image of eje_j. Read entry by entry, the same product is the familiar row formula,

(Ax)i=∑j=1naij xj,(Ax)_i = \sum_{j=1}^n a_{ij}\, x_j ,

row ii of AA multiplied by xx entry by entry and summed. With numbers the row formula is quicker; for reasoning the columns are the better view (Strang, 2016, section 1.3).

Let TT send e1e_1 to (2,0)(2, 0) and e2e_2 to (1,1)(1, 1). Then

A=(2101),A(3−2)=3(20)−2(11)=(4−2),\begin{aligned} A &= \begin{pmatrix} 2 & 1 \\ 0 & 1 \end{pmatrix}, \\ A \begin{pmatrix} 3 \\ -2 \end{pmatrix} &= 3 \begin{pmatrix} 2 \\ 0 \end{pmatrix} - 2 \begin{pmatrix} 1 \\ 1 \end{pmatrix} = \begin{pmatrix} 4 \\ -2 \end{pmatrix} , \end{aligned}

and the row formula agrees: 2⋅3+1⋅(−2)=42 \cdot 3 + 1 \cdot (-2) = 4 and 0⋅3+1⋅(−2)=−20 \cdot 3 + 1 \cdot (-2) = -2.

The recipe works for any spaces with chosen bases: column jj holds the coordinates of the image of the jj-th basis vector. Differentiation from the polynomials of degree at most 2 (basis 1,t,t21, t, t^2) to those of degree at most 1 (basis 1,t1, t) sends 1↦01 \mapsto 0, t↦1t \mapsto 1 and t2↦2tt^2 \mapsto 2t, so

D=(010002),D(325)=(210).\begin{aligned} D &= \begin{pmatrix} 0 & 1 & 0 \\ 0 & 0 & 2 \end{pmatrix}, \\ D \begin{pmatrix} 3 \\ 2 \\ 5 \end{pmatrix} &= \begin{pmatrix} 2 \\ 10 \end{pmatrix} . \end{aligned}

The derivative of 3+2t+5t23 + 2t + 5t^2 is 2+10t2 + 10t: differentiation has become a 2×32 \times 3 matrix.

What does a linear map do to a line? The points p+tdp + td of the line through pp with direction dd go to T(p)+t T(d)T(p) + t\,T(d), by linearity. If T(d)≠0T(d) \ne 0 this is again a line, with direction T(d)T(d); if T(d)=0T(d) = 0 the line collapses to a point. So an invertible map sends lines to lines, keeps parallel lines parallel, since a common direction dd goes to a common direction T(d)T(d), and keeps the equally spaced points t=0,1,2,…t = 0, 1, 2, \dots equally spaced. Every linear map fixes the origin. The unit square goes to the parallelogram spanned by the two columns, and, for an invertible map, the unit circle goes to an ellipse with half-axes σ1\sigma_1 and σ2\sigma_2, the singular values derived in the SVD note.

Figure

A linear map sends a grid to a grid and a circle to an ellipse

The image of a grid and of the unit circle under two matricesThree panels. Left: a square grid on [−1, 1]², the unit circle, the basis vectors e₁, e₂ and a dashed line ker B along (2, −1). Middle: under A the grid becomes a grid of parallelograms, the circle an ellipse, e₁ goes to (2, 0) and e₂ to (1, 1). Right: B flattens the whole plane onto the line im B along (2, 1); the circle becomes a segment.the input xAx: A invertibleBx: B of rank 1e₁e₂ker BAe₁ = (2, 0)Ae₂ = (1, 1)Be₁Be₂im BThe image of a grid and of the unit circle under two matricesThree panels. Left: a square grid on [−1, 1]², the unit circle, the basis vectors e₁, e₂ and a dashed line ker B along (2, −1). Middle: under A the grid becomes a grid of parallelograms, the circle an ellipse, e₁ goes to (2, 0) and e₂ to (1, 1). Right: B flattens the whole plane onto the line im B along (2, 1); the circle becomes a segment.the input xAx: A invertibleBx: B of rank 1e₁e₂ker BAe₁ = (2, 0)Ae₂ = (1, 1)Be₁Be₂im B
Each panel is the image of the picture on the left. A = (2 1; 0 1) sends e₁ to (2, 0) and e₂ to (1, 1): the grid becomes parallelograms and the circle an ellipse. B = (1 2; 1/2 1) has rank 1: the plane collapses onto im B along (2, 1), and ker B along (2, −1) goes to 0.

Composition is matrix multiplication#

Apply T:Rn→RpT: \mathbb R^n \to \mathbb R^p with matrix AA, and then S:Rp→RmS: \mathbb R^p \to \mathbb R^m with matrix BB. The composition S∘TS \circ T, defined by (S∘T)(x)=S(T(x))(S \circ T)(x) = S(T(x)), is again linear, by the linearity of TT and then of SS,

S(T(au+bv))=S(a T(u)+b T(v))=a S(T(u))+b S(T(v)),\begin{aligned} S(T(au + bv)) &= S(a\,T(u) + b\,T(v)) \\ &= a\,S(T(u)) + b\,S(T(v)) , \end{aligned}

so it has a matrix, and its jj-th column is where eje_j goes:

(S∘T)(ej)=S(aj)aj=T(ej)=Baj=a1j b1+⋯+apj bp,\begin{aligned} (S \circ T)(e_j) &= S(a_j) && a_j = T(e_j) \\ &= B a_j \\ &= a_{1j}\, b_1 + \dots + a_{pj}\, b_p , \end{aligned}

where bkb_k are the columns of BB. So column jj of the product BABA is BB times column jj of AA, and its ii-th entry is row ii of BB against column jj of AA:

(BA)ij=∑k=1pbik akj.(BA)_{ij} = \sum_{k=1}^p b_{ik}\, a_{kj} .

The shapes must match: (m×p)(p×n)(m \times p)(p \times n) gives m×nm \times n. The order reads right to left, BABA for “first AA, then BB”.

The rules of the product come from composition without any computation with entries. It is associative, (CB)A=C(BA)(CB)A = C(BA), because composing functions is, and a linear map has exactly one matrix, so equal maps have equal matrices. The identity matrix II, with ones on the diagonal, is the map that changes nothing. And it is not commutative, because doing TT and then SS is usually not doing SS and then TT. Let RR rotate the plane by 90°90° and GG stretch it by 2 along the first axis:

R=(0−110),G=(2001),RG=(0−120),GR=(0−210).\begin{aligned} R &= \begin{pmatrix} 0 & -1 \\ 1 & 0 \end{pmatrix}, \\ G &= \begin{pmatrix} 2 & 0 \\ 0 & 1 \end{pmatrix}, \\ RG &= \begin{pmatrix} 0 & -1 \\ 2 & 0 \end{pmatrix}, \\ GR &= \begin{pmatrix} 0 & -2 \\ 1 & 0 \end{pmatrix} . \end{aligned}

RGRG stretches first, e1↦(2,0)↦(0,2)e_1 \mapsto (2, 0) \mapsto (0, 2), its first column. GRGR rotates first, e1↦(0,1)e_1 \mapsto (0, 1), which the stretch along the first axis leaves alone.

Associativity does not make the two orders of evaluation equally cheap. Multiplying an m×pm \times p matrix by a p×np \times n one takes mpnmpn multiply–adds, since each of the mnmn entries is a sum of pp products. For n×nn \times n matrices AA, BB and a vector xx, (AB)x=A(Bx)(AB)x = A(Bx), but the left side costs n3+n2n^3 + n^2 multiply–adds and the right side 2n22n^2: for n=1000n = 1000, about 10910^9 against 2⋅1062 \cdot 10^6. Backpropagation exploits exactly this, multiplying a vector through a chain of Jacobians and never forming their product (why reverse mode is cheap).

Composition also explains why depth needs nonlinearities. Two linear layers, x↦W2W1xx \mapsto W_2 W_1 x, are one linear map with matrix W2W1W_2 W_1: the second layer adds parameters and no expressive power (why stacking linear layers is not enough).

Changing the basis#

The matrix of a map depends on the basis, and a good basis can make it much simpler. Let the columns of PP be a new basis p1,…,pnp_1, \dots, p_n of Rn\mathbb R^n. A vector with new coordinates cc is x=Pcx = Pc, and PP has an inverse P−1P^{-1}, which recovers c=P−1xc = P^{-1}x. Because the columns are a basis, every xx has exactly one coordinate vector cc; the map x↦cx \mapsto c is linear, by the uniqueness of coordinates, and its matrix is P−1P^{-1} (the next note computes inverses). To apply AA in the new coordinates, translate to the standard basis, apply AA, and translate back:

x=Pcstandard coordinatesAx=APcP−1Ax=P−1AP cnew coordinates.\begin{aligned} x &= Pc && \text{standard coordinates} \\ Ax &= APc \\ P^{-1}Ax &= P^{-1}AP\, c && \text{new coordinates} . \end{aligned}

In the basis p1,…,pnp_1, \dots, p_n the map x↦Axx \mapsto Ax has the matrix P−1APP^{-1}AP.

For the matrix AA of the previous section take p1=(1,0)p_1 = (1, 0) and p2=(1,−1)p_2 = (1, -1). Then Ap1=(2,0)=2p1Ap_1 = (2, 0) = 2p_1 and Ap2=(1,−1)=p2Ap_2 = (1, -1) = p_2, so

P=(110−1),P−1AP=(2001).\begin{aligned} P &= \begin{pmatrix} 1 & 1 \\ 0 & -1 \end{pmatrix}, \\ P^{-1} A P &= \begin{pmatrix} 2 & 0 \\ 0 & 1 \end{pmatrix} . \end{aligned}

In this basis the map only stretches the first coordinate by 2 and keeps the second. Here P−1=PP^{-1} = P, since P2=IP^2 = I. Finding such a basis, one in which a map scales each coordinate separately, is the subject of the eigenvalue note.

Kernel and image#

Two subspaces come with every linear map T:V→WT: V \to W. The kernel, or null space, ker⁡T={v∈V:T(v)=0}\ker T = \{v \in V : T(v) = 0\}, holds the vectors the map sends to zero. The image, or range, im⁡T={T(v):v∈V}\operatorname{im} T = \{T(v) : v \in V\}, holds everything the map can reach. Both are subspaces: if T(u)=T(v)=0T(u) = T(v) = 0 then T(au+bv)=0T(au + bv) = 0, and a T(u)+b T(v)=T(au+bv)a\,T(u) + b\,T(v) = T(au + bv) is again in the image. For a matrix, the image is the span of the columns, the column space, since AxAx is a combination of the columns. The rank of TT is the dimension of its image.

The kernel measures what the map loses. T(u)=T(v)T(u) = T(v) exactly when T(u−v)=0T(u - v) = 0: two inputs become indistinguishable exactly when they differ by a kernel vector. So TT is one-to-one exactly when ker⁡T={0}\ker T = \{0\}.

Take

B=(121/21),Bx=(x1+2x2)(11/2).\begin{aligned} B &= \begin{pmatrix} 1 & 2 \\ 1/2 & 1 \end{pmatrix}, \\ Bx &= (x_1 + 2x_2) \begin{pmatrix} 1 \\ 1/2 \end{pmatrix} . \end{aligned}

Both columns lie on the line through (2,1)(2, 1), so the image is that line and the rank is 1. The kernel is the line x1+2x2=0x_1 + 2x_2 = 0, spanned by (2,−1)(2, -1); indeed B(2,−1)=(0,0)B(2, -1) = (0, 0). The right panel of the figure shows the whole plane flattened onto the image. For differentiation DD of polynomials of degree at most 2, the kernel is the constants, of dimension 1, and the image is all polynomials of degree at most 1, of dimension 2, since c0+c1tc_0 + c_1 t is the derivative of c0t+12c1t2c_0 t + \tfrac12 c_1 t^2.

The rank–nullity theorem#

In both examples the two dimensions add up to the dimension of the input: 1+1=21 + 1 = 2 for BB and 1+2=31 + 2 = 3 for DD. This always holds. The kernel uses up some of the input’s dimensions by sending them to zero, and the rest pass to the image without loss (Axler, 2024, 3.21; the counting theorem of Strang, 2016, section 3.5):

dim⁡ker⁡T+rank⁡T=dim⁡V.\dim \ker T + \operatorname{rank} T = \dim V .

For a matrix A∈Rm×nA \in \mathbb R^{m \times n}, dim⁡ker⁡A+rank⁡A=n\dim \ker A + \operatorname{rank} A = n, the number of columns. The dimension of the kernel is also called the nullity.

Proof

Take a basis u1,…,uku_1, \dots, u_k of ker⁡T\ker T and extend it by v1,…,vrv_1, \dots, v_r to a basis of VV, adding vectors outside the current span until it spans; by the exchange lemma this stops, and k+r=dim⁡Vk + r = \dim V. It suffices to show that T(v1),…,T(vr)T(v_1), \dots, T(v_r) is a basis of im⁡T\operatorname{im} T. They span it: every v∈Vv \in V is ∑iaiui+∑jcjvj\sum_i a_i u_i + \sum_j c_j v_j, and since each uiu_i is in the kernel,

T(v)=∑iai T(ui)+∑jcj T(vj)=∑jcj T(vj).\begin{aligned} T(v) &= \sum_i a_i\, T(u_i) + \sum_j c_j\, T(v_j) \\ &= \sum_j c_j\, T(v_j) . \end{aligned}

They are independent: if ∑jcjT(vj)=0\sum_j c_j T(v_j) = 0, then ∑jcjvj\sum_j c_j v_j is in the kernel and equals some ∑iaiui\sum_i a_i u_i. That is a combination of the basis u1,…,uk,v1,…,vru_1, \dots, u_k, v_1, \dots, v_r equal to zero, so every cjc_j is zero. Hence rank⁡T=r=dim⁡V−k\operatorname{rank} T = r = \dim V - k.

The theorem is used throughout the course. If n>mn \gt m, a map Rn→Rm\mathbb R^n \to \mathbb R^m has rank at most mm, so its kernel has dimension at least n−m>0n - m \gt 0: a map to fewer dimensions always sends different inputs to the same output.

For a square matrix, one-to-one and onto are the same property. With n=mn = m, the kernel is {0}\{0\} exactly when the rank is nn, that is, when the image is all of Rn\mathbb R^n. Such a matrix is invertible.

A product never has more rank than its factors. The image of BABA lies inside the image of BB, so rank⁡(BA)≤rank⁡B\operatorname{rank}(BA) \le \operatorname{rank} B. And BABA is BB applied to the image of AA, a space of dimension rank⁡A\operatorname{rank} A, so rank–nullity for BB restricted to that space, whose kernel is ker⁡B∩im⁡A\ker B \cap \operatorname{im} A, gives

rank⁡(BA)=rank⁡A−dim⁡(ker⁡B∩im⁡A)≤rank⁡A.\begin{aligned} \operatorname{rank}(BA) &= \operatorname{rank} A - \dim(\ker B \cap \operatorname{im} A) \\ &\le \operatorname{rank} A . \end{aligned}

Where machine learning uses it#

A dataset of NN examples with dd features is NN points of Rd\mathbb R^d, the rows of a design matrix X∈RN×dX \in \mathbb R^{N \times d}.

A linear layer computes h=Wx+bh = Wx + b, an affine map; appending a constant 1 to the input folds the shift into one matrix, (W  b)(W \ \ b). Rank–nullity says what the linear part keeps: a layer from 768 numbers to 64 has a kernel of dimension at least 704, and moving the input along it leaves the output unchanged. The rank bound on products gives an update ΔW=BA\Delta W = BA with inner dimension rr a rank of at most rr, the idea of LoRA.

An embedding lookup applies a matrix to a basis vector. The one-hot vector of token ii is eie_i, and E⊤eiE^\top e_i is the ii-th row of the embedding table EE, where the transpose E⊤E^\top swaps rows and columns.

Where it breaks#

Rank, independence and dimension are exact notions, and measured data are not exact. Return to the flats. Fifty flats, each with 20 square metres per room, an integer number of rooms and an age, give a 50×350 \times 3 matrix whose area column is 20 times the rooms column: its rank is 2. Now record the areas with a measurement error of half a square metre. The rank becomes 3, and every test above reports three independent columns.

The third direction is almost empty. The singular values that the SVD note defines measure how much of the data lies along each direction: for this matrix they are 502502, 144144 and 0.170.17. A useful rank therefore needs a threshold, and the conditioning note shows what a nearly dependent set of columns does to the solution of a system.

Linear maps are also a small class. The ReLU, the softmax and the products inside attention are not linear. A network alternates linear maps with nonlinearities, and the calculus section approximates a nonlinear map near a point by a linear one, its Jacobian.

The plan of the course#

The course has four sections, and each ends with tools that another course on this site uses directly.

SectionWhat it buildsWhere it is used next
Linear Algebralinear systems, projections and QR, eigenvalues, symmetric matrices, the SVDleast squares, PCA, the multivariate Gaussian, Gaussian processes
Calculusgradients, Jacobians and Hessians, matrix calculus, change of variablesbackpropagation, the Laplace approximation, normalizing flows
Optimizationconvexity, gradient descent and Newton’s method, KKT conditions, dualityoptimizers, the SVM dual
Numerical Computationconditioning, stability, iterative solversevery solver above, in floating point

What you should remember#

  • A vector space is a set where addition and scaling obey the rules of lists; a subspace contains 0 and is closed under both.
  • A basis is an independent spanning list; coordinates in it are unique, and every basis has dim⁡V\dim V vectors.
  • Column jj of the matrix of TT is T(ej)T(e_j), and AxAx is the combination of the columns with weights xjx_j.
  • BABA means “first AA, then BB”: associative, not commutative, and the order of evaluation changes the cost.
  • In the basis given by the columns of PP, the matrix becomes P−1APP^{-1}AP.
  • dim⁡ker⁡A+rank⁡A=n\dim \ker A + \operatorname{rank} A = n: a map to fewer dimensions always loses a subspace of inputs.

Code#

The examples of the note, checked with NumPy and SciPy. Seeds are fixed; exact numbers can differ slightly across platforms and library versions, and a basis vector of a kernel can come out with the opposite sign. The script runs in about a second.

import numpy as np
from scipy.linalg import null_space

rng = np.random.default_rng(0)
rank = np.linalg.matrix_rank

# span and subspaces: is a vector a combination of (1, 0, 1) and (0, 1, 1)?
S = np.column_stack([[1, 0, 1], [0, 1, 1]])
for v in ([2, 3, 5], [1, 1, 1]):
    c, res, *_ = np.linalg.lstsq(S, v, rcond=None)
    print(v, c.round(3), 'in the span' if np.allclose(S @ c, v) else 'not in the span')
# [2, 3, 5] [2. 3.] in the span | [1, 1, 1] [0.667 0.667] not in the span

# linear independence: three vectors in R^2 are always dependent
V = np.column_stack([[1, 2], [3, 4], [5, 6]])
print(rank(V), V @ [1, -2, 1])            # 2 [0 0]: (1, 2) - 2 (3, 4) + (5, 6) = 0

# coordinates in the basis b1 = (1, 1), b2 = (1, -1)
C = np.column_stack([[1, 1], [1, -1]])
print(np.linalg.solve(C, [3, 1]))         # [2. 1.]: (3, 1) = 2 b1 + 1 b2

# the matrix of a map has the images of the basis vectors as columns
A = np.array([[2., 1], [0, 1]])
print(A @ [1, 0], A @ [0, 1], A @ [3, -2])   # [2. 0.] [1. 1.] [ 4. -2.] = 3 A e1 - 2 A e2
# the same map in the basis (1, 0), (1, -1) is diagonal
P = np.column_stack([[1, 0], [1, -1]])
print(np.linalg.inv(P) @ A @ P)          # [[2. 0.] [0. 1.]]

# differentiation of polynomials of degree at most 2, in the bases 1, t, t^2 and 1, t
D = np.array([[0, 1, 0], [0, 0, 2]])
print(D @ [3, 2, 5], rank(D), np.abs(null_space(D).ravel()).round(3))   # [ 2 10] 2 [1. 0. 0.]: 3 + 2t + 5t^2 -> 2 + 10t

# composition is the matrix product, and the order matters
R = np.array([[0, -1], [1, 0]])          # rotation by 90 degrees
G = np.diag([2, 1])                      # stretch along the first axis
print((R @ G).tolist(), (G @ R).tolist())   # [[0, -1], [2, 0]] [[0, -2], [1, 0]]
x = np.array([1, 0])
print(R @ (G @ x), (R @ G) @ x)          # [0 2] [0 2]: stretch first, then rotate

# associativity: same result, different cost (multiply-adds for n x n matrices and a vector)
n = 300
A1, B1, x1 = rng.normal(size=(n, n)), rng.normal(size=(n, n)), rng.normal(size=n)
print(np.allclose((A1 @ B1) @ x1, A1 @ (B1 @ x1)), n**3 + n**2, 2 * n**2)   # True 27090000 180000

# kernel and image of the rank-one map B = [[1, 2], [1/2, 1]]
B = np.array([[1, 2], [0.5, 1]])
k = null_space(B).ravel()
print(rank(B), (k / k[0] * 2).round(3), B @ [2, -1], B @ [1, 0], B @ [0, 1])
# 1 [ 2. -1.] [0. 0.] [1.  0.5] [2. 1.]: kernel spanned by (2, -1), image by (2, 1)

# rank-nullity: dim ker + rank = number of columns, for several shapes
for shape, r in (((3, 5), None), ((5, 3), None), ((4, 4), 2), ((6, 4), 3)):
    M = rng.normal(size=shape) if r is None else rng.normal(size=(shape[0], r)) @ rng.normal(size=(r, shape[1]))
    print(shape, rank(M), null_space(M).shape[1], rank(M) + null_space(M).shape[1] == shape[1])
# (3, 5) 3 2 True | (5, 3) 3 0 True | (4, 4) 2 2 True | (6, 4) 3 1 True

# a linear layer from 768 to 64 numbers: a 704-dimensional kernel, and the rank of a product
W = rng.normal(size=(64, 768)) / np.sqrt(768)
K = null_space(W)
z = rng.normal(size=768)
print(K.shape[1], np.abs(W @ z - W @ (z + 5 * K[:, 0])).max() < 1e-12)       # 704 True
U = rng.normal(size=(768, 64))
print(rank(U @ W), rank(W @ U))          # 64 64: rank(UW) <= min(rank U, rank W)

# a linear layer with a bias, and the same layer as one matrix acting on (x, 1)
Wl = np.array([[1, 0, -1], [2, 1, 0]]); b = np.array([0.5, -1]); xl = np.array([1, 2, 3])
print(Wl @ xl + b, np.column_stack([Wl, b]) @ np.r_[xl, 1])   # [-1.5  3. ] [-1.5  3. ]

# an embedding lookup is a product with a one-hot vector
E = np.array([[0.1, 0.3], [0.7, -0.2], [0.4, 0.4], [-0.5, 0.9]])   # 4 tokens, 2 dimensions
e3 = np.eye(4)[2]
print(E.T @ e3, E[2])                    # [0.4 0.4] [0.4 0.4]

# where it breaks: 50 flats with 20 m^2 per room have rank 2; half a square metre of noise gives rank 3
rng = np.random.default_rng(0)
rooms = rng.integers(1, 6, 50).astype(float); age = rng.uniform(0, 60, 50).round()
exact = np.column_stack([20 * rooms, rooms, age])
noisy = np.column_stack([20 * rooms + rng.normal(0, 0.5, 50), rooms, age])
print(rank(exact), rank(noisy), np.linalg.svd(noisy, compute_uv=False).round(2).tolist())
# 2 3 [501.87, 144.0, 0.17]: the third direction is almost empty

Next#

A matrix answers the question “where does xx go?”. Most uses of linear algebra ask the reverse: given an output bb, which inputs xx satisfy Ax=bAx = b? That is a system of linear equations. The next note solves it by Gaussian elimination, reads the elimination as the factorization A=LUA = LU, and uses the rank and the kernel to say exactly when a solution exists and when it is unique.

References#

  • S. Axler. Linear Algebra Done Right, 4th ed. Springer, 2024 (open access). Chapter 1 (vector spaces and subspaces), sections 2A–2C (span, independence, bases, dimension; 2.22, the length of an independent list), sections 3A–3D (linear maps, null spaces and ranges, 3.21 the fundamental theorem of linear maps, matrices, invertibility).
  • G. Strang. Introduction to Linear Algebra, 5th ed. Wellesley-Cambridge Press, 2016. Section 1.3 (matrices, AxAx as a combination of columns), section 3.5 (dimensions of the four subspaces).