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 . 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, , and the sum can be scaled by to give their average, . 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 for the real numbers and for the lists of of them, written as columns.
A vector space keeps only these two operations. It is a set with an addition and a scaling by real numbers, both giving elements of , such that for all and :
- addition is commutative and associative: and ;
- there is a zero vector with , and every has a negative with ;
- scaling is compatible with numbers: and ;
- the two distributive laws hold: and .
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 ; to the polynomials of degree at most 2, , added coefficient by coefficient; to the matrices, added entry by entry; and to the real functions on an interval, with .
Small facts follow from the rules alone. For instance for every : by the second distributive law , and adding to both sides leaves .
Subspaces#
A subspace of is a subset that contains and is closed under the two operations: and whenever . A subspace is a vector space in its own right.
The plane is a subspace, where is the -th entry of . It contains . If and satisfy the equation, so does , whose left side is , and so does , whose left side is . The parallel plane is not a subspace: it misses , 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, with , which contains no negatives; it is convex, the subject of the convexity note. The set of all predictions of a linear model, as varies, is a subspace: the column space of the least-squares note.
Span and linear independence#
A linear combination of is a vector with numbers . The set of all of them is the span, . It is a subspace, since sums and multiples of combinations are combinations, and it is the smallest subspace containing the , since any subspace that contains them contains all their combinations.
Take and . Every combination is , with the third entry equal to the sum of the first two. So is in the span, is not, and the span is exactly the plane of the previous section.
Vectors are linearly independent if the only combination that gives zero is the trivial one:
Otherwise they are dependent, and one of them is a combination of the others: if in a combination that gives zero, divide by and solve for . Removing that does not shrink the span.
The vectors , and are dependent, since . That any three vectors in the plane are dependent follows from the exchange lemma below, applied with the spanning list : an independent list in has at most 2 vectors (Axler, 2024, 2.22).
Exchange lemma. If span , then every independent list in has at most vectors.
Proof
Let be independent. Since the ‘s span , is a combination of them, with some nonzero coefficient because (an independent list contains no zero vector, since is a nontrivial combination); replace that by . The new list still spans , because the removed can be solved for from the expression of . Repeat: at step , is a combination of the current list, and some remaining has a nonzero coefficient, since otherwise would be a combination of , against independence; replace that by . After steps the list holds and of the ‘s and still spans . If , after steps the list spans , so is a combination of it, against independence. So .
Basis, dimension and coordinates#
A basis of is a list that is independent and spans . The standard basis of , where has a 1 in position and zeros elsewhere, is one of infinitely many.
Why ask for both conditions? Spanning guarantees that every vector can be built from the basis, . Independence guarantees that it can be built in only one way, because two lists of coefficients would give
by the distributive laws and then by independence. The unique numbers are the coordinates of in the basis, and the vector and its list of coordinates carry the same information.
In the basis , of the plane, the vector has coordinates : the equations and give and . In the standard basis the same vector has coordinates . Coordinates describe a vector relative to a basis; the vector itself does not change.
When is spanned by finitely many vectors, every basis of 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, . So ; the plane has dimension 2, with basis ; the polynomials of degree at most 2 have dimension 3, with basis , in which has coordinates ; and the matrices have dimension , with the basis of matrices that have a single 1 in row and column (Axler, 2024, 3.40).
Two consequences are used constantly. Adding a vector outside the span of an independent list keeps the list independent: in a combination , a nonzero would put in the span, so , and then every . Hence, in a space of dimension , any independent vectors are a basis: a vector outside their span would give independent vectors, more than a spanning basis of vectors allows. And any vectors that span are a basis: if they were dependent, removing one that is a combination of the others would leave spanning vectors, and the 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 -dimensional space into : 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 takes each element of to an element of . It is linear if it respects both operations:
Together, : 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 and to the parallelogram with sides and , so it sends the diagonal to ; and it sends , the arrow on the line of that is times as long, to . The same picture works for stretches along an axis and for reflections in a line through the origin. Differentiation of polynomials is linear too, , since and ; so are the predictions of a linear model as a function of its weights, ; and so is expectation, .
A shift with is not linear, because a linear map sends to : . A linear map followed by a shift is called affine. The ReLU is not linear either, since while . Neither is the length of a vector.
A linear map is fixed by what it does to a basis. If , linearity gives . The vectors determine everywhere. Conversely, any vectors of define a linear map by . The rule is well defined because coordinates are unique, and linear because the coordinates of are times those of plus times those of .
The matrix of a linear map#
Take and collect the images of the standard basis vectors as the columns of a table, . This table is a matrix , with rows, columns and the entry in row and column . Where does send an arbitrary ? Write in the standard basis and use linearity:
The last line defines the matrix–vector product: is the combination of the columns of with weights . Applying a linear map is multiplying by its matrix, and the -th column of the matrix is the image of . Read entry by entry, the same product is the familiar row formula,
row of multiplied by 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 send to and to . Then
and the row formula agrees: and .
The recipe works for any spaces with chosen bases: column holds the coordinates of the image of the -th basis vector. Differentiation from the polynomials of degree at most 2 (basis ) to those of degree at most 1 (basis ) sends , and , so
The derivative of is : differentiation has become a matrix.
What does a linear map do to a line? The points of the line through with direction go to , by linearity. If this is again a line, with direction ; if the line collapses to a point. So an invertible map sends lines to lines, keeps parallel lines parallel, since a common direction goes to a common direction , and keeps the equally spaced points 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 and , the singular values derived in the SVD note.
A linear map sends a grid to a grid and a circle to an ellipse
Composition is matrix multiplication#
Apply with matrix , and then with matrix . The composition , defined by , is again linear, by the linearity of and then of ,
so it has a matrix, and its -th column is where goes:
where are the columns of . So column of the product is times column of , and its -th entry is row of against column of :
The shapes must match: gives . The order reads right to left, for “first , then ”.
The rules of the product come from composition without any computation with entries. It is associative, , because composing functions is, and a linear map has exactly one matrix, so equal maps have equal matrices. The identity matrix , with ones on the diagonal, is the map that changes nothing. And it is not commutative, because doing and then is usually not doing and then . Let rotate the plane by and stretch it by 2 along the first axis:
stretches first, , its first column. rotates first, , which the stretch along the first axis leaves alone.
Associativity does not make the two orders of evaluation equally cheap. Multiplying an matrix by a one takes multiply–adds, since each of the entries is a sum of products. For matrices , and a vector , , but the left side costs multiply–adds and the right side : for , about against . 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, , are one linear map with matrix : 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 be a new basis of . A vector with new coordinates is , and has an inverse , which recovers . Because the columns are a basis, every has exactly one coordinate vector ; the map is linear, by the uniqueness of coordinates, and its matrix is (the next note computes inverses). To apply in the new coordinates, translate to the standard basis, apply , and translate back:
In the basis the map has the matrix .
For the matrix of the previous section take and . Then and , so
In this basis the map only stretches the first coordinate by 2 and keeps the second. Here , since . 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 . The kernel, or null space, , holds the vectors the map sends to zero. The image, or range, , holds everything the map can reach. Both are subspaces: if then , and is again in the image. For a matrix, the image is the span of the columns, the column space, since is a combination of the columns. The rank of is the dimension of its image.
The kernel measures what the map loses. exactly when : two inputs become indistinguishable exactly when they differ by a kernel vector. So is one-to-one exactly when .
Take
Both columns lie on the line through , so the image is that line and the rank is 1. The kernel is the line , spanned by ; indeed . The right panel of the figure shows the whole plane flattened onto the image. For differentiation 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 is the derivative of .
The rank–nullity theorem#
In both examples the two dimensions add up to the dimension of the input: for and for . 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):
For a matrix , , the number of columns. The dimension of the kernel is also called the nullity.
Proof
Take a basis of and extend it by to a basis of , adding vectors outside the current span until it spans; by the exchange lemma this stops, and . It suffices to show that is a basis of . They span it: every is , and since each is in the kernel,
They are independent: if , then is in the kernel and equals some . That is a combination of the basis equal to zero, so every is zero. Hence .
The theorem is used throughout the course. If , a map has rank at most , so its kernel has dimension at least : 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 , the kernel is exactly when the rank is , that is, when the image is all of . Such a matrix is invertible.
A product never has more rank than its factors. The image of lies inside the image of , so . And is applied to the image of , a space of dimension , so rank–nullity for restricted to that space, whose kernel is , gives
Where machine learning uses it#
A dataset of examples with features is points of , the rows of a design matrix .
A linear layer computes , an affine map; appending a constant 1 to the input folds the shift into one matrix, . 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 with inner dimension a rank of at most , the idea of LoRA.
An embedding lookup applies a matrix to a basis vector. The one-hot vector of token is , and is the -th row of the embedding table , where the transpose 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 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 , and . 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.
| Section | What it builds | Where it is used next |
|---|---|---|
| Linear Algebra | linear systems, projections and QR, eigenvalues, symmetric matrices, the SVD | least squares, PCA, the multivariate Gaussian, Gaussian processes |
| Calculus | gradients, Jacobians and Hessians, matrix calculus, change of variables | backpropagation, the Laplace approximation, normalizing flows |
| Optimization | convexity, gradient descent and Newton’s method, KKT conditions, duality | optimizers, the SVM dual |
| Numerical Computation | conditioning, stability, iterative solvers | every 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 vectors.
- Column of the matrix of is , and is the combination of the columns with weights .
- means “first , then ”: associative, not commutative, and the order of evaluation changes the cost.
- In the basis given by the columns of , the matrix becomes .
- : 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 go?”. Most uses of linear algebra ask the reverse: given an output , which inputs satisfy ? That is a system of linear equations. The next note solves it by Gaussian elimination, reads the elimination as the factorization , 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, as a combination of columns), section 3.5 (dimensions of the four subspaces).