Discover: six numbers that move an image
A network that reads house numbers from street photographs has a problem: the digits turn up at every size, angle and position. In 2015 a team at Google DeepMind gave networks a module that learns to straighten its input before reading it, the spatial transformer. At its heart is one equation. For each pixel of the output image, it computes where in the input image to look:
Spotted in the wild
The superscript marks a target point on the output's grid, and marks the source point in the input where its value comes from. A small network looks at the image and predicts the six numbers , and those six numbers are enough to rotate, zoom, shear, shift and crop. How can a 2-by-3 grid of numbers do all that? And what is that lonely doing at the bottom of the vector? By the end of this chamber you'll be able to read every piece.
Take a guess before reading on. In the Spatial Transformer's Eq. (1), set , , and . The output pixel at samples the input at which point ?
Learn: what makes a map linear
A map (or transformation) is a function that takes a vector with entries and returns one with entries. Read it as “T maps R n to R m”. Most maps are hopelessly complicated. Linear maps are the ones that respect the two operations from Chamber 1: adding and scaling.
In words: transforming a sum gives the sum of the transforms, and transforming a stretched vector gives the stretched transform. Geometrically, a linear map keeps grid lines straight, parallel and evenly spaced, and keeps the origin fixed. That last part is a theorem, with a two-line proof.
Claim. Every linear map sends to .
Proof. The zero vector is , so the scaling rule with gives .
The claim doubles as a test. The map , which slides everything one step right, sends to , so it can't be linear. The map does keep the origin, but fails the scaling rule: , while . And passes both rules, as you can check by expanding.
Which of these maps is linear?
Learn: a matrix is where the basis vectors land
Here is the fact that makes linear maps easy to work with. Every vector in the plane is a combination of the standard basis vectors (Chamber 1): . Apply a linear map and use its two rules:
The first step uses the addition rule, the second the scaling rule. So once you know the two vectors and , you know everywhere. Store them as the columns of a matrix:
That's the most important sentence in this chamber: the columns of a matrix are where the basis vectors land, and , read “A times x”, is the combination of the columns weighted by the entries of . The same holds in any size. An matrix has columns, one for each basis vector of , and each column is a vector in . (3Blue1Brown calls and “i-hat” and “j-hat”, written and . You'll see those names in the lab.)
A worked example. Let send to and to . Where does go?
You can also compute it row by row, as in Mathematics for ML, Chamber 6: each entry of is a row of dotted with . The first entry is and the second is . Same answer, two views. The column view tells you what the map does; the row view is how you'd work it out by hand.
- “T maps R n to R m”A function that takes vectors with entries to vectors with entries. It is linear if it respects sums and scalings.
- “A times x”Apply the matrix to the vector: the combination of 's columns, weighted by the entries of .
- “a j, the j-th column of A”Where the -th standard basis vector lands. The columns of a matrix are the images of the basis vectors.
- “A B, or A after B”The composition: apply first, then . Products are read right to left, like .
- “R theta, rotation by theta”The matrix that rotates the plane anticlockwise by the angle .
- “det A, the determinant of A”The signed factor by which scales areas. Negative means orientation flips (like a mirror); zero means the plane is flattened.
| Symbol | Say it | Meaning | LaTeX |
|---|---|---|---|
| “T maps R n to R m” | A function that takes vectors with entries to vectors with entries. It is linear if it respects sums and scalings. | ||
| “A times x” | Apply the matrix to the vector: the combination of 's columns, weighted by the entries of . | ||
| “a j, the j-th column of A” | Where the -th standard basis vector lands. The columns of a matrix are the images of the basis vectors. | ||
| “A B, or A after B” | The composition: apply first, then . Products are read right to left, like . | ||
| “R theta, rotation by theta” | The matrix that rotates the plane anticlockwise by the angle . | ||
| “det A, the determinant of A” | The signed factor by which scales areas. Negative means orientation flips (like a mirror); zero means the plane is flattened. |
Learn: a gallery of transformations
Now you can build transformations to order: decide where and should go, and write those images down as columns.
| Transformation | lands at | lands at | Matrix |
|---|---|---|---|
| Scale by and | |||
| Rotate anticlockwise by | |||
| Reflect in the -axis | |||
| Reflect in the line | |||
| Shear sideways by | |||
| Project onto the -axis |
Only the rotation needs any thought, so let's derive it. Rotating keeps lengths, so lands on the unit circle at angle from the -axis: by the definition of cosine and sine, at . The vector starts at angle and lands at angle , which is the point . Those two images are the columns of the rotation matrix, written and read “R theta”:
Using with , which matrix rotates the plane by a half turn?
Area, orientation and the determinant
Watch what each map does to the unit square, with corners , , and . It lands on the parallelogram built on the two columns, and in Chamber 3 you met the number that measures a parallelogram's signed area. For a matrix it's called the determinant:
Because the map is linear, every region's area gets multiplied by the same factor, (Chamber 5 makes this precise). The sign carries orientation. A negative determinant means the map flips the plane over, like a mirror: a clockwise loop comes out anticlockwise. And means the square has been squashed flat: the columns are dependent, and the whole plane lands on a line or a single point. Rotations and shears have determinant : they move area around without changing how much there is.
Time to sculpt. In the lab, type the four entries of a matrix and watch the grid, the unit square and a letter F move. The F has no mirror symmetry, so it shows you at a glance when a matrix flips the plane.
Interactive lab
Matrix sculptor
A horizontal shear: (x, y) ↦ (x + 0.5y, y).
î lands at column 1ĵ at column 2
det A
1
orientation
kept
Areas are multiplied by |det A| = 1.
- Rotate 90° anticlockwiseWhere must î land after a quarter turn? And ĵ?
- Reflect in a line through the originTry the x-axis, or the line y = x. The F should appear mirrored.
- Shear horizontally by 1Keep î fixed and slide the top of the square one unit right.
- Flatten the plane onto a lineMake the columns parallel, but don't use the zero matrix.
Learn: composition is multiplication
Do one transformation, then another. First , then : the vector goes to , and then to . The combined map is again linear (you'll assemble the proof in Your turn), so by the previous section it has a matrix. Which one? Follow the basis vectors. The vector goes first to , the -th column of , and then to . So
Matrix multiplication is defined to be composition. That is the whole reason for its strange-looking rule. Read off entry of column and you get back the formula from Mathematics for ML, Chamber 6, . And just like , the product is read right to left: in , the matrix acts first.
Shapes follow the same logic. If is , it takes -vectors to -vectors; then must accept -vectors, so it's , and the composition takes -vectors to -vectors:
Order matters
Let rotate by and let reflect in the -axis. Follow the basis vectors through each order, or multiply:
Reflecting first and then rotating gives the mirror in the line . Rotating first and then reflecting gives the mirror in . Different maps, so . Matrix multiplication is not commutative.
What does hold is associativity: . Both sides mean “do , then , then ”, so they must be the same map, and no index-juggling is needed to see it. Associativity never changes the answer, but it can change the cost enormously, which Problem 3 below explores.
Let (a shear) and (a quarter turn). What is the top-left entry of ?
A proof: rotations add up
Rotating by and then by should be the same as rotating by . Geometrically that's obvious. Algebraically, it hides the trigonometric addition formulas inside it.
Claim. For all angles and , .
Proof. Multiply, taking each row of dotted with each column of :
Now use the angle-addition identities
The two diagonal entries are both , the bottom-left entry is , and the top-right entry is . So
Two bonuses come free. Since , rotations of the plane commute with each other, even though matrices in general don't. And you can run the proof backwards: if you ever forget the addition formulas, multiply two rotation matrices and read them off.
Learn: four ways to multiply
The same product can be computed in four ways, and each is the natural view somewhere in machine learning. Take
- 1
Dot products, entry by entry
Entry of is row of dotted with column of . For example, the top-right entry is . This is the view behind attention scores: each entry of is one query dotted with one key.
- 2
Columns
Column of is times column of : the first column is . This is the composition view, with transforming each column of in turn. It's also a layer applied to a whole batch of inputs stored as columns.
- 3
Rows
Row of is row of times , a combination of the rows of : the first row is . This is the view when data sits in rows, as in most code:
X @ Wtransforms each example, one row ofXat a time. - 4
Outer products, column times row
is a sum of outer products, column of times row of : the column times the row gives , the column times the row gives , and their sum is . Each piece is a matrix of rank one, the building block of LoRA (Chamber 6).
All four describe the same multiplications, grouped differently. Which grouping you choose decides what you can see, and how fast your code runs.
- “the outer product of a and b”A column times a row: the matrix whose entry is . Every product is a sum of these, one per column of .
- “x maps to W x plus b”An affine map: a linear map followed by a shift. It is not linear unless , because it moves the origin to .
- “sigma of W x plus b”A neural-network layer: an affine map, then a nonlinearity (ReLU, tanh, …) applied to each entry separately.
- “x in homogeneous coordinates”The vector with a 1 appended. A matrix acting on it can shift as well as transform, because its last column gets added.
| Symbol | Say it | Meaning | LaTeX |
|---|---|---|---|
| “the outer product of a and b” | A column times a row: the matrix whose entry is . Every product is a sum of these, one per column of . | ||
| “x maps to W x plus b” | An affine map: a linear map followed by a shift. It is not linear unless , because it moves the origin to . | ||
| “sigma of W x plus b” | A neural-network layer: an affine map, then a nonlinearity (ReLU, tanh, …) applied to each entry separately. | ||
| “x in homogeneous coordinates” | The vector with a 1 appended. A matrix acting on it can shift as well as transform, because its last column gets added. |
Learn: a neural layer, and maps that move the origin
A fully connected layer of a neural network computes
read “h equals sigma of W x plus b”. Take it apart with this chamber's eyes:
- is a linear map. The matrix takes inputs to outputs, and its columns say where each input direction lands.
- Adding shifts the result. Together, is an affine map: a linear map followed by a translation. It isn't linear unless , because it moves the origin to .
- is a nonlinear function, such as ReLU or tanh, applied to each entry separately. It bends the grid, which no matrix can do.
Why does the nonlinearity matter so much? Stack two layers without it and expand:
That's a single affine map, with matrix and shift . A hundred linear layers collapse into one. Without between them, depth buys nothing: the whole network would be one matrix multiplication plus a shift.
Homogeneous coordinates: the trick with the 1
Affine maps aren't linear, which is a nuisance: we'd like to compose them by multiplying matrices. The fix is to append one extra coordinate that is always . For and an affine map ,
The last column gets multiplied by the , so it gets added: a shift disguised as a matrix product. Now every affine map of the plane is a matrix, and composing affine maps is plain matrix multiplication. 3D graphics software uses the same trick, with matrices, to move objects around a scene.
This is precisely the in the Spatial Transformer's Eq. (1). Its matrix is the top two rows of the matrix above. The left block () is the linear part, which rotates, scales and shears. The last column () is the translation. For attention, the paper restricts it further to a zoom and a shift :
Spotted in the wild
Its left block is times the identity, a pure zoom. With the output grid covers only a small window of the input, centred at : the network crops and zooms in on whatever it has learned to look at.
Read beyond the course
Article · free online · ~25 min
Neural Networks, Manifolds, and TopologyChristopher Olah
Animations of a small tanh network untangling data, with each layer split into a linear map, a translation and a pointwise nonlinearity. Read the first sections now: they are this chamber's layer anatomy, in motion.
Interactive · free online · ~30 min
Immersive Linear Algebra: Linear MappingsJ. Ström, K. Åström & T. Akenine-Möller · Chapter 9: sections 9.1–9.3
Interactive figures for rotations, projections and composite mappings, including a theorem that the columns of a matrix are the images of the basis vectors. Drag the inputs and check your predictions against the pictures.
Book · free online · ~40 min
Mathematics for Machine LearningMarc Peter Deisenroth, A. Aldo Faisal & Cheng Soon Ong · Section 2.7 up to 2.7.1 (linear mappings and their matrix representation), and 2.8.2 (affine mappings)
The same ideas with the notation you'll meet in machine-learning papers. Section 2.7.2 on basis change connects this chamber back to Chamber 3; it's worth a skim now and a proper read later.
Book · free online · ~60 min
Linear Algebra Done Right (4th edition)Sheldon Axler · Chapter 3: sections 3A (the vector space of linear maps) and 3C (matrices)
A rigorous, readable treatment that starts from linear maps and only then introduces matrices, exactly this chamber's order. Section 3C derives matrix multiplication from composition.
Papers and lectures
Spatial Transformer Networks is clearly written and well illustrated. Read the abstract and look at Figure 1, where distorted digits come out straightened. Then read Section 3 up to the end of Section 3.2: the localisation network that predicts , and the parameterised sampling grid with Eq. (1) and Eq. (2). Notice the direction of the arrow: the matrix takes each point of the output grid and says where to sample in the input, because every output pixel needs exactly one value. Section 3.3, on sampling differentiably, is worth a skim. The experiments in Section 4 can wait, apart from the pictures in Table 1.
Spatial Transformer NetworksMax Jaderberg, Karen Simonyan, Andrew Zisserman, Koray Kavukcuoglu · NeurIPS, 2015A learnable module that predicts an affine map from the image itself and resamples the image with it, so that a network learns to rotate, zoom and crop its input with no extra supervision. Linear maps, homogeneous coordinates and the column view of multiplication, all in one equation.
Decode the paper · Eq. (1), Section 3.2
Spatial Transformer NetworksMax Jaderberg, Karen Simonyan, Andrew Zisserman, Koray Kavukcuoglu · NeurIPS, 2015
The grid generator at the heart of a spatial transformer. For each point of the output's regular grid, it computes where to look in the input. Match each symbol to its meaning.
Options
Watch
The first video is this chamber's big idea in motion: keep your eye on where and land, and read the matrix off their coordinates. The second shows composition as “apply one, then the other” and explains, with no index-juggling, why the order of a product matters and why associativity is automatic.
Your turn
You can now read a matrix as a transformation, compose transformations and take a neural layer apart. Match matrices to their effects and formulas to code, then assemble a proof, write one, and solve three problems in code.
Match · Matrix ↔ What it does
Name that transformation
Read each matrix column by column (where do and land?) and match it to what it does to the plane.
Options
Match · Maths ↔ Python
From symbols to NumPy
Match each formula to the NumPy that computes it. n is the number of columns of A (and rows of B), and t is an angle in radians.
Options
Proofs
The first proof shows that composing linear maps gives a linear map, which is why a product is again a matrix. The second you write yourself, with the norm from Chamber 2.
Proof puzzle
Composing linear maps keeps them linear
Claim
If and are linear, then so is their composition , defined by .
Tap lines in the order they should appear. Not every line belongs. Tap a line in your proof to send it back.
Your proof
- Pick the first line below.
Available lines
Prove it yourself
Rotations preserve length
Claim
For every angle and every , .
Your typeset proof appears here.
Code it up
The first problem rewards linearity, the second applies the Spatial Transformer's Eq. (1) to a whole sampling grid, and the third asks what associativity is worth.
Problem 10·Warm-up
Linearity saves work
A linear map sends to and to . For (inclusive) let .
Compute the vector , and give the sum of its two entries.
Problem 11·Standard
Where does the sampling grid land?
A Spatial Transformer (Jaderberg et al., 2015) builds its output on a regular grid of target points and, by its Eq. (1), samples the input at
Coordinates are normalised, so the input image occupies the square , . A sample point outside that square falls off the image.
The output grid is : both and range over the 21 values . The network predicts a zoom out by , a rotation by and a shift of :
How many of the 441 grid points sample from inside the input image, boundary included?
Problem 12·Challenge
The cheapest bracketing
Multiplying an matrix by an matrix the schoolbook way costs scalar multiplications: each of the entries is a dot product of length . Matrix multiplication is associative, so a product of several matrices gives the same result however you bracket it, but the cost can differ enormously. For example, if is , is and is , then costs multiplications while costs .
You need the product of seven matrices with shapes
What is the minimum total number of scalar multiplications needed to compute , over all ways of bracketing the product?
Key takeaways
- A linear map respects sums and scalings. It keeps grid lines straight, parallel and evenly spaced, and it keeps the origin fixed.
- The columns of a matrix are where the basis vectors land, and is the combination of the columns weighted by the entries of .
- Multiplication is composition: means “first , then ”. It's associative but not commutative, except in special cases like .
- Four views of one product: dot products, columns, rows and outer products. The determinant is the signed area scale: negative flips the plane, zero flattens it.
- A neural layer is : a linear map, a shift and a bend. Without , stacked layers collapse into one affine map, and appending a 1 (homogeneous coordinates) turns shifts into matrix products, as in Spatial Transformer Networks.
Checkpoint
Prove it to the labyrinth
Answer every question to clear this chamber. First-try answers earn the most XP.
A linear map sends to and to . What is the second entry of the image of ?
is a matrix and is a matrix. Which statement is true?
You want to rotate a vector with first, and then scale the result with . Which single matrix does both?
Which pair of matrices always commutes, that is, ?
The matrix maps the unit square to a parallelogram. What is the parallelogram's area?
Why is with not a linear map?
Two layers with no activation function compute , where is and is . Which single layer computes exactly the same function?
The Spatial Transformer's attention form is . Take , and . The output pixel with target coordinates samples the input at . What is ?
End of the chamber
Clear this chamber
- Questions in this chamber (0/12 solved)Next unsolved
- Bonus: Matrix sculptor (+50 XP)
- Bonus: Problem 10: Linearity saves work (+20 XP)
- Bonus: Problem 11: Where does the sampling grid land? (+35 XP)
- Bonus: Problem 12: The cheapest bracketing (+50 XP)
- Bonus: Proof: Composing linear maps keeps them linear (+25 XP)
- Bonus: Proof: Rotations preserve length (+40 XP)
- Bonus: Decode the paper (+30 XP)
- Bonus: Match: Name that transformation (+25 XP)
- Bonus: Match: From symbols to NumPy (+25 XP)