Sub topic 11
Broadcasting in practice
This chapter assumes you know the broadcasting rules, np.newaxis, keepdims, and reductions along an axis. Here you apply them to three common jobs: centering columns, centering rows, and computing pairwise distances.
Centering and scaling
Centering means subtracting a mean so the data is centered on zero. The mean's shape decides whether the subtraction broadcasts correctly.
import numpy as np
x = np.array([[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0]])
col_centered = x - x.mean(axis=0) # mean has shape (3,)
row_centered = x - x.mean(axis=1, keepdims=True) # mean has shape (2, 1)
print(col_centered) # [[-1.5 -1.5 -1.5]
# [ 1.5 1.5 1.5]]
print(row_centered) # [[-1. 0. 1.]
# [-1. 0. 1.]]x.mean(axis=0) has shape (3,). NumPy aligns it with the trailing axis of x, which has shape (2, 3). The same row of means is subtracted from every row.
x.mean(axis=1) would have shape (2,). That does not align with (2, 3), because the trailing sizes 2 and 3 differ. Passing keepdims=True keeps the reduced axis as size 1, so the mean has shape (2, 1). That size-1 axis stretches across the three columns.
Scaling works the same way. Dividing by x.std(axis=0) gives each column unit spread. Dividing by x.std(axis=1, keepdims=True) does the same for each row.
Pairwise computations
Broadcasting can also compare every item with every other item. For points, the idea is to give the same array two different shapes and let broadcasting build all the pairs.
import numpy as np
pts = np.array([[0.0, 0.0],
[3.0, 4.0],
[6.0, 8.0]])
diff = pts[:, np.newaxis, :] - pts[np.newaxis, :, :] # shape (3, 3, 2)
dist = np.sqrt((diff ** 2).sum(axis=-1)) # shape (3, 3)
print(dist)
# [[ 0. 5. 10.]
# [ 5. 0. 5.]
# [10. 5. 0.]]The first operand has shape (3, 1, 2) and the second has shape (1, 3, 2). Each size-1 axis stretches to 3, so the result has shape (3, 3, 2). Entry diff[i, j] is point i minus point j. Summing the squares over the last axis gives squared distances. Taking the square root gives dist[i, j], the distance between points i and j.
A recipe for aligning shapes
When a broadcast does not do what you want, work through these steps:
- Write down the shape of each operand.
- Decide which axis of the result each operand axis should line up with.
- Insert
np.newaxis(or usekeepdims=Trueafter a reduction) so that every axis you want to stretch has size 1. - Check the result shape before trusting the values.
Exercise
A matrix m has shape (5, 3). You compute m / m.sum(axis=1) to turn each row into proportions, and NumPy raises a ValueError. What is the cause, and what is the fix?
Show answer
m.sum(axis=1) has shape (5,). Broadcasting compares trailing axes, so it tries to match 5 against 3 and fails. Keep the reduced axis with m / m.sum(axis=1, keepdims=True), which divides by a (5, 1) array, or write m.sum(axis=1)[:, np.newaxis].
Exercise
Two arrays have shapes (4, 1, 3) and (2, 1). What is the broadcast result shape?
Show answer
Align the shapes on the right: (4, 1, 3) and (1, 2, 1). The result takes the larger size on each axis, giving (4, 2, 3).