Almost all the arithmetic in a neural network is matrix multiplication: it applies a layer to a whole batch at once, chains layers together, and computes attention scores.
A layer applied to a whole batch of examples is one product, XW⊤, so every example and every neuron is handled in a single operation. (P4.5: The forward pass in matrix form, coming soon)
Stacking two layers multiplies their matrices. Without a nonlinearity in between, the two collapse into one matrix, which is why networks need activation functions. (P4.3: Multi-layer perceptrons, coming soon)
Attention scores for every pair of tokens come from one product, QK⊤, followed by a softmax and another product with V.(P7.3: Queries, keys and values step by step, coming soon)
LoRA fine-tuning stores a weight update as the product of two thin matrices, which is far fewer numbers than the full matrix. (P10.E3: Parameter-efficient fine-tuning, coming soon)
The cost of a model is mostly the cost of its matrix products, which is why GPUs and other accelerators are built to do them fast. (P10.B8: Hardware for deep learning, coming soon)
Multiply two matrices by hand, entry by entry (row of A dotted with column of B), after checking the shapes (m×n)(n×p)→(m×p)
See one product four ways (entries, columns, rows, and a sum of outer products) and use whichever way answers the question at hand
Explain AB as “first B, then A”, show with a picture that AB=BA in general, and say which rules still hold (associative, distributive, identity)
Count the multiply-adds in a product, choose a cheap order for a chain of products, and write products in NumPy with @
In P1.B5 a matrix acted on one vector. Two questions come up at once. What if you have many vectors, such as a whole dataset? And what if you apply one matrix and then another? Both have the same answer: multiply the two matrices. This one operation is the workhorse of machine learning, and this lesson shows how to do it by hand, how to see what it means, and what it costs.
From one vector to many
Start from what you know. Let
A=(142536)B=791181012
A is 2×3, so it takes 3-entry vectors in and gives 2-entry vectors out (P1.B5). Now look at B as two column vectors standing side by side: b1=(7,9,11) and b2=(8,10,12). Apply A to each one, using the rows-dotted-with-x way from P1.B5:
Put the two results side by side as the columns of a new matrix. That matrix is the product:
AB=(5813964154)
So AB means “apply A to every column of B”. With a data matrix this is how you process many examples at once.
The recipe: row times column
Look at where each of the four numbers came from. Every entry of AB is a row of A dotted with a column of B (P1.B3). In symbols, the entry in row i and column j is
(Here A has n columns. (AB)ij means “the (i,j) entry of the product”, and the brackets keep the subscripts attached to the whole product.) For the example, all four entries:
Picture the row sliding across the column: you walk along the row of A and down the column of B together, multiply each pair, and add up. Try it yourself in the widget. It writes the multiply-add out one product at a time.
Slide a row of A across a column of B
row of Acolumn of Bentry of AB
7
8
9
10
11
12
1
2
3
4
5
6
(AB)11 = row 1 of A · column 1 of B
1×7 + 2×9 + 3×11 = 7 + 18 + 33 = 58
Entry in row 1, column 1 of AB = row 1 of A · column 1 of B. Row 1 of A has 3 numbers and column 1 of B has 3, so they can be paired off.
Click an entry of AB to see its row and column. “Step one product” adds one term at a time: the strong blue and pink cells are the pair being multiplied now. Shapes: A is 2×3, B is 3×2, so AB is 2×2.
Row times column. A is at the bottom left, B at the top right, and the product AB at the bottom right. Click an entry of AB to see the row of A (blue) and the column of B (pink) that make it. Use Step one product to add one term at a time, Next entry to move on, or Play to watch every entry in turn. Four example shapes are provided, including a matrix times a vector.
Things to try:
Click each entry of the product in the first example and check it against the four lines above.
Press Step one product repeatedly and watch the running total grow: each step multiplies one entry of the row by the matching entry of the column.
Switch to 3×2 times 2×3. The product is 3×3: nine entries, each a dot product of only two pairs. The size of the result comes from the outer numbers, and the number of terms in each sum comes from the inner number.
Switch to the last example. With one column in B the product has one column: this is the matrix-times-vector product from P1.B5, now seen as a special case.
The shape rule
Each entry pairs up a row of A with a column of B. A dot product needs two lists of the same length (P1.B3). A row of A has as many numbers as A has columns, and a column of B has as many numbers as B has rows. So the number of columns of A must equal the number of rows of B. When it does:
A(m×n)B(n×p)⟶AB(m×p)
The two inner numbers (both n) must match, and they disappear. The two outer numbers, m and p, are the shape of the result: one row for each row of A, one column for each column of B.
Can these two matrices be multiplied?
AB is defined: the inner dimensions match (3 = 3), so the result has the outer dimensions 2×2. It has 4 entries, each a dot product of 3 pairs, so 12 multiply-adds in all (about 24 floating-point operations). The other order BA is also defined, but its shape is 3×3, not 2×2, so AB and BA cannot be equal.
The numbers touching the “×” are the inner dimensions: green when they match, red when they do not. The product takes the outer ones, rows of the left factor and columns of the right factor.
The shape rule. Set the sizes of A (m by n) and B (rows by p) with the sliders. The picture shows the product when the inner dimensions match, and a crossed-out box when they do not. Tick the checkbox to try the other order, BA, and read what the widget says about it.
Try these: the preset 2×3 and 3×2 (defined, result 2×2);2×3 and 2×3 (not defined, although the two shapes are equal); then tick the checkbox to see that the other order BA of the first pair is defined too, but gives a 3×3 matrix.
A table of the cases you will meet most:
Left
Right
Result
What it is
m×n
n×1
m×1
matrix times a vector (P1.B5)
1×n
n×1
1×1
a row times a column: a single number, the dot product
n×1
1×m
n×m
a column times a row: the outer product
n×n
n×n
n×n
two square matrices of the same size: always defined
The second row explains a notation from P1.B3. A vector a is a column (n×1), so a⊤ is a row (1×n) and a⊤b is (1×n)(n×1)=(1×1): the dot product, as a matrix product. The third row is the same two vectors the other way round: ab⊤ is an n×n grid of all the products aibj.
Four ways to see one product
You have seen the product computed entry by entry. The same numbers can be organised three more ways. Each one is useful for a different question. Here they are for the example, AB=(5813964154).
View
What it says
In the example
Entries
each entry is a row of A dotted with a column of B
(AB)21=(4,5,6)⋅(7,9,11)=139
Columns
column j of AB is A times column j of B
column 2 is A(8,10,12)=(64,154)
Rows
row i of AB is row i of A times B
row 1 is (1,2,3)B=(58,64)
Outer products
AB is a sum of (column of A) times (row of B)
see the Go deeper box below
Columns view. This is how we started: A acts on each column of B separately, so each column of the result depends only on the matching column of B. It is the view for “apply a map to many vectors”.
Rows view. The mirror image. A row vector times a matrix, (1,2,3)B, is a combination of the rows of B, with the entries of the row vector as weights: 1⋅(7,8)+2⋅(9,10)+3⋅(11,12)=(58,64).. So each row of the result depends only on the matching row of A. This is the view for “each example (a row) is processed on its own”: changing one row of A changes only that row of the product.
A useful consequence. Multiplying B on the right by a matrix mixes the columns of B, and multiplying on the left mixes the rows. Take the swap matrix Q=(0110) and P=(1324):
The two products are different, which is the next big topic. First, what does a product mean?
AB means: first B, then A
Here is the reason matrix multiplication is defined this way. Take any vector x with p entries. Apply B to it, then apply A to the result:
xBBxAA(Bx)
The claim is that doing both steps is the same as doing one step with the matrix AB:
(AB)x=A(Bx)
Why? Write x‘s effect through B‘s columns (Way 2 of P1.B5): Bx=x1b1+⋯+xpbp. Now apply A, and use linearity (it passes through sums and constants): A(Bx)=x1Ab1+⋯+xpAbp.. But Ab1,…,Abp are exactly the columns of AB, so the right side is (AB)x by Way 2 again. That is the whole proof, and it is why the product was defined by “apply A to each column of B”.
Read right to left. In ABx, the vector x meets B first, because B is the matrix next to it. This is the same habit as function notation: in f(g(x)) you compute g first. The shapes agree: B takes p numbers in and gives n out, and A takes those n numbers in and gives m out. So the whole thing takes p in and gives m out, which is the shape m×p of AB.
A picture with two 2×2 maps
Let R=(01−10) be a quarter turn (counter-clockwise, P1.B5) and S=(1011) the shear (x,y)↦(x+y,y). Consider SR: first rotate, then shear. To find its matrix, read the columns: follow where (1,0) and (0,1) land.
(1,0) turns to (0,1), and the shear sends (0,1) to (1,1). Column 1 is (1,1).
(0,1) turns to (−1,0), and the shear leaves (−1,0) alone. Column 2 is (−1,0).
So SR=(11−10), and multiplying the matrices gives the same: (1011)(01−10)=(11−10).. Now the other order, RS (shear first, then rotate): (1,0) stays at (1,0) and turns to (0,1);(0,1) shears to (1,1) and turns to (−1,1). So RS=(01−11). Different matrices. Look at the two results for the “F” from P1.B5:
Two maps in a row: does the order matter?
B =0−110
A =1101
AB =1−110
BA =0−111
AB and BA are different matrices, so the order matters: doing B first and then A (blue F) ends in a different place from doing A first and then B (pink F).
The grey outline is the starting “F”. AB means B first, then A: the blue F. BA means A first, then B: the pink F. The matrix AB is computed by multiplying the matrices, and it does in one step what the two maps do in two.
Two maps applied in a row. B is applied first and A second. The blue F is AB (first B, then A), the pink F is BA (first A, then B). Choose the two maps, swap them, and tick the box to see the halfway step. The status line says whether the order matters for the pair you chose.
Things to try:
Leave the defaults (B = rotate 90°, A = shear). The blue F is the one from the text: rotate, then shear. The pink F is the other order. They end in different places.
Tick Show the halfway step. The dashed blue F is where B alone puts the F (the middle of the blue route). The dashed pink F is where A alone puts it (the middle of the pink route).
Choose Rotate 90° for A and Rotate 30° for B. The two F shapes land on top of each other: turning by 30° then 90° is the same as 90° then 30°.
Choose Double everything for one map and anything for the other. Again they commute.
Choose Project onto the x-axis and Rotate 90°. Both results are flat, but they are different lines.
Intuition
Think of an assembly line with two machines. B is the first machine and A is the second. A product AB is a single machine that does the work of both. To build it, you only need to know what the line does to the two test arrows (1,0) and (0,1), which are the columns. The order matters for the same reason it does when you put on socks and then shoes: swapping the machines gives a different line.
Where the analogy breaks: with socks and shoes, one order is impossible. With matrices of the same shape both orders are possible, and you simply get two different answers (or occasionally the same one).
Math
For A∈Rm×n and B∈Rn×p, the product AB∈Rm×p has
(AB)ijAB=k=1∑nAikBkj=(Ab1⋯Abp)
and it satisfies (AB)x=A(Bx) for every x∈Rp. Composition of linear maps is a linear map, and its matrix is the product of the matrices in the order they are applied, right to left.
Code
import numpy as npA = np.array([[1, 2, 3], [4, 5, 6]])B = np.array([[ 7, 8], [ 9, 10], [11, 12]])A @ B # array([[ 58, 64], [139, 154]])A @ B[:, 0] # array([ 58, 139]): column 1 of the productA[0] @ B # array([58, 64]): row 1 of the product
A @ B is the matrix product. The runnable cells at the end of the lesson try everything here.
Order matters: AB=BA
Multiplying numbers is commutative: 3⋅5=5⋅3. Multiplying matrices is not. There are three different ways it can fail.
One order does not exist. With A of shape 2×3 and B of shape 3×4, the product AB is 2×4. But BA would be (3×4)(2×3) and the inner numbers 4 and 2 do not match, so it is not defined.
Both exist but with different shapes. The example from the start: AB is 2×2, but BA is (3×2)(2×3)=3×3. Different shapes cannot be equal.
Both exist, same shape, different values. The swap example above (PQ against QP), or rotate-then-shear against shear-then-rotate. Another: with M=(1011) and N=(1101),
MNNM=(2111)=(1112)
Some pairs do commute, and it helps to know which:
Anything with the identity: IA=AI=A.
A matrix with itself, or with its own powers: AA2=A2A.
A number times the identity, cI, with any matrix of the same size (scaling every direction equally).
Two diagonal matrices of the same size (each only stretches the axes).
Two rotations of the plane about the origin (the total turn is the sum of the angles, in either order).
What still works
Losing commutativity does not make matrices unruly. These rules all hold whenever the shapes allow the products:
Rule
Written
Associative
(AB)C=A(BC), so we write ABC
Distributive
A(B+C)=AB+AC and (A+B)C=AC+BC
Scalars move freely
(cA)B=c(AB)=A(cB)
Identity
ImA=A=AIn for A of shape m×n
Associativity is the same fact as “doing three maps in a row has one meaning”: first C, then B, then A, however you group the brackets. It is what lets a stack of linear layers be written as one long product, and it is what makes the choice of bracketing a matter of cost only (next section). The identityI has to match the sizes: for a 2×3 matrix, I2A=A and AI3=A.
Careful with the algebra you know from numbers. Because AB=BA, the middle terms do not combine:
(A+B)2=A2+AB+BA+B2
This is notA2+2AB+B2 in general.
Two more number-habits fail:
A product can be zero with neither factor zero.(1000)(0001)=(0000)..
You cannot cancel a factor. Take A=(1000),B=(1324) and C=(1526). Then
AB=AC=(1020),yet B=C.
Both come from the same cause as the projection in P1.B5: this A squashes the plane (it throws away the second coordinate), so different inputs end up the same and no step can recover them. (Matrices that can be undone are the subject of P1.B9, and then cancelling is allowed.)
Coming attractions (stated here, proved later): det(AB)=detA⋅detB,, the areas scale one after the other (P1.B8). For invertible matrices, (AB)−1=B−1A−1: to undo “first B, then A” you undo A first, like taking off shoes before socks (P1.B9). And the transpose reverses the order too, (AB)⊤=B⊤A⊤ (P1.B10). Note that it is notA⊤B⊤, whose shapes usually do not even fit.
Powers of a square matrix
If A is square (n×n), then AA is defined, since (n×n)(n×n)→(n×n). Write A2=AA,A3=AAA, and A0=I. A non-square matrix has no powers: (2×3)(2×3) is not defined. Powers mean “apply the same map again”:
The shear S=(1011) gives S2=(1021) and S5=(1051): shearing five times in a row is one shear five times as strong.
The quarter turn R gives R2=(−100−1)=−I (a half turn) and R4=I (a full turn: nothing changed).
Recurrent networks reuse the same weight matrix at every step (P6.5). With a nonlinearity and new inputs in between it is not literally a power, but without them it would be, which is why powers come back later.
How much work is a product?
Count the arithmetic in (m×n)(n×p). There are m⋅p entries. Each is a dot product of n pairs: n multiplications and n−1 additions, about nmultiply-adds.
So the product costs m⋅n⋅p multiply-adds, which is about 2mnp floating-point operations (FLOPs).
(A floating-point operation is one addition or multiplication of decimal numbers; “about 2mnp” counts each multiply-add as two.) For the first example, 2⋅3⋅2=12 multiply-adds. For two 1000×1000 matrices, 10003=109 multiply-adds, about 2×109 FLOPs, for a single product. Double all three sizes and the work grows 8 times. Compare a matrix times a vector of the same size (p=1): only 106 multiply-adds, a thousand times less.
The order of a chain matters for cost, not for the answer. Associativity says (AB)C=A(BC), but the two bracketings can do very different amounts of work. Take shapes A:10×100,B:100×5,C:5×50.
Order
Multiply-adds
(AB)C
10⋅100⋅5+10⋅5⋅50=5000+2500=7,500
A(BC)
100⋅5⋅50+10⋅100⋅50=25000+50000=75,000
(In the first order, AB is a small 10×5 matrix. In the second, BC is a larger 100×50 one.)
Same final 10×50 matrix, ten times the work. For a long chain, finding the cheapest bracketing is a classic algorithm problem; for three matrices you just compute both totals. Another common case: if the last factor is a vector, multiplying from the right (matrix times vector, then matrix times that) avoids ever building a big matrix-times-matrix product.
Because so much of a neural network is this one operation, processors for deep learning (GPUs and similar chips) are designed to do big products very fast (P10.B8), and the FLOP count of a whole model is built from counts like 2mnp (P10.B4).
Matrix multiplication in ML
You now have everything needed to read four places where products appear. The details come in later lessons; here the point is to see the shapes.
1. A layer on a whole batch. Let X be a data matrix, N examples as rows and d features as columns, so X is N×d. A layer with h outputs has a weight matrix W of shape h×d (P1.B5). Applying it to every example is one product:
N×dXd×hW⊤=N×hXW⊤
Entry (i,j) of the result is xi⋅wj: example i against neuron j. Row i is the layer’s output for example i. This is the product from the last Go deeper box of P1.B5, and now you can see why the shapes work: the inner number d is the number of features. (The transpose ⊤ swaps rows and columns; P1.B10 treats it properly.) With X=(1201−10) and W=(142536) you get
XW⊤=(−24−213)
2. Stacking layers, and why we need activations. Two layers in a row apply W1 and then W2, which is the product W2W1 (first W1). Take W1=1101−11(3×2),W2=(100111)(2×3) and x=(1,2):
So two layers with nothing in between are one layer with the matrix W2W1. Adding biases changes nothing important: W2(W1x+b1)+b2=(W2W1)x+(W2b1+b2) is still one matrix plus one bias. Ten stacked linear layers are still one. The fix is the squashing step from P1.B5. Put ReLU(z)=max(0,z) (entry by entry, P4.4) between them: ReLU(W1x)=(3,0,2),, and then W2(3,0,2)=(5,2), which is not(5,1). So the single matrix W2W1 no longer reproduces the network here. Nonlinearity is what makes depth useful (P4.3).
3. Attention scores. In attention (P7.3) there are T tokens, each with a query vector and a key vector of length dk, stacked as the rows of Q and K, each T×dk. The scores for every pair of tokens come from one product:
T×dkQdk×TK⊤=T×TQK⊤
Entry (i,j) is qi⋅kj, the score of token i looking at token j. With Q=101021 and K=110011, the scores are
QK⊤=101122021
Real attention then rescales the scores, applies a softmax to each row, and multiplies by a value matrix V(T×dv) to get a T×dv result: (T×T)(T×dv)→(T×dv).. P7.3 does that step by step; the point here is that it is products all the way, and the T×T matrix is why attention cost grows with the square of the sequence length.
4. LoRA: a big matrix as a product of thin ones. Fine-tuning a big weight matrix W of shape d×d means learning a change of the same shape, which is d2 numbers. LoRA (Hu et al., 2021) keeps W frozen and learns the change as a product BA of two thin matrices (the paper’s letters: here A and B are new matrices, and A acts first), shapes d×r and r×d with a small r:(d×r)(r×d)→(d×d), the right shape to add to W. (Real weight matrices are often not square, d×k; then the factors are d×r and r×k.) For the example sizes d=1000 and r=8 that is 1000⋅8+8⋅1000=16,000 numbers instead of 1,000,000. A product of thin matrices cannot do everything a full matrix can: its rank is at most r (P1.B7). P10.E3 covers the method.
Go deeper The outer-product view: a product as a sum of simple pieces
There is a fourth way to compute a product. Take column k of A and row k of B, multiply them as a column times a row (an m×1 times a 1×p gives a whole m×p matrix, the outer product), and add over k:
AB=k=1∑nakrk⊤
where ak is column k of A and rk⊤ is row k of B (written as a transpose, like the data rows in P1.B5).
Each piece has a very simple shape (all its rows are multiples of one row). The reason is the sum in the entry formula: entry (i,j) is ∑kAikBkj, and the k-th term of every entry together forms the k-th piece. Two reasons to know it: it shows that a product of an m×r and an r×p matrix is a sum of only r such pieces, which is the idea behind LoRA above and behind low-rank approximation (P1.B13); and it is the view you want when the inner dimension is small.
Go deeper Why associativity holds, and block multiplication
Associativity, by entries. Write out entry (i,j) of both sides. It is the same sum of triple products AikBklClj (over all k and l), added in a different order:
The picture version: both sides mean “first C, then B, then A”.
Blocks. You may cut matrices into rectangular blocks and multiply the blocks as if they were numbers, as long as the cuts line up so every block product has matching shapes: cut A‘s columns and B‘s rows in the same places. For example, (PRQS)(EGFH)=(PE+QGRE+SGPF+QHRF+SH).. Splitting a big product into small block products is how software and hardware organise large products into pieces that fit in fast memory or can be done in parallel.
Go deeper Is the plain recipe the fastest possible?
The recipe above uses about n3 multiply-adds for two n×n matrices. In 1969 Volker Strassen showed that two 2×2 matrices can be multiplied with 7 multiplications instead of 8, and applying this idea repeatedly to blocks gives about nlog27≈n2.81 operations. Faster methods with smaller exponents have been found since, and the best possible exponent is a research question. Whether such methods help in practice depends on matrix size and hardware, so this lesson (and most FLOP counting in deep learning, P10.B4) uses the plain count mnp.
Matrix multiplication in NumPy
Run the cell and read each line against the text. It covers the product, the four views, order, powers, * versus @, and the shape error.
Try it: matrix products in NumPy
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
A few things to take from it:
@, np.matmul and np.dot. For 2-D arrays all three give the matrix product. @ is the one to use: it is short, and np.dot behaves differently for arrays with more than two dimensions (P1.B14).
* is not the matrix product.P * P multiplies entry by entry (the Hadamard product, which appears in ML for masks and gates). It needs equal shapes (or shapes NumPy can stretch to match, P1.B14). P @ P is the matrix product.
Shape errors.A @ A with A of shape (2,3) raises an error whose first words are matmul: Input operand 1 has a mismatch in its core dimension 0. The exact wording varies between NumPy versions, but it always means the inner dimensions do not match. Read it as: “the 3 columns of the left array do not match the 2 rows of the right one”.
The second cell is about plain 1-D arrays, where @ quietly does something sensible.
Try it: @ with 1-D arrays, and what a product costs
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Here A @ v treats the 1-D array v as a column, and v @ A.T treats it as a row on the left, so the result has no leftover dimension. Two 1-D arrays give a single number. A plain number is not allowed in @ (A @ 2 raises an error): use 2 * A to scale.
Common mistakes
Check your understanding
A is 5×3 and B is 3×7. What is the shape of AB?
The inner numbers (3 and 3) match and disappear. The outer numbers give the result: 5 rows from A and 7 columns from B, so 5 × 7. A 7×5 result would be B⊤A⊤, a different product.
Let A=(1324) and B=(5768). What is the entry in row 2, column 1 of AB?
Row 2 of A is (3, 4) and column 1 of B is (5, 7), so 3·5 + 4·7 = 15 + 28 = 43. The value 19 is entry (1, 1), 39 pairs row 2 of A with row 1 of B, and 21 is the entry-by-entry product 3·7.
R turns the plane by a quarter turn and S is a shear. What does the matrix SR do to a vector?
In SRx the matrix next to the vector, R, acts first, then S acts on the result. The order matters here: SR and RS are different matrices.
A is 10×100,B is 100×5 and C is 5×50. Which statement is true?
Associativity means the result is the same. The cost is not: (AB)C costs 10·100·5 + 10·5·50 = 7,500 multiply-adds, while A(BC) costs 100·5·50 + 10·100·50 = 75,000.
A network has two linear layers with matrices W1 and W2 and no activation function or bias between them. What is the pair equivalent to?
First W1 and then W2 is the product W2W1 (the first step is written on the right). The sum is a different matrix, and W1W2 is generally a different matrix and may not even have fitting shapes. This collapse is why networks put a nonlinearity between layers.
Exercises
Compute (1−10321)321110.Show answerThe shapes are (2×3)(3×2), so the result is 2×2.(1,0,2)⋅(3,2,1)=5,,(1,0,2)⋅(1,1,0)=1,,(−1,3,1)⋅(3,2,1)=−3+6+1=4,,(−1,3,1)⋅(1,1,0)=−1+3=2.. The product is (5412).
A is 4×2,B is 2×5 and C is 5×4. Which of AB,BA,AC,CA,BC,CB are defined, and what are their shapes? Show answerAB:(4×2)(2×5)→4×5.CA:(5×4)(4×2)→5×2.BC:(2×5)(5×4)→2×4. The other three are not defined: BA(5=4),AC(2=5),CB(4=2).
For A=(1324) and B=(2103), find only the second column of AB and only the first row of AB.Show answerColumn 2 is A(0,3)=(6,12). Row 1 is (1,2)B=1⋅(2,0)+2⋅(1,3)=(4,6).. (The full product is (410612), which agrees.)
Find the matrix of “scale x by 2 (first), then quarter turn counter-clockwise (second)”, by tracking where (1,0) and (0,1) land. Then check it by multiplying matrices, and find the matrix for the opposite order. Show answerTracking: (1,0)→(2,0)→(0,2) and (0,1)→(0,1)→(−1,0),, so the columns are (0,2) and (−1,0):(02−10). Multiplying: RD=(01−10)(2001)=(02−10).. The opposite order DR=(01−20) is different.
Show that M=(1011) and N=(1101) do not commute. Show answerMN=(2111) but NM=(1112).
How many multiply-adds does (200×300)(300×400) need, and roughly how many floating-point operations is that? Show answer200⋅300⋅400=24,000,000 multiply-adds, so about 48,000,000 FLOPs (using 2mnp).
A is 50×2,B is 2×50 and C is 50×1. Compare the cost of (AB)C and A(BC).Show answer(AB)C:50⋅2⋅50+50⋅50⋅1=5000+2500=7500..A(BC):2⋅50⋅1+50⋅2⋅1=100+100=200.. Doing the vector C first is 37.5 times cheaper, and the answer (a 50×1 vector) is the same.
Find a non-zero 2×2 matrix N with N2=0.Show answerN=(0010): Row 1 of N2 is (0,1)N=1⋅(0,0)=(0,0) and row 2 is (0,0)N=(0,0), so N2=0. A non-zero matrix can square to zero, which no non-zero number does.
A dataset X has 32 examples and 10 features. A layer has 4 outputs. What are the shapes of W and of the layer’s output on the whole dataset (before any bias or activation)? Show answerW is 4×10 (rows are outputs, columns are inputs). The product is XW⊤:(32×10)(10×4)→32×4,, one row of 4 outputs per example.
In the composition widget, find two different maps (neither the identity) that commute, and a pair that does not, and explain each with one sentence. Show answerFor example, Rotate 30° and Rotate 90° commute: turning by one angle then another gives the same total turn either way. Rotate 90° and Shear do not commute: the two orders give different matrices and different F shapes. (Other commuting pairs: any two of the diagonal maps, or Double everything with anything.)
Code: for P = np.array([[1, 2], [3, 4]]) and Q = np.array([[0, 1], [1, 0]]), predict P * Q and P @ Q, then run them. Show answerP * Q is [[0, 2], [3, 0]] (entry by entry). P @ Q is [[2, 1], [4, 3]]: multiplying by the swap matrix on the right swaps the columns of P.
Key takeaways
The entry in row i and column j of AB is row i of A dotted with column j of B:(AB)ij=∑kAikBkj.
Shapes: (m×n)(n×p)→(m×p). The inner dimensions must be equal, and the outer ones give the shape of the result. A matrix times a vector is the case p=1, and a row times a column is a dot product.
The columns of AB are A times the columns of B, and the rows of AB are the rows of A times B.
AB means first B, then A:(AB)x=A(Bx). Matrix multiplication is composition of linear maps, read right to left.
Order matters: AB=BA in general (and one of them may not even exist). But (AB)C=A(BC), products distribute over sums, and I does nothing. You cannot cancel: AB=AC does not force B=C.
An (m×n)(n×p) product costs mnp multiply-adds (about 2mnp floating-point operations). Associativity lets you pick the cheapest order for a chain.
In NumPy, A @ B is the matrix product and A * B is entry by entry. Two linear layers with no nonlinearity between them collapse into one matrix, which is why networks put an activation function in between.