Two questions have been waiting since earlier lessons. In P1.B5 a rotation by carried the point to , and its distance from the origin stayed . Why does a rotation never change a length? And in P1.B6 and P1.B9 a small symbol appeared again and again, always with the promise “P1.B10 explains it”. This lesson keeps both promises. First the transpose (swap rows and columns) and what it really means. Then two special families of matrices: symmetric matrices, which equal their own transpose, and orthogonal matrices, which are exactly the rotations and reflections.
The transpose: flip across the diagonal
The transpose of a matrix , written , swaps its rows and columns. Row 1 of becomes column 1 of , row 2 becomes column 2, and so on. Take the matrix from P1.B5 and P1.B6:
In symbols, the entry in row and column of is the entry of in row and column :
Entries on the diagonal () stay where they are, and every other entry swaps with its mirror image across the diagonal. The shape changes too: is (2 rows, 3 columns) and is . In general an matrix has an transpose. A square matrix keeps its shape.
A vector is a matrix with one column (P1.B5), so its transpose is a matrix with one row:
That is why the dot product of P1.B3 can be written : a row times an column is a matrix, a single number, and it is the sum of the products of matching entries. The data matrix of P1.B5 is the stack of the examples written as rows .
Things to try:
- The first matrix is the one above. Tap the entry (row 1, column 3): it sits at row 3, column 1 of . The shape reads .
- Choose Column 3 × 1: a column vector becomes a row vector.
- Choose 3 × 3. The diagonal does not move. The status says “Not symmetric” and names a pair that differs.
- Choose Symmetric 3 × 3: the status says the flip changes nothing. Now tap an entry off the diagonal and press +1. The status turns to “Not symmetric”, because the entry and its mirror image no longer match. Press −1 to fix it.
- Tick Also show AᵀA. Whatever matrix you choose, is symmetric. The next sections show why.
Intuition
Picture the matrix as a table on a sheet of paper. Draw the diagonal from the top-left corner to the bottom-right, and flip the sheet over along that diagonal, like turning a page along a slanted hinge. What was a row now reads down as a column. A mirror placed along the diagonal gives the same picture: every entry trades places with its reflection.
The analogy only describes the table. It does not say what the transpose does to vectors, and that is more interesting. A matrix sends a vector from one space to another; the transpose does a different job, which the section after the rules explains. It is not the inverse (it does not undo , except for the special matrices at the end of this lesson).
Math
. If is then is . The -th row of is the -th column of , and the -th column of is the -th row of . For a vector, is the row with the same entries, and .
A matrix is symmetric if and skew-symmetric if . Both need a square matrix.
Code
import numpy as np
A = np.array([[1, 2, 3], [4, 5, 6]])
print(A.T) # [[1 4] [2 5] [3 6]]
print(A.shape, A.T.shape) # (2, 3) (3, 2)A.T is the transpose. In NumPy it is a view of the same numbers (no copy is made), so changing an entry of A.T changes A. The last section has a warning about 1-D arrays.
Rules of the transpose
Three rules are easy to believe because the transpose only moves entries around:
- : flip twice and you are back.
- (same shapes).
- for a number .
The fourth one needs care, and you met it in P1.B6 as a promise: the transpose of a product reverses the order.
The shapes show that this is the only possible order. Let be and be . Then is , so is . Now try both candidates:
- is times : it fits and gives .
- is times : it only fits when , and it would then be , the wrong shape.
A check with numbers. Take the above and . Then
You can see why entry by entry. Entry of is entry of , which is (row of ) (column of ). For : . And (row of ) (column of ) is the same two lists of numbers, so it is the same dot product. Like the inverse rule of P1.B9, it is the shoes-and-socks rule: reverse the order. It extends to longer products, .
The payoff you were promised. In P1.B5 and P1.B6 you saw X @ W.T for a layer applied to a data matrix whose rows are examples. If one example is the column , the layer gives . As a row, that result is by the product rule. Stack the rows into and you get , whose row is the output for example . With above and this is the of P1.B5.
Two more rules connect the transpose to earlier lessons.
Inverse. If is invertible, so is , and . Reason: by the product rule, , so is the inverse of . It is the rule P1.B9 checked on .
Determinant. . For a matrix, is the same number as . The general case is the rule stated in P1.B8. It means that a matrix and its transpose stretch areas and volumes by the same factor, and also that a matrix and its transpose have the same rank (P1.B7).
Intuition
To undo “put on socks, then shoes” you take off the shoes first. The transpose reverses a product in the same way, but for a different reason: it is not undoing anything, it is reading the whole table of products from the other side. The row-times-column pairs that make up are the same pairs that make up , read in the other order.
Math
Entry-wise: .
Not rules: in general, and in general.
Code
import numpy as np
A = np.array([[1, 2, 3], [4, 5, 6]])
B = np.array([[1, 0], [2, 1], [0, 3]])
print(np.array_equal((A @ B).T, B.T @ A.T)) # TrueA.T @ B.T also runs here ( times gives a matrix), but it is a different matrix, so a program that runs is not proof that you used the right order. Check .shape.
What the transpose really does: moving across a dot product
The product rule gives the transpose its meaning. Take a matrix (), a vector in and a vector in . The dot product is
So you can move to the other side of a dot product if you transpose it. Check it with and from above, and . Then , and . On the other side, , and . Same number. Mathematicians call the adjoint of (for real matrices): the matrix that makes this identity true for every and .
Why backpropagation uses . A layer computes , and later the loss depends on . During backpropagation (P4.8) the gradient arrives from above. It says: if changes by a small , the loss changes by about . Now nudge the input by . The output changes by , so the loss changes by about
and a gradient with respect to is exactly the vector that, dotted with , gives the change in . So . With above and this is . Test it: raising by changes by the second column of , , and , the second entry. (This is a first-order estimate, which is exact here because the layer is linear and is treated as linear in .) The shapes agree too: has entries, is , and the result has entries, one gradient per input, as it must.
That is the “swap” that P4.8 mentions: in the forward pass a signal goes through , and in the backward pass the gradient goes through . P1.C11 derives the full matrix calculus and P4.10 builds a network this way.
Symmetric matrices
A square matrix is symmetric if it equals its own transpose, , which means : the entries mirror across the diagonal. For example
Symmetric matrices are everywhere, because many quantities are between pairs and a pair has no order:
- A distance table: the distance from town 1 to town 2 equals the distance from 2 to 1. For towns at , and the table is .
- A covariance matrix (P1.D7): the covariance of feature with feature equals that of with .
- A Hessian, the matrix of second derivatives (P1.C8), for smooth functions.
- The matrices below.
and are symmetric for every matrix , even a non-square one. By the product rule and ,
and the same for . There is a picture behind it. Entry of is (column of ) (column of ), and a dot product does not care about order. For :
Entry of the first is entry . Notice the shapes: is (one row and column per column of ) and is (one per row). If is a data matrix with examples as rows and features as columns, then is (features against features) and is (every example against every other, a Gram matrix of dot products). For the second one is . For data whose columns have mean , divided by (or by , depending on the convention) is the covariance matrix. Least squares (P1.B11 and P3.A2) leads to the normal equations , a linear system whose matrix is symmetric.
Two cautions. A product of two symmetric matrices is usually not symmetric, because , which equals only when they commute (P1.B6). For and , . And an attention score matrix (P7.3) is not symmetric in general, because the queries and the keys are different matrices. (Its transpose is .)
Go deeper Positive semi-definite: AᵀA never makes a negative bowl
For any and any vector ,
A symmetric matrix with for every is called positive semi-definite. So is always positive semi-definite. A covariance matrix is too: for a vector of length , is the variance of the data projected on that direction, and a variance cannot be negative (P1.D7). P1.C8 uses the same idea to tell bowls from saddles. Here it is only a preview. For and : , so : the value is allowed, and has no inverse here (rank for a matrix).
Go deeper Every square matrix is a symmetric part plus a skew part
For any square , . The first piece is symmetric, and the second is skew-symmetric (, so its diagonal is ). For the pieces are and . The skew piece here is the rotation of P1.B5. A symmetric matrix stretches along perpendicular directions (the next box), and a skew-symmetric matrix is a quarter turn times a number. Also: the inverse of an invertible symmetric matrix is symmetric, since .
Go deeper Why symmetric matrices are so well behaved (a preview of eigenvalues)
P1.B12 proves the spectral theorem: a real symmetric matrix has real eigenvalues and a set of perpendicular eigenvectors, so it stretches space along perpendicular directions and does nothing else. The symmetric matrix of P1.B8 stretches the direction by and the perpendicular direction by . That is why PCA (P3.C3) can find perpendicular directions of largest variance in a covariance matrix. A non-symmetric matrix can have eigenvectors that are not perpendicular, or even no real ones (a rotation).
Orthogonal matrices
Now the second special family. From P1.B3, two vectors are orthogonal (perpendicular) if their dot product is . A set of vectors is orthonormal if they are orthogonal to each other and each has length (“norm” , hence “ortho-normal”). The vectors and are orthonormal, and so are and .
A square matrix is orthogonal if its columns are orthonormal. There is a one-line test using the transpose. Entry of is (column ) (column ) , which is if (unit length) and if (perpendicular). So
The rotation by is the example from P1.B5. Its columns and have length and dot product . For any angle, each column has length and the two columns have dot product , so every rotation matrix is orthogonal. The widget lets you turn, mirror and break it.
Things to try:
- At the start, . lands at and its length stays . Drag the slider: the solid circle passes through the moving at every angle, and the readouts (the lengths, the angle and the dot product ) never change. is the identity for every angle.
- Press 0°, 90°, 180° and 360°. and give , and gives : every vector goes to its opposite, yet lengths are still kept.
- Tick Reflect. The F comes out mirrored, the determinant is , and lengths, angle and dot product are still unchanged. is now a symmetric matrix as well (a reflection is its own inverse).
- Compare with for a rotation: is the rotation by , so it undoes (P1.B9).
- Press Any matrix (for contrast). The start matrix is not orthogonal: is not , the circle becomes an ellipse and lengths change.
- Press Perpendicular columns, length √2. The columns and are perpendicular, but the matrix is not orthogonal: and every length is multiplied by .
- Press Rotation with rounded entries (a rotation by about with entries rounded to two decimals). The status says “almost orthogonal”, because by a hair. Orthogonality is exact: it is true or it is not, and rounding breaks it slightly.
Intuition
An orthogonal matrix moves a rigid object: a coin on a table can be turned (rotation) or flipped over (reflection), but it is not stretched, squashed or sheared. Distances between all points, and so all angles, stay the same. The only things that change are position and orientation.
Where the picture misleads: in higher dimensions there are many more ways to turn than “by an angle ”. A rotation in 3-D has an axis, and an orthogonal matrix in 100-D can mix all the directions at once. The facts below hold in every dimension, and the 2-D picture is only the easiest one to draw.
Math
() is orthogonal the columns are an orthonormal set. Then is invertible with , so also (the rows are orthonormal too), and:
2-D rotation by () and reflection ():
Code
import numpy as np
t = np.radians(30)
Q = np.array([[np.cos(t), -np.sin(t)], [np.sin(t), np.cos(t)]])
print(np.allclose(Q.T @ Q, np.eye(2))) # TrueCompare with np.eye(2) using np.allclose rather than ==: floating-point rounding leaves tiny errors.
Why lengths, dot products and angles are kept
The proof is two lines. Write the length with a dot product (P1.B3 and P1.B4), , and use :
The same line with two vectors gives . Since the angle between two vectors comes from (P1.B3) and all three quantities are unchanged, the angle is unchanged. Check with the widget’s numbers: has , and the dot product of and is still , giving the angle before and after. It also explains why every distance is kept: the distance between and is , and .
The converse is also true: a square matrix that keeps the length of every vector is orthogonal (the dot products follow from the lengths). So for square matrices “orthogonal” and “preserves lengths” are the same property. (A tall matrix can keep lengths too, without being orthogonal: see the box on tall matrices below.)
The inverse is the transpose
says that is a left inverse of , and for a square matrix a left inverse is the inverse (P1.B9). So
This is the cheapest inverse there is: no elimination, just a flip. It is also the promise of P1.B9: the inverse of the rotation by is the rotation by , which is the transpose, because and swap the two entries. Because as well, the rows are orthonormal too. And the determinant: , so , as P1.B8 stated: areas and volumes are kept (), and the sign tells whether the space is flipped.
Every orthogonal matrix is a rotation or a reflection
Let be and orthogonal. Its first column is a unit vector, so it is for some angle . The second column is a unit vector perpendicular to the first, and in the plane there are exactly two of those: and its opposite . So
or
The first is the rotation by with . The second has : it is a reflection in the line through the origin at angle (the widget’s checkbox draws it as “flip the -axis, then turn by ”). Points on that line stay where they are, and points perpendicular to it are sent to their opposites. A reflection is symmetric () and is its own inverse (). For example gives , the swap of the two coordinates: a mirror in the line . In higher dimensions the picture is the same: means a rotation, means a reflection (possibly combined with a rotation).
More facts about orthogonal matrices
- Products. If and are orthogonal, so is : . A rotation followed by a reflection is orthogonal, and two rotations make a rotation by the sum of the angles. The inverse and the transpose of an orthogonal matrix are orthogonal too.
- Permutation matrices. A matrix that only reorders coordinates, such as (which sends to ), has one in each row and column and zeros elsewhere. Its columns are orthonormal, so it is orthogonal. Reordering never changes a length.
- The name trap. “Orthogonal matrix” means orthonormal columns: perpendicular and of length 1. A matrix with perpendicular columns of other lengths is not orthogonal. has perpendicular columns but , and it stretches to length . The matrix has : dividing by gives the orthogonal rotation by . Remember: orthogonal matrices keep lengths; matrices with merely orthogonal columns can stretch. The name is unlucky, and some books say “orthonormal matrix”, but “orthogonal matrix” is the standard term.
- Coordinates are dot products. If are the columns of , they form an orthonormal basis (P1.B7), and the coordinates of a vector in that basis satisfy . In a general basis you must solve this system (P1.B9). Here : each coordinate is one dot product, , and . This is the payoff promised in P1.B7. Example: , and give , and indeed . The coordinates have the same length as : .
- Numerically the best. All stretch factors of are , so its condition number (largest stretch over smallest, P1.B9) is : solving with or multiplying by does not magnify errors. That is one reason software likes orthogonal matrices.
Go deeper Tall matrices with orthonormal columns
A non-square matrix can have orthonormal columns too. The matrix has columns and : each has length , and the dot product is (the pair from P1.B3). So , and keeps lengths: , by the same two-line proof. For , , of length . But is and not the identity:
Its trace is , not . This matrix is a projection, which sends every vector of onto the plane spanned by the two columns (P1.B11). The inverse needs a square matrix: for a tall matrix, is only a left inverse. (A wide matrix cannot have more orthonormal columns than rows, since perpendicular vectors need at least dimensions.)
Go deeper Orthonormal bases from any basis: Gram–Schmidt and QR
Given any independent columns (P1.B7), you can build orthonormal ones that span the same space: take the first vector and scale it to length ; subtract from the second its component along the first and scale; and so on. This is Gram–Schmidt. Written as a matrix product it is the QR factorization , where has orthonormal columns and is upper triangular. In NumPy, np.linalg.qr(M) does this (it uses a different, more stable method than Gram–Schmidt, and may flip signs of columns). The projection step is the topic of P1.B11.
Go deeper Rotations in a position code: why RoPE keeps the dot product tidy
Let be the rotation by angle . Two facts from this lesson, and “two rotations add their angles”, give
The result depends on only. Rotary position embeddings (RoPE, P7.14) rotate pairs of entries of the query and key vectors by angles proportional to the token’s position (each pair turning at its own rate), so the attention score depends on the offset between two positions rather than on the positions themselves. A numeric check with , and per position: positions , and all have offset and all give the score . And since rotations keep lengths, the rotation never changes the size of or . (This shows the mathematical reason, not the details of any particular model.)
Go deeper Orthogonal matrices in a deep linear chain
Stack layers with every orthogonal. The product is orthogonal, so the length of the signal is exactly the same at the end: . Compare a chain whose matrices stretch every length by : after layers the factor is , and for it is . Lengths explode or vanish exponentially unless every layer keeps every length, as orthogonal matrices do. The backward pass multiplies by at each layer (see above), which is also orthogonal, so the gradient’s length is kept the same way. That is the reasoning behind orthogonal initialization, which starts a weight matrix as a random orthogonal matrix, and behind the vanishing and exploding gradients of P4.16. Real networks have nonlinear activations between the layers, which break the exact statement, so this is a good starting point, not a guarantee.
Try it in NumPy
The first cell checks the product rule, the symmetry of , the dot-product identity and the 1-D trap.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
What to expect: the two sides of the product rule agree (True), is the matrix above and is symmetric, and both sides of the dot-product identity are . The 1-D line is the trap: for a 1-D array v.T is v’s own shape, (3,). NumPy does not know whether a 1-D array is a row or a column, so there is nothing to flip. (That is also why v @ v is the dot product, a number.) To get a real column or row, make the array 2-D with v.reshape(-1, 1) or v[:, None]. Beware a silent bug: np.outer(v, v) is , not the number . Check .shape when the transpose seems not to work.
The second cell checks the orthogonal matrix from the widget, the name trap, the tall matrix, and np.linalg.qr.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
What to expect: every line that tests prints True, the length stays , and the condition number print (when this lesson was checked; the last digits of floating-point results can differ between machines, which is why the cell rounds and uses np.allclose). is , the tall matrix has T^T T = I true and T T^T = I false with trace , and np.linalg.qr returns a with orthonormal columns and an with . Test orthogonality with np.allclose(Q.T @ Q, np.eye(n)) rather than ==, because rounding leaves tiny errors.
Where you will meet it next
- Backward pass (P4.8, P4.10, P1.C11). A layer sends gradients back with . If is orthogonal, then the backward map is exactly , and it keeps the length of the gradient.
- Covariance and PCA (P1.D7, P3.C3). A covariance matrix is symmetric, so its eigenvectors can be chosen perpendicular, and the principal directions of PCA form an orthonormal set.
- Attention (P7.3). The scores are all pairs of dot products in one matrix product. (Here means the matrix of queries, not an orthogonal matrix.)
- Weight tying. Several language models use the same matrix twice: the embedding matrix (one row per word) turns a word into a vector by picking its row, and the output layer reuses the same numbers to give one score per word, for a row vector . The transpose is what makes the shapes fit.
- SVD (P1.B13). Every matrix can be written as “rotate or reflect, stretch along the axes, rotate or reflect again”, with and orthogonal.
- Position and initialization (P7.14, P4.12). Rotary embeddings and orthogonal initialization both use the fact that an orthogonal matrix keeps lengths (see the Go deeper boxes above).
- Arrays and axes (P1.B14). The same idea for arrays with more than two axes is that
.Treverses all the axes, NumPy’sswapaxesswaps two of them, and PyTorch’spermutereorders them all; that lesson treats it.
Common mistakes
Check your understanding
is a matrix. What is the shape of ?
is , so is , one row and column per column of . The shape belongs to .
is and is . Which expression equals ?
is , so its transpose is . is , and it is the true rule. would be , which cannot be multiplied.
Which matrix is symmetric?
Only equals its transpose: the two off-diagonal entries are both . The matrix with and is not, the matrix is not square, and the one with off-diagonal and is not.
Which matrix is orthogonal?
Its columns are perpendicular () and each has length , so . The diagonal matrix with and stretches the axes, the matrix with entries has perpendicular columns of length (so ), and the shear has columns that are not perpendicular.
is orthogonal and . What is ?
An orthogonal matrix keeps lengths: , so the length is whichever it is. The is and the is the squared length.
A orthogonal matrix has determinant . What does it do?
An orthogonal matrix has and keeps lengths, so areas are kept. A negative sign means the plane is flipped over, which is a reflection. A rotation has determinant .
To compute for an orthogonal , the cheapest correct step is to:
means is the inverse. Elimination would also work, but it is slower. Dividing by the determinant () does nothing useful, and negating every entry gives , whose product with is .
A layer computes with of shape . During backpropagation the gradient with respect to arrives. How is the gradient with respect to computed?
Moving across the dot product turns it into , and the shapes fit: gives entries, one per input. is not even defined ( times a vector with entries), and a matrix has no inverse. has the wrong length: entries, one per output, not one per input.
Exercises
- Write the transpose of and give both shapes.
Show answer
. The original is and its transpose is . - Check for and .
Show answer
(the columns of swapped), so . And . They agree. Here is different. - Make into a symmetric matrix by splitting it into and .
Show answer
The symmetric part is and the skew-symmetric part is . Their sum is . - Compute and for . Which one is , and what do their entries mean?
Show answer
(, features against features: entry is column column ) and (, examples against examples). Both are symmetric. - For compute . Is orthogonal? What would you divide by to get an orthogonal matrix?
Show answer
. The columns are perpendicular but have length , so is not orthogonal. Dividing by gives an orthogonal matrix (a rotation by about ). - Show that is orthogonal, find its determinant and say whether it is a rotation or a reflection.
Show answer
The columns are and : lengths and , dot product , so . The determinant is , so it is a reflection. It is symmetric, so it is its own inverse. - Find the inverse of the rotation by , , without elimination.
Show answer
The inverse is the transpose, , which is the rotation by . Check: the product of the two is . - A vector has length and is orthogonal. What are , and ?
Show answer
All three are : and are orthogonal too, and orthogonal matrices keep lengths. - Find the coordinates of in the orthonormal basis , .
Show answer
and . Check: , and , the length of . - Is orthogonal? What is its inverse, and what does it do to ?
Show answer
It is a permutation matrix: each column has a single , in different rows, so the columns are orthonormal and . It sends to . The inverse is its transpose , which sends to and undoes the move. - A orthogonal matrix has first column . Write both possibilities for the second column and say which matrix is a rotation.
Show answer
The second column is . With the matrix is with : a rotation (by about ). With the determinant is : a reflection. - Is symmetric when and are symmetric? What condition makes it so?
Show answer
, so is symmetric exactly when . In general it is not: . - A layer has and the gradient arriving at its output is . Find the gradient at its input.
Show answer
with is : two entries, one per input. - Code: build a random matrix with
np.random.randn(3, 3), takeQ, _ = np.linalg.qr(M), and check thatQ.T @ Qis the identity and thatnp.linalg.det(Q)is .Show answer
np.allclose(Q.T @ Q, np.eye(3))isTrueandabs(np.linalg.det(Q))is about (the sign can be or depending on the random matrix). The columns ofQare orthonormal for any randomMwith independent columns.