Sub topic 13
Broadcasting errors and pitfalls
This chapter assumes you know the broadcasting rules, np.newaxis, and keepdims from the earlier chapters. It covers the two ways broadcasting goes wrong. It can raise an error, or it can succeed and return a result you did not intend.
The rule that decides compatibility
NumPy compares two shapes from the last dimension backward. Each pair of dimensions must be equal, or one of them must be 1. A missing leading dimension counts as 1. If any pair fails, NumPy raises a ValueError.
Loud failures: shape mismatch
Here a (3, 4) matrix meets a (3,) vector. The trailing pair is 4 and 3, so the shapes do not align, even though the vector matches the matrix's first axis.
import numpy as np
m = np.ones((3, 4))
v = np.arange(3)
try:
m + v # shapes (3, 4) and (3,) do not align
except ValueError as err:
print('error:', err)
print((m + v[:, np.newaxis]).shape) # (3, 4)Adding an axis turns v into shape (3, 1). Its trailing dimension of 1 then stretches across the 4 columns.
The error message lists both shapes. Read them right to left and find the first pair that disagrees.
Silent failures: the unintended outer result
The worse case is when broadcasting succeeds with the wrong meaning. A (3,) array and a (3, 1) array are compatible, and the result is (3, 3), not (3,).
import numpy as np
pred = np.array([1.0, 2.0, 3.0]) # shape (3,)
actual = np.array([[1.0], [2.0], [4.0]]) # shape (3, 1), for example read from a file
err = pred - actual
print(err.shape) # (3, 3), not (3,)
print(np.abs(err).mean())This returns a number, not an error. It averages all nine pairwise differences instead of the three matching ones. Check shapes before any subtraction or comparison between arrays that should line up one to one.
A similar trap appears with reductions on square arrays. If you forget keepdims=True, a non-square array raises an error. A square array does not.
import numpy as np
x = np.arange(9.0).reshape(3, 3)
rowsum = x.sum(axis=1) # shape (3,)
wrong = x - rowsum # subtracts rowsum[j] from column j
right = x - x.sum(axis=1, keepdims=True) # subtracts rowsum[i] from row i
print(wrong[0]) # [-3. -11. -19.]
print(right[0]) # [-3. -2. -1.]With a (2, 3) array the same mistake raises an error, which is the better outcome. Square test data can hide the bug until real data arrives.
Defensive habits
- Print
.shapefor each operand when a result looks off. - Keep vectors explicitly as
(n,)or(n, 1)and do not mix them. Convert withreshape(-1, 1)or[:, np.newaxis]. - Use
keepdims=Truefor any reduction whose result you plan to broadcast back. - Test with non-square shapes such as
(2, 3)or(3, 5). Mismatches then raise errors instead of passing quietly. - Use
assert a.shape == b.shapewhere you expect an exact match.
Exercise
Do shapes (5, 1, 3) and (4, 1) broadcast? If so, what is the result shape? Which pair of dimensions would fail if the second shape were (4, 2)?
Show answer
Align on the right: (5, 1, 3) and (_, 4, 1) with the missing dimension treated as 1. Pairs from the right are 3 and 1 (ok, gives 3), 1 and 4 (ok, gives 4), and 5 and 1 (ok, gives 5). The result shape is (5, 4, 3). With (4, 2), the trailing pair 3 and 2 is neither equal nor 1, so it raises a ValueError.