Vectorized numpy
Apply operations to whole arrays, broadcast across shapes, and reduce with sum/mean/max along an axis.
Builds on: numpy arrays and shapes
What the animation says
Why not a loop?
Here's a table of numbers: a thousand rows, five hundred twelve columns. We want three things: multiply everything by ten, subtract each column's average, and find each row's largest value. With Python loops, that's nested for statements over half a million entries. Slow, and easy to get an index wrong. Numpy lets you write each step as one line about the whole table. The looping still happens, but inside numpy's fast built-in routines, not in slow Python steps.
Elementwise and the stamp
Let's shrink the table to two rows and three columns, holding one through six. X times ten works position by position. Every entry is multiplied, and you wrote no loop. Adding two arrays of the same shape also pairs entries, position by position. Now subtract a single row of three numbers. Numpy reuses that row, like a stamp pressed onto every row. But what if you subtract two numbers instead, one meant for each row? What happens?
Line shapes up from the right
It's an error. Numpy lines shapes up from the right. Write two, three above two. The rightmost sizes, three and two, are compared. They differ, and neither is one, so it fails. The rule: each pair must be equal, or one of them must be one. A missing size counts as one. Two, three with just three: the threes match, the missing size becomes one, and the result is two by three. So subtracting a row of three column averages works: each row loses its own column's average.
Reductions collapse an axis
Reductions like sum, mean and max collapse one axis. Summing along axis zero adds down each column. One plus four is five, then seven, then nine. Shape three. Axis zero disappears from the shape. One number per column remains. Mean along axis zero divides by the two rows: two and a half, three and a half, four and a half. Those are the averages we used. Your turn. Which arrow shows how a sum along axis one adds?
keepdims: keep the slot
Now subtract each row's maximum from that row. Max along axis one gives three and six, shape two. Lined up from the right against two, three, that's the same error as before. Add keepdims equals true. The collapsed axis stays, as size one. Shape two by one. From the right: three against one, so the one stretches across the columns. Two against two matches. So what is the first row of X minus this row maximum?
The whole picture
Minus two, minus one, zero. The second row, four, five, six minus six, gives the same. Three ideas. Write the operation for the whole array, and let numpy do the looping. Match shapes from the right: sizes equal or one, and ones get stretched. Reducing along an axis removes that axis from the shape. And use keepdims when you want to combine the result with the original array again.
Whole-array ops, stretching, collapsing
The exact rules
Worked by hand
Try it, including keepdims
import numpy as np
X = np.array([[1., 2., 3.],
[4., 5., 6.]]) # shape (2, 3)
print(X * 10) # every entry times 10
col_mean = X.mean(axis=0) # shape (3,): [2.5 3.5 4.5]
print(X - col_mean) # (2,3) - (3,) -> (2,3)
row_max = X.max(axis=1, keepdims=True) # shape (2,1): [[3.],[6.]]
print(X - row_max) # [[-2. -1. 0.] [-2. -1. 0.]]
print(X.sum(axis=1)) # [ 6. 15.]
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