1.3 Linear Algebra
Dividing an image minibatch by rescales each pixel in isolation, whereas a predictive model must combine hundreds or thousands of input features into a decision. Linear algebra is the mathematical language of such weighted combinations, allowing us to express the forward pass of an entire layer across a minibatch in one compact equation and read off its output shape and floating-point cost ahead of time.
Consider a linear image classifier sorting grayscale clothing images (Chapter 3) into categories. Flattening each photograph yields pixels. Stacking a minibatch of flattened images as the rows of a data matrix , arranging the weights for each of the categories as the columns of , and collecting the category offsets into ( parameters in all), all category scores across the minibatch are given by
where is added to every row via broadcasting (Figure 1.3.1).
The scores of a linear classifier for a minibatch of 256 images and 10 categories. Row of holds image , column of holds the weights of category , and the two meet in the score .
In this section, we build up to starting from scalars, vectors, matrices, and tensors, through reductions, dot products, and matrix products, and conclude with norms and eigenvalues (notational conventions are summarized in Notation).
import torch1.3.1 Scalars, Vectors, Matrices, and Tensors#
We already created and reshaped -, -, -, and -order arrays in Section 1.1; here we pair each order (ndim in code) with its standard mathematical name and notation.
1.3.1.1 Scalars#
Single numbers are called scalars, denoted by ordinary lowercase italic letters (). Writing states that is a real number. In code, a scalar is a -order tensor with empty shape ():
x = torch.tensor(3.0)
x, x.shape(tensor(3.), torch.Size([]))
1.3.1.2 Vectors#
A vector is a fixed-length 1D array of scalars (its elements or components), denoted by bold lowercase letters (). We write for an -dimensional real vector, treated by default as a column vector:
or written inline as . In code, a vector is a -order tensor:
x = torch.arange(3, dtype=torch.float32)
xtensor([0., 1., 2.])
Whereas mathematical notation uses 1-based indexing (), Python uses 0-based indexing, so the third component is accessed via x[2]:
x[2]tensor(2.)
A vector's dimensionality (its number of components) is returned by Python's built-in len(x) or as the sole entry in its 1-tuple shape x.shape:
len(x), x.shape(3, torch.Size([3]))
To prevent confusion when "dimension" is used informally, we reserve order (ndim) for the number of axes of a tensor and dimensionality for the number of components of a vector.
1.3.1.3 Matrices#
Matrices are -order tensors, denoted by bold uppercase letters (). Writing indicates rows and columns (when , is square), with entry in row and column :
Tabular and flattened minibatch matrices store one example per row and one feature per column. Below, we construct a matrix A:
A = torch.arange(6, dtype=torch.float32).reshape(2, 3)
Atensor([[0., 1., 2.],
[3., 4., 5.]])
Exchanging a matrix's rows and columns yields its transpose , with , accessed in code via .T:
A.Ttensor([[0., 3.],
[1., 4.],
[2., 5.]])
A square matrix is symmetric if ( for all ):
S = torch.tensor([[2.0, 1.0], [1.0, 2.0]])
(S == S.T).all()tensor(True)
1.3.1.4 Higher-Order Tensors#
Tensors with three or more axes are denoted by sans-serif uppercase letters (). Below, we generate a synthetic 4D image minibatch images of shape with entries in and flatten each image to form the 2D matrix :
images = torch.rand(256, 1, 28, 28)
X = images.reshape(256, -1) # One row of 784 pixels per image
images.shape, X.shape(torch.Size([256, 1, 28, 28]), torch.Size([256, 784]))
1.3.2 Elementwise Operations and Reductions#
1.3.2.1 Elementwise Operations and the Hadamard Product#
The elementwise product of two identically shaped matrices is their Hadamard product , with entries , computed in code with *:
A * Atensor([[ 0., 1., 4.],
[ 9., 16., 25.]])
1.3.2.2 Reductions Along Axes#
Passing axis=0 to .sum() sums over rows to produce a vector of column sums (), whereas axis=1 sums over columns to produce a vector of row sums (); omitting axis sums all entries (Figure 1.3.2):
Reductions of a matrix. Summing over axis 0 leaves one sum per column, and summing over axis 1 leaves one sum per row; the reduced axis disappears from the shape. With keepdims=True, the row sums keep the shape , so broadcasting stretches them across the three columns and the division A / sum_A scales every row to sum to 1.
A.sum(), A.sum(axis=0), A.sum(axis=1)(tensor(15.), tensor([3., 5., 7.]), tensor([ 3., 12.]))
1.3.2.3 Keeping the Reduced Axis for Broadcasting#
To normalize each row of A (shape (2, 3)) by its row sum, A.sum(axis=1) (shape (2,)) cannot broadcast against (2, 3) because trailing dimensions and clash. Passing keepdims=True retains the reduced axis with length so sum_A has shape (2, 1):
sum_A = A.sum(axis=1, keepdims=True)
sum_A, sum_A.shape(tensor([[ 3.],
[12.]]),
torch.Size([2, 1]))
PyTorch accepts both dim/keepdim and the NumPy aliases axis/keepdims.
Because sum_A has shape (2, 1), dividing A / sum_A broadcasts each row sum across all three columns so that every row of the resulting matrix sums to :
A / sum_Atensor([[0.0000, 0.3333, 0.6667],
[0.2500, 0.3333, 0.4167]])
On our minibatch , subtracting per-pixel column means (axis=0, shape (784,)) broadcasts directly, whereas subtracting per-image row means (axis=1) requires keepdims=True (shape (256, 1)):
col_means = X.mean(axis=0)
row_means = X.mean(axis=1, keepdims=True)
col_means.shape, row_means.shape, (X - row_means).shape(torch.Size([784]), torch.Size([256, 1]), torch.Size([256, 784]))
Beware: if happens to be square (), omitting keepdims=True in X - X.mean(axis=1) raises no error and silently subtracts image 's mean from column of every image (Exercise 2).
1.3.3 Products#
1.3.3.1 Dot Products#
Given two vectors , their dot product (or inner product) (also written ) sums the products of corresponding entries:
In code, we compute the dot product of two 1D vectors x and y directly with the framework's dot function:
y = torch.ones(3)
x, y, torch.dot(x, y)(tensor([0., 1., 2.]), tensor([1., 1., 1.]), tensor(3.))
Equivalently, we can multiply x * y elementwise and sum the resulting products with sum (returning when ):
torch.sum(x * y)tensor(3.)
1.3.3.2 Matrix--Vector Products#
Partitioning into its row vectors , the matrix--vector product with is the -vector of row dot products (Figure 1.3.3):
The matrix--vector product takes one dot product per row of , so a matrix maps a vector of length 3 to a vector of length 2. The first row gives .
In Python, the infix operator @ computes both matrix--vector and matrix--matrix products:
A.shape, x.shape, A @ x(torch.Size([2, 3]), torch.Size([3]), tensor([ 5., 14.]))
Viewed column by column, is a linear combination of the columns of , where the column is the image of the standard basis vector . In , a matrix maps the unit square spanned by onto the parallelogram spanned by its columns (Figure 1.3.4).
A matrix maps the unit square (dashed) to the parallelogram spanned by its columns and . From left to right: a rotation by , a scaling by 2 along and by along , and a shear.
1.3.3.3 Matrix--Matrix Products#
Given and , their matrix product has entry equal to the dot product of row of with column of :
B = torch.ones(3, 4)
A @ Btensor([[ 3., 3., 3., 3.],
[12., 12., 12., 12.]])
We can now evaluate our 10-class linear classifier on the minibatch X and pick each image's highest-scoring category via argmax along axis :
W = 0.01 * torch.randn(784, 10) # Column j: category j
b = torch.zeros(10) # Entry j: category j
O = X @ W + b # Row i: image i
O.shape, O.argmax(dim=1).shape(torch.Size([256, 10]), torch.Size([256]))
Multiplying an matrix by a matrix computes dot products of length , costing FLOPs ( FLOPs for X @ W, or FLOPs against only memory entries for two matrices; see Chapter 13). Two special square matrices recur throughout linear algebra: the identity matrix (s on the main diagonal and s elsewhere), which leaves every vector unchanged (), and the inverse of an invertible matrix , defined by (Section 21.2.2.3).
Later models multiply a whole stack of matrices at once, one for each example in the minibatch. The @ operator does this without a loop: on tensors with more than two axes it multiplies along the last two and broadcasts over the leading ones (Section 1.1.3.2). Where @ does not fit, einsum lets us write the sum in (1.3.5) out index by index. The string 'bil,lj->bij' names the axes of each factor and of the result, and an index that is missing from the result, here l, is summed over. We stack three multiples of A and multiply them all by B:
As = torch.stack([A, 2 * A, 3 * A]) # Three 2 x 3 matrices, shape (3, 2, 3)
C = As @ B # B is broadcast across the batch
C.shape, (torch.einsum('bil,lj->bij', As, B) == C).all()(torch.Size([3, 2, 4]), tensor(True))
The result holds three products, one per matrix in the stack, and einsum agrees with @ in every entry.
1.3.4 Norms#
Norms measure the magnitude of a vector or matrix, serving in machine learning both as loss functions (measuring prediction error ) and as regularization penalties (constraining weight magnitude).
1.3.4.1 Euclidean Length and Angle#
The norm (or Euclidean norm) of is
often abbreviated . For two planar vectors separated by angle , equating the law of cosines with the bilinear expansion yields (Figure 1.3.5)
In arbitrary dimension , we read (1.3.7) in reverse to define the cosine similarity between nonzero vectors:
which depends only on direction and ranges from (aligned) through (orthogonal) to (opposed) (Figure 1.3.6).
The dot product is the length of times the signed length of the projection of onto the line through .
Two unit vectors at angle : their dot product equals , ranging from (aligned) through (perpendicular) to (opposed).
The Cauchy--Schwarz inequality guarantees that (so ): for unit vectors and , expanding gives .
def cosine(x, y):
return torch.dot(x, y) / (torch.linalg.vector_norm(x) *
torch.linalg.vector_norm(y))
x, y = torch.tensor([1.0, 1, 1, 1]), torch.tensor([1.0, 1, 1, -1])
cosine(x, y), cosine(2 * x, y), torch.acos(cosine(x, y))(tensor(0.5000), tensor(0.5000), tensor(1.0472))
1.3.4.2 The , , and Frobenius Norms#
The norm (or Manhattan distance) sums the absolute values of the components (Figure 1.3.7):
The norm of is the length of the straight path to ; the norm is the length of the path along the grid.
x = torch.tensor([3.0, -4.0])
torch.linalg.vector_norm(x), torch.abs(x).sum()(tensor(5.), tensor(7.))
Because squares components while does not, loss is more robust to large outlier errors, and weight penalties drive weights to exact zero (sparsity). Both belong to the family of norms (), with as . Any valid norm satisfies (i) absolute homogeneity , (ii) the triangle inequality , and (iii) positive definiteness ( for ).
For an matrix , the Frobenius norm computes the norm of its entries:
torch.linalg.matrix_norm(torch.ones(4, 9))tensor(6.)
PyTorch separates torch.linalg.vector_norm from torch.linalg.matrix_norm; the latter treats a 3D tensor as a batch of 2D matrices.
1.3.5 Eigenvectors and Eigenvalues#
What happens when a 50-layer network multiplies an input vector by matrices repeatedly? A nonzero vector is an eigenvector of with scalar eigenvalue if multiplying by simply scales without rotating it:
For our symmetric matrix , is an eigenvector with and is an eigenvector with (Figure 1.3.8).
Left: maps the unit circle (dashed) to an ellipse whose axes are its eigenvectors, stretched by and , while is turned to . Right: the directions of for approach the eigenvector of the largest eigenvalue.
We compute eigenvalues and unit eigenvectors of a real symmetric matrix using linalg.eigh:
S = torch.tensor([[2.0, 1.0], [1.0, 2.0]])
eigenvalues, eigenvectors = torch.linalg.eigh(S)
eigenvalues, eigenvectors(tensor([1., 3.]),
tensor([[-0.7071, 0.7071],
[ 0.7071, 0.7071]]))
By the spectral theorem (Section 21.3), every real symmetric matrix has real eigenvalues and a complete orthonormal basis of eigenvectors . Expanding any vector (with ) gives
As grows, the term with the largest dominates: aligns with the dominant eigenvector and grows by per step (power iteration). For a symmetric matrix this growth rate is also the largest factor by which the matrix can stretch any vector, its spectral norm .
norm = torch.linalg.vector_norm
v = torch.tensor([1.0, 0.0])
for _ in range(10):
v_prev, v = v, S @ v
growth = norm(v) / norm(v_prev)
growth, v / norm(v)(tensor(3.0000), tensor([0.7071, 0.7071]))
Returning to our 50-layer thought experiment: for , whose eigenvalues and differ from by just , multiplying its two unit eigenvectors by times amplifies the first by and shrinks the second to :
M = torch.tensor([[1.0, 0.1], [0.1, 1.0]])
# The eigenvectors (1, 1) and (-1, 1) of M, as columns of length 1
V = torch.tensor([[1.0, -1.0], [1.0, 1.0]]) / 2 ** 0.5
for _ in range(50): # 50 "layers"
V = M @ V
torch.linalg.vector_norm(V, dim=0)tensor([1.1739e+02, 5.1538e-03])
The weight matrices of a network are not symmetric, and most are not even square. Do eigenvalues still tell us how far such a matrix stretches a vector? They do not. Both eigenvalues of are , and , yet maps to and so doubles its length. Since , stretching is governed by the symmetric matrix . The square roots of its eigenvalues, , are the singular values of , and they exist for every matrix, square or not. We compute them for and for :
A = torch.tensor([[0.0, 2.0], [0.0, 0.0]]) # Both eigenvalues are 0
svdvals = torch.linalg.svdvals
(svdvals(S), svdvals(A), torch.linalg.eigvalsh(A.T @ A).sqrt(),
torch.linalg.matrix_rank(A))(tensor([3., 1.]), tensor([2., 0.]), tensor([0., 2.]), tensor(1))
For the symmetric the singular values are and (up to rounding), the magnitudes of its eigenvalues: for a symmetric matrix the two notions agree. For they are and , and the eigenvalues of return the same two numbers in ascending order. The largest singular value is the spectral norm of any matrix. The number of nonzero singular values is its rank, the number of independent directions that survive the multiplication, which is one for . Both facts follow from the singular value decomposition (Section 21.5).
Unless each layer's weight matrix keeps vector lengths close to on average, activations and gradients explode or vanish exponentially with depth (Section 4.4).
1.3.6 Summary#
Linear algebra expresses whole-minibatch models compactly: stacking flattened images as computes all category scores via . Reductions aggregate along specified axes (keepdims=True retains the axis as length for broadcasting). Dot products build matrix--vector products and matrix--matrix products (costing FLOPs). Norms (, , , Frobenius, and spectral) measure vector and matrix magnitudes, normalized dot products give cosine similarity , and eigenvectors () explain why repeated matrix multiplication scales components as . For a matrix that is not symmetric, the singular values measure the stretching, and the largest of them is the spectral norm.
1.3.7 Exercises#
- Transposes and matrix products. Prove the following algebraic identities:
- Show that the transpose of a matrix product reverses the order of the factors: whenever is defined. (Write out the entry of both sides using (1.3.5).)
- Show that for any rectangular matrix , the product is always square and symmetric (and likewise for ). For our image minibatch , what is the shape of , and what does its entry measure?
- [code] Predicting reduction and broadcasting shapes. Without running any code, predict the shape (or error) of each expression below for
imagesof shape andXof shape , then verify your answers in code:- What does
len(images)return? What are the shapes ofimages.sum(axis=(2, 3))withkeepdims=Falseversuskeepdims=True? Which of the two can divideimagesdirectly via broadcasting, and what doesimages / images.sum(axis=(2, 3), keepdims=True)compute? - What happens when you evaluate
X - X.mean(axis=1)on our matrixX, and how doeskeepdims=Truefix it? - Now suppose your minibatch happens to contain images, so that
Xis a square matrix. Show thatX - X.mean(axis=1)executes without raising any error. Write out what entry ofX - X.mean(axis=1)actually computes in terms of the entries ofX, and explain why a silent broadcasting bug on a square matrix is far more dangerous than a shape error.
- What does
-
How mutually obtuse can a set of vectors be? The following questions explore how negative all pairwise dot products among vectors can simultaneously be.
- Can three vectors in the plane satisfy , , and simultaneously? Provide a concrete numerical example, or prove that none exists.
- Suppose unit vectors () are arranged symmetrically so that every distinct pair has the exact same dot product for all . By expanding , prove that . What does this bound imply about the pairwise cosine similarity of unit-length class templates in a 10-class classifier when all templates are separated by equal angles?
Adapted from MIT 18.06, Problem Set 1, Section 1.2, Problem 28.
-
[code] Norms across multiple parameter tensors. The vector-norm routines introduced in this section can also be applied to higher-order tensors.
- Evaluate the vector norm with default arguments on a 3D tensor of shape , state in words what mathematical formula it computes, and confirm your answer by squaring, summing, and taking the square root of the entries manually.
- A deep neural network stores its learnable parameters across a list of weight and bias tensors of varying orders and shapes. When monitoring training or clipping gradients (Section 8.4.2), we often need the single global norm of all parameters concatenated into one giant vector. Express this global norm in terms of the individual tensor norms without flattening or concatenating the tensors, and verify your formula in code on three tensors of shapes , , and .
-
Associativity of matrix multiplication and computational cost. Although matrix multiplication is associative, meaning mathematically, the order in which you parenthesize a chain of matrix products can change its computational cost by orders of magnitude. Given , , and , calculate the total FLOP count and the number of entries in the intermediate product matrix under both and . By what factors do the two evaluation orders differ in arithmetic work and intermediate memory?
-
[code] All-pairs Euclidean distance matrix without loops. ● Given two collections of vectors in stacked as the rows of and , we want to compute the matrix of squared Euclidean distances without Python loops:
- Compute first via 3D broadcasting: reshape to and to , subtract, square, and sum along the last axis. Second, compute via the quadratic expansion , which requires only row-norm reductions, 2D broadcasting, and a single matrix multiplication . Verify that both results match to floating-point precision.
- When and each contain vectors in , how many intermediate floating-point numbers must the 3D-broadcasting method allocate compared with the matrix-product method? Which method should you use at scale?
- Explain why floating-point rounding in can occasionally produce tiny negative numbers (such as ) when , and show how to clamp the output before taking a square root.
Adapted from Stanford CS231n, Assignment 1 (-nearest-neighbor distances), and fast.ai, Deep Learning from the Foundations, Lesson 8.
-
[code] Power iteration and convergence rate. ● Implement normalized power iteration, repeatedly updating from a random unit vector , on the symmetric matrix
- Record the first iteration at which the absolute cosine similarity between consecutive iterates exceeds . Compare your converged vector against the dominant eigenvector returned by
eigh(A), and explain why the two vectors may differ by an overall sign . - At each step, measure the sine of the angle between and the true dominant eigenvector , , and compute the per-step shrinkage ratio . Express this asymptotic ratio in terms of the eigenvalues of using (1.3.12), and use it to explain why power iteration converged in so few steps.
- Now run power iteration on the shifted matrix . Which eigenvalue and eigenvector of does power iteration converge to now, what happens to the sign of consecutive iterates and , and why?
Adapted from MIT 18.06, Problem Set 1, Section 2.1, Problems 29–30.