Linear algebra in numpy
Write matrix products with @, transpose with .T, and check shapes in code.
Builds on: Vectorized numpy, Matrix multiplication
What the animation says
Two ways to multiply
On paper, X times W is one product. Rows of X meet columns of W. In numpy you have two ways to write a times sign: the star, and the at sign. Here are two small square arrays, A and B, each two by two. This line multiplies them with the star. What comes out?
Star hides, at multiplies
It runs, with no warning, and gives zero, two, three, zero. The star multiplies matching entries: one times zero, two times one, and so on. The at sign does the real matrix product. Each entry is a row of A with a column of B. First row, one two, with first column, zero one: zero plus two, so two. The full product is two, one, four, three. Different numbers, and the star never complained. With square arrays, the wrong operator hides. Use the at sign for matrix products.
Inner sizes meet, outer stay
Now X with three rows and two columns, times W with two rows and three columns. The inner sizes, two and two, match. The result takes the outer sizes: three by three. First row of X, one two, meets each column of W: one, two, and four. The star can't do this. Shapes three by two and two by three don't line up, so numpy raises an error. Row two of X, three four, with the third column of W, two one, gives ten. Tap where ten lands.
.T flips the shape
Dot T is the transpose. Rows become columns, so shape four by three becomes three by four. Take X, four by three. X at X fails: inner sizes three and four don't match. Value error. Flip the second one. X at X transposed is four by three times three by four: a four by four grid. Each entry is a dot product of two rows. Row zero with row one gives fourteen. Now flip the first one instead: X transposed, at X. What shape comes out?
Assert the shape
Three by three. The inner fours match, and the outer threes become the shape. So where you put the transpose decides which sizes meet in the middle. Make that a habit in code. After each product, assert the shape you expect. This line checks that Y is T by d out. If it isn't, you find out here, not three layers later. Remember: the at sign multiplies matrices, the star goes entry by entry, dot T swaps the sizes.
@ multiplies, .T flips, shapes check
The exact rules
A 3×2 times 2×3 by hand
Check shapes as you go
import numpy as np
T, d, d_out = 4, 3, 2
X = np.arange(T * d).reshape(T, d) # (4, 3)
W = np.ones((d, d_out)) # (3, 2)
Y = X @ W
assert Y.shape == (T, d_out) # (4, 2)
G = X @ X.T # (4,3) @ (3,4)
print(G.shape, G[0, 1]) # (4, 4) 14: row0 . row1
try:
X @ X # (4,3) @ (4,3): 3 != 4
except ValueError:
print("inner sizes don't match")
Remember
On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.
Bytewise
All courses