Skip to content
AriadneTechnology

The Middle Ring · Chamber 4 of 9

Matrices as Transformations

A matrix is a function that moves space. Watch grids rotate, shear and collapse, then compose them.

40 min 60 XP + 12 questions + 1 challengeMathVideoPapersProofsCodeLab

In this chamber you will

  • Read a matrix column by column as where the basis vectors land
  • Multiply matrices four ways and explain why AB ≠ BA
  • Build rotation, scaling, shear and projection matrices
  • Read a neural-network layer as a linear map plus a nonlinearity
DiscoverLearnRead beyondPapers & lecturesYour turn

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 ii of the output image, it computes where in the input image to look:

Spotted in the wild

(xisyis)=Tθ(Gi)=Aθ(xityit1)=[θ11θ12θ13θ21θ22θ23](xityit1)\begin{pmatrix} x_i^s \\ y_i^s \end{pmatrix} = \mathcal{T}_\theta(G_i) = \mathtt{A}_\theta \begin{pmatrix} x_i^t \\ y_i^t \\ 1 \end{pmatrix} = \begin{bmatrix} \theta_{11} & \theta_{12} & \theta_{13} \\ \theta_{21} & \theta_{22} & \theta_{23} \end{bmatrix} \begin{pmatrix} x_i^t \\ y_i^t \\ 1 \end{pmatrix}
Jaderberg, Simonyan, Zisserman & Kavukcuoglu (2015), “Spatial Transformer Networks”, Eq. (1)

The superscript tt marks a target point on the output's grid, and ss marks the source point in the input where its value comes from. A small network looks at the image and predicts the six numbers θ11,…,θ23\theta_{11}, \ldots, \theta_{23}, 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 11 doing at the bottom of the vector? By the end of this chamber you'll be able to read every piece.

Quick check +20 XP

Take a guess before reading on. In the Spatial Transformer's Eq. (1), set θ11=θ22=1\theta_{11} = \theta_{22} = 1, θ12=θ21=0\theta_{12} = \theta_{21} = 0, θ13=0.5\theta_{13} = 0.5 and θ23=0\theta_{23} = 0. The output pixel at (xt,yt)=(0,0)(x^t, y^t) = (0, 0) samples the input at which point (xs,ys)(x^s, y^s)?

DiscoverLearnRead beyondPapers & lecturesYour turn

Learn: what makes a map linear

A map (or transformation) T:Rn→RmT : \mathbb{R}^n \to \mathbb{R}^m is a function that takes a vector with nn entries and returns one with mm 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 0\mathbf{0} to 0\mathbf{0}.

Proof. The zero vector is 0⋅00 \cdot \mathbf{0}, so the scaling rule with c=0c = 0 gives T(0)=T(0⋅0)=0⋅T(0)=0T(\mathbf{0}) = T(0 \cdot \mathbf{0}) = 0 \cdot T(\mathbf{0}) = \mathbf{0}. ■\blacksquare

The claim doubles as a test. The map T(x,y)=(x+1,y)T(x, y) = (x + 1, y), which slides everything one step right, sends 0\mathbf{0} to (1,0)(1, 0), so it can't be linear. The map T(x,y)=(x2,y)T(x, y) = (x^2, y) does keep the origin, but fails the scaling rule: T(2,0)=(4,0)T(2, 0) = (4, 0), while 2 T(1,0)=(2,0)2\,T(1, 0) = (2, 0). And T(x,y)=(2x−y, x+y)T(x, y) = (2x - y,\ x + y) passes both rules, as you can check by expanding.

Quick check +20 XP

Which of these maps T:R2→R2T : \mathbb{R}^2 \to \mathbb{R}^2 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): x=x1e1+x2e2\mathbf{x} = x_1\mathbf{e}_1 + x_2\mathbf{e}_2. Apply a linear map TT and use its two rules:

T(x)=T(x1e1+x2e2)=T(x1e1)+T(x2e2)=x1 T(e1)+x2 T(e2).T(\mathbf{x}) = T(x_1\mathbf{e}_1 + x_2\mathbf{e}_2) = T(x_1\mathbf{e}_1) + T(x_2\mathbf{e}_2) = x_1\,T(\mathbf{e}_1) + x_2\,T(\mathbf{e}_2).

The first step uses the addition rule, the second the scaling rule. So once you know the two vectors T(e1)T(\mathbf{e}_1) and T(e2)T(\mathbf{e}_2), you know TT everywhere. Store them as the columns of a matrix:

A=[∣∣T(e1)T(e2)∣∣],T(x)=Ax=x1a1+x2a2.A = \begin{bmatrix} | & | \\ T(\mathbf{e}_1) & T(\mathbf{e}_2) \\ | & | \end{bmatrix}, \qquad T(\mathbf{x}) = A\mathbf{x} = x_1\mathbf{a}_1 + x_2\mathbf{a}_2.

That's the most important sentence in this chamber: the columns of a matrix are where the basis vectors land, and AxA\mathbf{x}, read “A times x”, is the combination of the columns weighted by the entries of x\mathbf{x}. The same holds in any size. An m×nm \times n matrix has nn columns, one for each basis vector ej\mathbf{e}_j of Rn\mathbb{R}^n, and each column aj=Aej\mathbf{a}_j = A\mathbf{e}_j is a vector in Rm\mathbb{R}^m. (3Blue1Brown calls e1\mathbf{e}_1 and e2\mathbf{e}_2 “i-hat” and “j-hat”, written ı^\hat{\imath} and ȷ^\hat{\jmath}. You'll see those names in the lab.)

A worked example. Let TT send e1\mathbf{e}_1 to (2,1)(2, 1) and e2\mathbf{e}_2 to (−1,1)(-1, 1). Where does x=(3,2)\mathbf{x} = (3, 2) go?

A=[2−111],A(32)=3(21)+2(−11)=(45).A = \begin{bmatrix} 2 & -1 \\ 1 & 1 \end{bmatrix}, \qquad A\begin{pmatrix} 3 \\ 2 \end{pmatrix} = 3\begin{pmatrix} 2 \\ 1 \end{pmatrix} + 2\begin{pmatrix} -1 \\ 1 \end{pmatrix} = \begin{pmatrix} 4 \\ 5 \end{pmatrix}.

You can also compute it row by row, as in Mathematics for ML, Chamber 6: each entry of AxA\mathbf{x} is a row of AA dotted with x\mathbf{x}. The first entry is (2,−1)⋅(3,2)=4(2, -1) \cdot (3, 2) = 4 and the second is (1,1)⋅(3,2)=5(1, 1) \cdot (3, 2) = 5. 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.

Maps and matrices
  • T:Rn→RmT : \mathbb{R}^n \to \mathbb{R}^m“T maps R n to R m”
    A function that takes vectors with nn entries to vectors with mm entries. It is linear if it respects sums and scalings.
    T(u+v)=T(u)+T(v)T(\mathbf{u} + \mathbf{v}) = T(\mathbf{u}) + T(\mathbf{v})
  • AxA\mathbf{x}“A times x”
    Apply the matrix to the vector: the combination x1a1+⋯+xnanx_1\mathbf{a}_1 + \cdots + x_n\mathbf{a}_n of AA's columns, weighted by the entries of x\mathbf{x}.
    [2−111](32)=(45)\begin{bmatrix} 2 & -1 \\ 1 & 1 \end{bmatrix}\begin{pmatrix} 3 \\ 2 \end{pmatrix} = \begin{pmatrix} 4 \\ 5 \end{pmatrix}
  • aj=Aej\mathbf{a}_j = A\mathbf{e}_j“a j, the j-th column of A”
    Where the jj-th standard basis vector lands. The columns of a matrix are the images of the basis vectors.
    Ae1=a1A\mathbf{e}_1 = \mathbf{a}_1
  • ABAB“A B, or A after B”
    The composition: apply BB first, then AA. Products are read right to left, like f∘gf \circ g.
    (AB)x=A(Bx)(AB)\mathbf{x} = A(B\mathbf{x})
  • RθR_\theta“R theta, rotation by theta”
    The matrix that rotates the plane anticlockwise by the angle θ\theta.
    Rθ=[cos⁡θ−sin⁡θsin⁡θcos⁡θ]R_\theta = \begin{bmatrix} \cos\theta & -\sin\theta \\ \sin\theta & \cos\theta \end{bmatrix}
  • det⁡A\det A“det A, the determinant of A”
    The signed factor by which AA scales areas. Negative means orientation flips (like a mirror); zero means the plane is flattened.
    det⁡[abcd]=ad−bc\det\begin{bmatrix} a & b \\ c & d \end{bmatrix} = ad - bc

Now you can build transformations to order: decide where e1\mathbf{e}_1 and e2\mathbf{e}_2 should go, and write those images down as columns.

Transformatione1\mathbf{e}_1 lands ate2\mathbf{e}_2 lands atMatrix
Scale by s1s_1 and s2s_2(s1,0)(s_1, 0)(0,s2)(0, s_2)[s100s2]\begin{bmatrix} s_1 & 0 \\ 0 & s_2 \end{bmatrix}
Rotate anticlockwise by θ\theta(cos⁡θ,sin⁡θ)(\cos\theta, \sin\theta)(−sin⁡θ,cos⁡θ)(-\sin\theta, \cos\theta)[cos⁡θ−sin⁡θsin⁡θcos⁡θ]\begin{bmatrix} \cos\theta & -\sin\theta \\ \sin\theta & \cos\theta \end{bmatrix}
Reflect in the xx-axis(1,0)(1, 0)(0,−1)(0, -1)[100−1]\begin{bmatrix} 1 & 0 \\ 0 & -1 \end{bmatrix}
Reflect in the line y=xy = x(0,1)(0, 1)(1,0)(1, 0)[0110]\begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}
Shear sideways by kk(1,0)(1, 0)(k,1)(k, 1)[1k01]\begin{bmatrix} 1 & k \\ 0 & 1 \end{bmatrix}
Project onto the xx-axis(1,0)(1, 0)(0,0)(0, 0)[1000]\begin{bmatrix} 1 & 0 \\ 0 & 0 \end{bmatrix}

Only the rotation needs any thought, so let's derive it. Rotating keeps lengths, so e1\mathbf{e}_1 lands on the unit circle at angle θ\theta from the xx-axis: by the definition of cosine and sine, at (cos⁡θ,sin⁡θ)(\cos\theta, \sin\theta). The vector e2\mathbf{e}_2 starts at angle 90°90° and lands at angle 90°+θ90° + \theta, which is the point (cos⁡(90°+θ),sin⁡(90°+θ))=(−sin⁡θ,cos⁡θ)(\cos(90° + \theta), \sin(90° + \theta)) = (-\sin\theta, \cos\theta). Those two images are the columns of the rotation matrix, written RθR_\theta and read “R theta”:

Rθ=[cos⁡θ−sin⁡θsin⁡θcos⁡θ].R_\theta = \begin{bmatrix} \cos\theta & -\sin\theta \\ \sin\theta & \cos\theta \end{bmatrix}.
Quick check +20 XP

Using RθR_\theta with θ=180°\theta = 180°, 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 0\mathbf{0}, e1\mathbf{e}_1, e1+e2\mathbf{e}_1 + \mathbf{e}_2 and e2\mathbf{e}_2. 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:

det⁡[abcd]=ad−bc.\det \begin{bmatrix} a & b \\ c & d \end{bmatrix} = ad - bc.

Because the map is linear, every region's area gets multiplied by the same factor, ∣det⁡A∣|\det A| (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 det⁡A=0\det A = 0 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 11: 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

Type the four entries of a 2 × 2 matrix. Its first column is where î lands, its second where ĵ lands, and the rest of the grid follows. Watch the letter F to spot reflections, and the determinant for areas.
îĵ

A horizontal shear: (x, y) ↦ (x + 0.5y, y).

î lands at column 1ĵ at column 2

A =

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.
Challenge: Matrix sculptorBuild matrices that rotate, reflect, shear and flatten the grid.+50 XP

Learn: composition is multiplication

Do one transformation, then another. First BB, then AA: the vector x\mathbf{x} goes to BxB\mathbf{x}, and then to A(Bx)A(B\mathbf{x}). 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 ej\mathbf{e}_j goes first to Bej=bjB\mathbf{e}_j = \mathbf{b}_j, the jj-th column of BB, and then to AbjA\mathbf{b}_j. So

AB=[∣∣Ab1⋯Abp∣∣],A(Bx)=(AB) x.AB = \begin{bmatrix} | & & | \\ A\mathbf{b}_1 & \cdots & A\mathbf{b}_p \\ | & & | \end{bmatrix}, \qquad A(B\mathbf{x}) = (AB)\,\mathbf{x}.

Matrix multiplication is defined to be composition. That is the whole reason for its strange-looking rule. Read off entry ii of column jj and you get back the formula from Mathematics for ML, Chamber 6, (AB)ij=∑kAikBkj(AB)_{ij} = \sum_k A_{ik}B_{kj}. And just like f∘gf \circ g, the product is read right to left: in ABAB, the matrix BB acts first.

Shapes follow the same logic. If BB is n×pn \times p, it takes pp-vectors to nn-vectors; then AA must accept nn-vectors, so it's m×nm \times n, and the composition takes pp-vectors to mm-vectors:

(m×n) (n×p)=m×p.(m \times n)\,(n \times p) = m \times p.

Order matters

Let RR rotate by 90°90° and let FF reflect in the xx-axis. Follow the basis vectors through each order, or multiply:

R=[0−110],F=[100−1],RF=[0110],FR=[0−1−10].R = \begin{bmatrix} 0 & -1 \\ 1 & 0 \end{bmatrix}, \quad F = \begin{bmatrix} 1 & 0 \\ 0 & -1 \end{bmatrix}, \qquad RF = \begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}, \quad FR = \begin{bmatrix} 0 & -1 \\ -1 & 0 \end{bmatrix}.

Reflecting first and then rotating gives the mirror in the line y=xy = x. Rotating first and then reflecting gives the mirror in y=−xy = -x. Different maps, so RF≠FRRF \neq FR. Matrix multiplication is not commutative.

What does hold is associativity: (AB)C=A(BC)(AB)C = A(BC). Both sides mean “do CC, then BB, then AA”, 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.

Quick check +20 XP

Let S=[1101]S = \begin{bmatrix} 1 & 1 \\ 0 & 1 \end{bmatrix} (a shear) and R=[0−110]R = \begin{bmatrix} 0 & -1 \\ 1 & 0 \end{bmatrix} (a quarter turn). What is the top-left entry of SRSR?

A proof: rotations add up

Rotating by β\beta and then by α\alpha should be the same as rotating by α+β\alpha + \beta. Geometrically that's obvious. Algebraically, it hides the trigonometric addition formulas inside it.

Claim. For all angles α\alpha and β\beta, RαRβ=Rα+βR_\alpha R_\beta = R_{\alpha + \beta}.

Proof. Multiply, taking each row of RαR_\alpha dotted with each column of RβR_\beta:

RαRβ=[cos⁡α−sin⁡αsin⁡αcos⁡α][cos⁡β−sin⁡βsin⁡βcos⁡β]=[cos⁡αcos⁡β−sin⁡αsin⁡β−(sin⁡αcos⁡β+cos⁡αsin⁡β)sin⁡αcos⁡β+cos⁡αsin⁡βcos⁡αcos⁡β−sin⁡αsin⁡β].\begin{aligned} R_\alpha R_\beta &= \begin{bmatrix} \cos\alpha & -\sin\alpha \\ \sin\alpha & \cos\alpha \end{bmatrix} \begin{bmatrix} \cos\beta & -\sin\beta \\ \sin\beta & \cos\beta \end{bmatrix} \\ &= \begin{bmatrix} \cos\alpha\cos\beta - \sin\alpha\sin\beta & -(\sin\alpha\cos\beta + \cos\alpha\sin\beta) \\ \sin\alpha\cos\beta + \cos\alpha\sin\beta & \cos\alpha\cos\beta - \sin\alpha\sin\beta \end{bmatrix}. \end{aligned}

Now use the angle-addition identities

cos⁡(α+β)=cos⁡αcos⁡β−sin⁡αsin⁡β,sin⁡(α+β)=sin⁡αcos⁡β+cos⁡αsin⁡β.\cos(\alpha + \beta) = \cos\alpha\cos\beta - \sin\alpha\sin\beta, \qquad \sin(\alpha + \beta) = \sin\alpha\cos\beta + \cos\alpha\sin\beta.

The two diagonal entries are both cos⁡(α+β)\cos(\alpha + \beta), the bottom-left entry is sin⁡(α+β)\sin(\alpha + \beta), and the top-right entry is −sin⁡(α+β)-\sin(\alpha + \beta). So

RαRβ=[cos⁡(α+β)−sin⁡(α+β)sin⁡(α+β)cos⁡(α+β)]=Rα+β.■R_\alpha R_\beta = \begin{bmatrix} \cos(\alpha+\beta) & -\sin(\alpha+\beta) \\ \sin(\alpha+\beta) & \cos(\alpha+\beta) \end{bmatrix} = R_{\alpha+\beta}. \qquad \blacksquare

Two bonuses come free. Since α+β=β+α\alpha + \beta = \beta + \alpha, 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

A=[1234],B=[5678],AB=[19224350].A = \begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix}, \qquad B = \begin{bmatrix} 5 & 6 \\ 7 & 8 \end{bmatrix}, \qquad AB = \begin{bmatrix} 19 & 22 \\ 43 & 50 \end{bmatrix}.
  1. 1

    Dot products, entry by entry

    Entry (i,j)(i, j) of ABAB is row ii of AA dotted with column jj of BB. For example, the top-right entry is (1,2)⋅(6,8)=6+16=22(1, 2) \cdot (6, 8) = 6 + 16 = 22. This is the view behind attention scores: each entry of QK⊤QK^\top is one query dotted with one key.

  2. 2

    Columns

    Column jj of ABAB is AA times column jj of BB: the first column is 5(1,3)+7(2,4)=(19,43)5(1, 3) + 7(2, 4) = (19, 43). This is the composition view, with AA transforming each column of BB in turn. It's also a layer applied to a whole batch of inputs stored as columns.

  3. 3

    Rows

    Row ii of ABAB is row ii of AA times BB, a combination of the rows of BB: the first row is 1(5,6)+2(7,8)=(19,22)1(5, 6) + 2(7, 8) = (19, 22). This is the view when data sits in rows, as in most code: X @ W transforms each example, one row of X at a time.

  4. 4

    Outer products, column times row

    ABAB is a sum of outer products, column kk of AA times row kk of BB: the column (1,3)(1, 3) times the row (5,6)(5, 6) gives [561518]\begin{bmatrix} 5 & 6 \\ 15 & 18 \end{bmatrix}, the column (2,4)(2, 4) times the row (7,8)(7, 8) gives [14162832]\begin{bmatrix} 14 & 16 \\ 28 & 32 \end{bmatrix}, and their sum is ABAB. Each piece is a matrix of rank one, the building block of LoRA (Chamber 6).

All four describe the same mnpmnp multiplications, grouped differently. Which grouping you choose decides what you can see, and how fast your code runs.

Products, layers and affine maps
  • ab⊤\mathbf{a}\mathbf{b}^\top“the outer product of a and b”
    A column times a row: the matrix whose (i,j)(i, j) entry is aibja_ib_j. Every product ABAB is a sum of these, one per column of AA.
    AB=∑kA:,k Bk,:AB = \sum_k A_{:,k}\, B_{k,:}
  • x↦Wx+b\mathbf{x} \mapsto W\mathbf{x} + \mathbf{b}“x maps to W x plus b”
    An affine map: a linear map followed by a shift. It is not linear unless b=0\mathbf{b} = \mathbf{0}, because it moves the origin to b\mathbf{b}.
  • σ(Wx+b)\sigma(W\mathbf{x} + \mathbf{b})“sigma of W x plus b”
    A neural-network layer: an affine map, then a nonlinearity σ\sigma (ReLU, tanh, …) applied to each entry separately.
    h=ReLU(Wx+b)\mathbf{h} = \mathrm{ReLU}(W\mathbf{x} + \mathbf{b})
  • [x1]\begin{bmatrix} \mathbf{x} \\ 1 \end{bmatrix}“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.
    (3,5)↦(3,5,1)(3, 5) \mapsto (3, 5, 1)

Learn: a neural layer, and maps that move the origin

A fully connected layer of a neural network computes

h=σ(Wx+b),\mathbf{h} = \sigma(W\mathbf{x} + \mathbf{b}),

read “h equals sigma of W x plus b”. Take it apart with this chamber's eyes:

  • WxW\mathbf{x} is a linear map. The matrix W∈Rm×nW \in \mathbb{R}^{m \times n} takes nn inputs to mm outputs, and its columns say where each input direction lands.
  • Adding b\mathbf{b} shifts the result. Together, x↦Wx+b\mathbf{x} \mapsto W\mathbf{x} + \mathbf{b} is an affine map: a linear map followed by a translation. It isn't linear unless b=0\mathbf{b} = \mathbf{0}, because it moves the origin to b\mathbf{b}.
  • σ\sigma 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:

W2(W1x+b1)+b2=(W2W1) x+(W2b1+b2).W_2(W_1\mathbf{x} + \mathbf{b}_1) + \mathbf{b}_2 = (W_2W_1)\,\mathbf{x} + (W_2\mathbf{b}_1 + \mathbf{b}_2).

That's a single affine map, with matrix W2W1W_2W_1 and shift W2b1+b2W_2\mathbf{b}_1 + \mathbf{b}_2. A hundred linear layers collapse into one. Without σ\sigma 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 11. For x∈R2\mathbf{x} \in \mathbb{R}^2 and an affine map x↦Ax+t\mathbf{x} \mapsto A\mathbf{x} + \mathbf{t},

[At0⊤1][x1]=[Ax+t1].\begin{bmatrix} A & \mathbf{t} \\ \mathbf{0}^\top & 1 \end{bmatrix}\begin{bmatrix} \mathbf{x} \\ 1 \end{bmatrix} = \begin{bmatrix} A\mathbf{x} + \mathbf{t} \\ 1 \end{bmatrix}.

The last column gets multiplied by the 11, so it gets added: a shift disguised as a matrix product. Now every affine map of the plane is a 3×33 \times 3 matrix, and composing affine maps is plain matrix multiplication. 3D graphics software uses the same trick, with 4×44 \times 4 matrices, to move objects around a scene.

This is precisely the 11 in the Spatial Transformer's Eq. (1). Its matrix Aθ\mathtt{A}_\theta is the top two rows of the 3×33 \times 3 matrix above. The left 2×22 \times 2 block (θ11,θ12,θ21,θ22\theta_{11}, \theta_{12}, \theta_{21}, \theta_{22}) is the linear part, which rotates, scales and shears. The last column (θ13,θ23\theta_{13}, \theta_{23}) is the translation. For attention, the paper restricts it further to a zoom ss and a shift (tx,ty)(t_x, t_y):

Spotted in the wild

Aθ=[s0tx0sty]\mathtt{A}_\theta = \begin{bmatrix} s & 0 & t_x \\ 0 & s & t_y \end{bmatrix}
Jaderberg et al. (2015), “Spatial Transformer Networks”, Eq. (2)

Its left block is ss times the identity, a pure zoom. With s<1s < 1 the output grid covers only a small window of the input, centred at (tx,ty)(t_x, t_y): the network crops and zooms in on whatever it has learned to look at.

DiscoverLearnRead beyondPapers & lecturesYour turn

Read beyond the course

Article · free online · ~25 min

Neural Networks, Manifolds, and Topology

Christopher 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 Mappings

J. 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 Learning

Marc 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.

DiscoverLearnRead beyondPapers & lecturesYour turn

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 θ\theta, 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, 2015

A 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 Networks

Max Jaderberg, Karen Simonyan, Andrew Zisserman, Koray Kavukcuoglu · NeurIPS, 2015

+30 XP
(xisyis)=Tθ(Gi)=Aθ(xityit1)=[θ11θ12θ13θ21θ22θ23](xityit1)\begin{pmatrix} x_i^s \\ y_i^s \end{pmatrix} = \mathcal{T}_\theta(G_i) = \mathtt{A}_\theta \begin{pmatrix} x_i^t \\ y_i^t \\ 1 \end{pmatrix} = \begin{bmatrix} \theta_{11} & \theta_{12} & \theta_{13} \\ \theta_{21} & \theta_{22} & \theta_{23} \end{bmatrix} \begin{pmatrix} x_i^t \\ y_i^t \\ 1 \end{pmatrix}

The grid generator at the heart of a spatial transformer. For each point GiG_i of the output's regular grid, it computes where to look in the input. Match each symbol to its meaning.

xit, yitx_i^t,\ y_i^t
xis, yisx_i^s,\ y_i^s
Aθ\mathtt{A}_\theta
θ11,θ12,θ21,θ22\theta_{11}, \theta_{12}, \theta_{21}, \theta_{22}
θ13,θ23\theta_{13}, \theta_{23}
11
Tθ(Gi)\mathcal{T}_\theta(G_i)

Options

Watch

Linear transformations and matrices | Chapter 3, Essence of linear algebra3Blue1Brown · 11 min
Matrix multiplication as composition | Chapter 4, Essence of linear algebra3Blue1Brown · 10 min

The first video is this chamber's big idea in motion: keep your eye on where ı^\hat{\imath} and ȷ^\hat{\jmath} 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.

DiscoverLearnRead beyondPapers & lecturesYour turn

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

+25 XP

Read each matrix column by column (where do e1\mathbf{e}_1 and e2\mathbf{e}_2 land?) and match it to what it does to the plane.

[0−110]\begin{bmatrix} 0 & -1 \\ 1 & 0 \end{bmatrix}
[−100−1]\begin{bmatrix} -1 & 0 \\ 0 & -1 \end{bmatrix}
[100−1]\begin{bmatrix} 1 & 0 \\ 0 & -1 \end{bmatrix}
[0110]\begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}
[1101]\begin{bmatrix} 1 & 1 \\ 0 & 1 \end{bmatrix}
[2002]\begin{bmatrix} 2 & 0 \\ 0 & 2 \end{bmatrix}
[1000]\begin{bmatrix} 1 & 0 \\ 0 & 0 \end{bmatrix}

Options

Match · Maths ↔ Python

From symbols to NumPy

+25 XP

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.

AxA\mathbf{x}
aj=Aej\mathbf{a}_j = A\mathbf{e}_j, the jj-th column
(AB)ij(AB)_{ij} as a dot product
ABAB as a sum of outer products
RθR_\theta
max⁡(0, Wx+b)\max(0,\ W\mathbf{x} + \mathbf{b}), a ReLU layer
x\mathbf{x} in homogeneous coordinates

Options

Proofs

The first proof shows that composing linear maps gives a linear map, which is why a product ABAB is again a matrix. The second you write yourself, with the norm from Chamber 2.

Proof puzzle

Composing linear maps keeps them linear

+25 XP

Claim

If T:Rn→RmT : \mathbb{R}^n \to \mathbb{R}^m and S:Rm→RpS : \mathbb{R}^m \to \mathbb{R}^p are linear, then so is their composition S∘TS \circ T, defined by (S∘T)(x)=S(T(x))(S \circ T)(\mathbf{x}) = S(T(\mathbf{x})).

Tap lines in the order they should appear. Not every line belongs. Tap a line in your proof to send it back.

Your proof

  1. Pick the first line below.

Available lines

Prove it yourself

Rotations preserve length

+40 XP

Claim

For every angle θ\theta and every x∈R2\mathbf{x} \in \mathbb{R}^2, ∥Rθx∥=∥x∥\|R_\theta\mathbf{x}\| = \|\mathbf{x}\|.

Preview

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

+20 XP

A linear map T:R2→R2T : \mathbb{R}^2 \to \mathbb{R}^2 sends e1=(1,0)\mathbf{e}_1 = (1, 0) to (3,1)(3, 1) and e2=(0,1)\mathbf{e}_2 = (0, 1) to (−2,4)(-2, 4). For k=1,2,…,20k = 1, 2, \ldots, 20 (inclusive) let pk=(k,k2)\mathbf{p}_k = (k, k^2).

Compute the vector T(p1)+T(p2)+⋯+T(p20)T(\mathbf{p}_1) + T(\mathbf{p}_2) + \cdots + T(\mathbf{p}_{20}), and give the sum of its two entries.

An exact integer (or a fraction like 7/12)

Problem 11·Standard

Where does the sampling grid land?

+35 XP

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

(xsys)=Aθ(xtyt1).\begin{pmatrix} x^s \\ y^s \end{pmatrix} = \mathtt{A}_\theta \begin{pmatrix} x^t \\ y^t \\ 1 \end{pmatrix}.

Coordinates are normalised, so the input image occupies the square −1≤xs≤1-1 \le x^s \le 1, −1≤ys≤1-1 \le y^s \le 1. A sample point outside that square falls off the image.

The output grid is 21×2121 \times 21: both xtx^t and yty^t range over the 21 values −1,−0.9,−0.8,…,0.9,1-1, -0.9, -0.8, \ldots, 0.9, 1. The network predicts a zoom out by s=1.2s = 1.2, a rotation by φ=30°\varphi = 30° and a shift of (0.1,−0.2)(0.1, -0.2):

Aθ=[scos⁡φ−ssin⁡φ0.1ssin⁡φscos⁡φ−0.2].\mathtt{A}_\theta = \begin{bmatrix} s\cos\varphi & -s\sin\varphi & 0.1 \\ s\sin\varphi & s\cos\varphi & -0.2 \end{bmatrix}.

How many of the 441 grid points sample from inside the input image, boundary included?

An exact integer (or a fraction like 7/12)

Problem 12·Challenge

The cheapest bracketing

+50 XP

Multiplying an m×nm \times n matrix by an n×pn \times p matrix the schoolbook way costs m⋅n⋅pm \cdot n \cdot p scalar multiplications: each of the mpmp entries is a dot product of length nn. 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 AA is 10×10010 \times 100, BB is 100×5100 \times 5 and CC is 5×505 \times 50, then (AB)C(AB)C costs 5000+2500=75005000 + 2500 = 7500 multiplications while A(BC)A(BC) costs 25,000+50,000=75,00025{,}000 + 50{,}000 = 75{,}000.

You need the product M=A1A2A3A4A5A6A7M = A_1A_2A_3A_4A_5A_6A_7 of seven matrices with shapes

40×300,300×10,10×500,500×20,20×800,800×5,5×200.40 \times 300,\quad 300 \times 10,\quad 10 \times 500,\quad 500 \times 20,\quad 20 \times 800,\quad 800 \times 5,\quad 5 \times 200.

What is the minimum total number of scalar multiplications needed to compute MM, over all ways of bracketing the product?

An exact integer (or a fraction like 7/12)

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 AxA\mathbf{x} is the combination of the columns weighted by the entries of x\mathbf{x}.
  • Multiplication is composition: ABAB means “first BB, then AA”. It's associative but not commutative, except in special cases like RαRβ=Rα+βR_\alpha R_\beta = R_{\alpha+\beta}.
  • Four views of one product: dot products, columns, rows and outer products. The determinant ad−bcad - bc is the signed area scale: negative flips the plane, zero flattens it.
  • A neural layer is σ(Wx+b)\sigma(W\mathbf{x} + \mathbf{b}): a linear map, a shift and a bend. Without σ\sigma, 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.

0/8
Question 1 of 8 +20 XP

A linear map sends e1\mathbf{e}_1 to (2,5)(2, 5) and e2\mathbf{e}_2 to (−1,3)(-1, 3). What is the second entry of the image of (4,1)(4, 1)?

Question 2 of 8 +20 XP

AA is a 3×23 \times 2 matrix and BB is a 2×42 \times 4 matrix. Which statement is true?

Question 3 of 8 +20 XP

You want to rotate a vector with RR first, and then scale the result with SS. Which single matrix does both?

Question 4 of 8 +20 XP

Which pair of 2×22 \times 2 matrices always commutes, that is, AB=BAAB = BA?

Question 5 of 8 +20 XP

The matrix [3122]\begin{bmatrix} 3 & 1 \\ 2 & 2 \end{bmatrix} maps the unit square to a parallelogram. What is the parallelogram's area?

Question 6 of 8 +20 XP

Why is T(x)=Ax+bT(\mathbf{x}) = A\mathbf{x} + \mathbf{b} with b≠0\mathbf{b} \neq \mathbf{0} not a linear map?

Question 7 of 8 +20 XP

Two layers with no activation function compute W2(W1x)W_2(W_1\mathbf{x}), where W1W_1 is 64×78464 \times 784 and W2W_2 is 10×6410 \times 64. Which single layer computes exactly the same function?

Question 8 of 8 +20 XP

The Spatial Transformer's attention form is Aθ=[s0tx0sty]\mathtt{A}_\theta = \begin{bmatrix} s & 0 & t_x \\ 0 & s & t_y \end{bmatrix}. Take s=0.5s = 0.5, tx=0.2t_x = 0.2 and ty=−0.4t_y = -0.4. The output pixel with target coordinates (xt,yt)=(1,1)(x^t, y^t) = (1, 1) samples the input at (xs,ys)(x^s, y^s). What is xsx^s?

End of the chamber

Clear this chamber

+60 XPLinear MapMatrix MultiplicationRotation MatrixAffine Map