Sub topic 11
Broadcasting in practice
This chapter applies the broadcasting rules to three everyday jobs: centering and scaling data, building grids and tables from vectors, and computing pairwise quantities. It assumes you know the broadcasting rules (shapes are compared from the trailing end, and each pair of dimensions must be equal or contain a 1). It also assumes you know np.newaxis and keepdims, and the axis argument of reductions.
A shape-first workflow
Broadcasting problems are easiest to solve on paper before you write code. Use this routine every time:
- Write down the shape of each operand.
- Write down the shape you want the result to have.
- Add size-1 axes (with
np.newaxis,reshape, orkeepdims=True) until each operand lines up with the result. - Run the expression and check
result.shape.
Centering: subtracting a mean
Centering means subtracting a mean from each value so that the mean becomes zero. The result depends on which axis you take the mean over, and the two cases need different handling.
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.]]The two cases work for different reasons:
x.mean(axis=0)collapses the rows and leaves shape(3,). Against(2, 3), the trailing dimensions match (3 and 3), and the missing leading dimension is treated as 1. No extra work is needed.x.mean(axis=1)would leave shape(2,). Against(2, 3)it would line up 2 with 3 and fail. Withkeepdims=Truethe result is(2, 1). The 1 stretches across the three columns.
A rule of thumb: reducing over the last axis needs keepdims=True (or [:, np.newaxis]). Reducing over the first axis of a 2-D array usually works without help. In higher dimensions, keepdims=True is the safest habit, because it works for any axis.
Scaling columns and rows
Once centering works, scaling follows the same pattern. Standardizing each column (zero mean, unit standard deviation) is one expression:
import numpy as np
x = np.array([[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0]])
z = (x - x.mean(axis=0)) / x.std(axis=0)
print(z) # [[-1. -1. -1.]
# [ 1. 1. 1.]]
lo = x.min(axis=0)
hi = x.max(axis=0)
scaled = (x - lo) / (hi - lo) # min-max scaling to the range 0 to 1
print(scaled) # [[0. 0. 0.]
# [1. 1. 1.]]Each column has its own mean and spread, so x.mean(axis=0) and x.std(axis=0) both have shape (3,). Every intermediate array in the expression is either (2, 3) or (3,), and these combine without any reshaping.
To apply a different weight to each row instead, the weights need shape (2, 1):
import numpy as np
x = np.array([[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0]])
w = np.array([10.0, 100.0]) # one weight per row, shape (2,)
print(x * w[:, np.newaxis])
# [[ 10. 20. 30.]
# [400. 500. 600.]]Building grids from vectors
A column vector combined with a row vector produces a full grid. The elementwise operation is applied to every pairing of one value from each vector. This is called an outer operation.
import numpy as np
col = np.arange(3).reshape(3, 1) # shape (3, 1)
row = np.arange(4) # shape (4,)
grid = col + row # shape (3, 4)
print(grid)
# [[0 1 2 3]
# [1 2 3 4]
# [2 3 4 5]]Entry grid[i, j] equals col[i, 0] + row[j]. The same shape arrangement works for any ufunc, so a multiplication table is a one-liner:
import numpy as np
table = np.arange(1, 4)[:, np.newaxis] * np.arange(1, 5)
print(table)
# [[ 1 2 3 4]
# [ 2 4 6 8]
# [ 3 6 9 12]]Grids are useful for evaluating a function over two parameters at once. For example, you can compute np.sin(x) * np.cos(y) over a whole plane by making x a row and y a column. NumPy also provides np.meshgrid and np.ix_, which build such arrays for you. Plain broadcasting is often lighter, because the two vectors stay small until the final operation.
Pairwise computations with a third axis
Sometimes you need a value for every pair of items, such as the distance between every pair of points. The technique is to insert a new axis in a different position for each copy of the array, so that the two copies broadcast against each other.
Suppose pts has shape (n, d): n points with d coordinates each. Then:
pts[:, np.newaxis, :]has shape(n, 1, d).pts[np.newaxis, :, :]has shape(1, n, d).- Their difference has shape
(n, n, d), and entry[i, j]ispts[i] - pts[j].
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 reduction uses axis=-1 to sum over the coordinate axis, which collapses (3, 3, 2) to (3, 3). Using a negative axis means the line still works if you later add leading batch dimensions.
The result is symmetric and has zeros on the diagonal, which is a quick sanity check. The distance from point 0 to point 1 is sqrt(3**2 + 4**2) = 5.
The memory cost
The intermediate array diff holds n * n * d numbers. For 10,000 points in 3 dimensions with float64 (8 bytes each), that is 10,000 × 10,000 × 3 × 8 bytes, about 2.4 GB, before squaring creates another array of the same size. The loop-free version is fast but can run out of memory long before the loop version would. Options when this happens:
- Process the points in chunks, for example 500 rows of
ptsagainst all ofptsat a time. - Use a library routine built for this job, such as
scipy.spatial.distance.cdist. - Use
float32if the precision is acceptable. This halves the memory.
Combining broadcasting with other tools
Broadcasting composes with the selection tools from earlier chapters. A comparison is a ufunc, so it broadcasts too. This marks which columns of each row exceed that column's mean:
import numpy as np
x = np.array([[1.0, 8.0, 3.0],
[4.0, 5.0, 9.0]])
above = x > x.mean(axis=0) # (2, 3) compared with (3,), result is (2, 3) bool
print(above)
# [[False True False]
# [ True False True]]
print(np.where(above, x, 0.0))
# [[0. 8. 0.]
# [4. 0. 9.]]The same idea lets np.where take a (2, 3) condition and scalars, or other arrays that broadcast against it, as its two branches.
Common mistakes in practice
| Symptom | Likely cause | Fix |
|---|---|---|
| `ValueError: operands could not be broadcast together` | A reduction over the last axis dropped it, so the mean has shape `(m,)` where `(m, 1)` was needed | Use `keepdims=True` |
| Result has shape `(n, n)` where `(n,)` was expected | A `(n, 1)` array met a `(n,)` array | Reduce a stray axis or call `.ravel()` before combining |
| No error, but values are wrong on a square array | Weights or means applied along the wrong axis | Make the intended axis explicit with `[:, np.newaxis]` |
| Memory error in a pairwise computation | The `(n, n, d)` intermediate is too large | Chunk the work or use a specialized routine |
Summary of the pattern
Every example in this chapter follows the same recipe. Pick the result shape. Insert size-1 axes in the operands so that each axis of the result either comes from the operand or is stretched from size 1. Then let the elementwise operation do the loop. Reductions with keepdims=True give you the right-shaped operands for centering and scaling. Reshaping with np.newaxis gives you the right-shaped operands for grids and pairwise work.
Exercise
You have a matrix x of shape (5, 3) and want to divide each row by its own sum so that every row sums to 1. Write the expression, give the shape of the row sums that makes it work, and say what would go wrong without that shape.
Show answer
Use x / x.sum(axis=1, keepdims=True). The row sums have shape (5, 1), which broadcasts against (5, 3) by stretching across the columns. Without keepdims=True (or [:, np.newaxis]), the sums have shape (5,), which is compared with the trailing dimension 3 and raises a ValueError. If x had shape (3, 3), it would not raise an error. It would silently divide each column by the wrong sum.
Exercise
Given a of shape (4,) and b of shape (6,), write one expression that returns a (4, 6) array whose entry [i, j] is a[i] * b[j]. Then give the result shape of a[:, np.newaxis, np.newaxis] + np.zeros((3, 5)) and explain it.
Show answer
The first expression is a[:, np.newaxis] * b, which compares shapes (4, 1) and (6,) and gives (4, 6). For the second, the operand shapes are (4, 1, 1) and (3, 5). Aligning from the right gives (4, 1, 1) against (1, 3, 5), so the result has shape (4, 3, 5).
Exercise
For 1000 points in 3 dimensions stored as float64, how many bytes does the intermediate diff array use in the pairwise-distance code, and what is one way to avoid creating it?
Show answer
diff has shape (1000, 1000, 3), so 1000 1000 3 * 8 = 24,000,000 bytes, about 24 MB. To avoid it, process the points in chunks of rows so that only a (chunk, 1000, 3) array exists at a time, or call scipy.spatial.distance.cdist.