Sub topic 13
Broadcasting errors and pitfalls
This chapter assumes you know the broadcasting rules from the earlier chapters. NumPy compares shapes from the trailing axis backward, and two axes are compatible when they are equal or one of them is 1. It also assumes you are comfortable with np.newaxis, reshape and keepdims. Here you learn to read broadcasting failures, and to spot the more dangerous case where broadcasting succeeds and gives the wrong answer.
The two kinds of failure
Broadcasting goes wrong in two ways:
- Loud failure: the shapes are incompatible and NumPy raises
ValueError. This is annoying but safe. - Silent failure: the shapes happen to be compatible, NumPy returns a result, and the result is not the one you meant. This is the costly kind, because nothing tells you to look.
Most silent failures come from the same source. A 1-D array of shape (n,) and a column of shape (n, 1) are different objects, and mixing them produces an (n, n) result.
Loud failure: misaligned trailing axes
Alignment starts at the last axis, not the first. A vector of length 3 does not line up with the rows of a (3, 4) matrix, because its single axis is compared with the matrix's last axis, which has length 4.
import numpy as np
m = np.ones((3, 4))
v = np.arange(3)
try:
m + v
except ValueError as err:
print("error:", err)
print((m + v[:, np.newaxis]).shape) # (3, 4)The message begins operands could not be broadcast together with shapes (3,4) (3,). It names both shapes, which is the information you need. Compare them right to left. Here 4 meets 3, they are unequal, and neither is 1, so the operation fails.
The fix depends on your intent. To add v to each row you need a length-4 vector. To add v[i] to row i, you turn v into a column with v[:, np.newaxis], which has shape (3, 1).
To test shapes without building arrays, use np.broadcast_shapes:
import numpy as np
print(np.broadcast_shapes((3, 1), (4,))) # (3, 4)
print(np.broadcast_shapes((2, 1), (3,))) # (2, 3)
try:
np.broadcast_shapes((3, 4), (3,))
except ValueError:
print("incompatible")Quick reference for shape pairs
| Shape A | Shape B | Result |
|---|---|---|
| `(3, 4)` | `(4,)` | `(3, 4)` |
| `(3, 4)` | `(3,)` | error |
| `(3,)` | `(3, 1)` | `(3, 3)` silently |
| `(3, 1)` | `(1, 4)` | `(3, 4)` |
| `(2, 3, 4)` | `(3, 1)` | `(2, 3, 4)` |
| `(5,)` | `(0,)` | error |
| `(1,)` | `(0,)` | `(0,)` silently empty |
The (3,) with (3, 1) row is the one to remember. It is legal and never raises an error.
Silent failure: the accidental outer operation
This case appears constantly in machine-learning code. Predictions come out of a model as a column, labels are stored as a flat array, and the error is computed by subtraction.
import numpy as np
y = np.array([1.0, 2.0, 3.0]) # shape (3,)
pred = np.array([[1.0], [2.0], [4.0]]) # shape (3, 1)
err = pred - y
print(err.shape) # (3, 3)
print(err)
# [[ 0. -1. -2.]
# [ 1. 0. -1.]
# [ 3. 2. 1.]]
print(round(float((err ** 2).mean()), 3)) # 2.333, wrong
print(round(float(((pred[:, 0] - y) ** 2).mean()), 3)) # 0.333, correctThe wrong version compares every prediction with every label. The shape is (3, 3), the mean is over 9 numbers instead of 3, and the code never fails. The result is a plausible-looking but wrong loss value.
Ways to prevent it:
- Pick one convention for 1-D data, such as always flat
(n,), and convert at the boundary withravel()orreshape(-1). - Check shapes right after the operation that could go wrong.
- Use
assert err.shape == y.shapein code where the shape matters.
Silent failure: reductions that drop the axis
A reduction removes the axis it reduces over. If you then combine the result with the original array, the remaining axis is compared with the last axis of the original, which is a different axis than you intended. For a non-square array the mismatch raises an error. For a square array it does not.
import numpy as np
x = np.arange(9.0).reshape(3, 3)
wrong = x - x.mean(axis=1) # mean has shape (3,)
right = x - x.mean(axis=1, keepdims=True) # mean has shape (3, 1)
print(wrong.sum(axis=1)) # [-9. 0. 9.]
print(right.sum(axis=1)) # [0. 0. 0.]In wrong, the row means [1, 4, 7] are subtracted down the columns, so each column gets a different offset. A correct row-centering has row sums of zero. That makes a good check: after centering, the mean along the centered axis should be near zero.
If the array were (2, 3), the wrong version would raise an error because 3 and 2 do not match. This is why a bug can survive in tests that use square arrays and fail only on real data. Test with non-square shapes, and with different sizes on every axis, such as (2, 3, 5).
In-place operations cannot grow
Operators like += write the result back into the left operand. The left operand keeps its shape, so the broadcast result must fit it.
import numpy as np
a = np.zeros((3, 1))
b = np.arange(4)
try:
a += b
except ValueError as err:
print("error:", err)
print((a + b).shape) # (3, 4)The error reads non-broadcastable output operand with shape (3,1) doesn't match the broadcast shape (3,4). The plain a + b works because it allocates a new array of the larger shape. The reverse case is fine: if a is (3, 4) and b is (4,), then a += b works, because the result already has a's shape.
In-place addition also checks dtypes. Adding a float array into an integer array with += raises a UFuncTypeError instead of silently truncating.
Size 1 and size 0 axes
A size-1 axis stretches to any length, including 0. That means (1,) combined with (0,) gives an empty (0,) result, with no warning. Empty results usually come from an earlier filtering step. If a later computation yields an empty array or nan, check whether an earlier mask or slice selected nothing.
A size-0 axis does not stretch. Only 1 does. A (5,) array and a (0,) array raise an error.
Memory is part of the pitfall
Broadcasting avoids copying the smaller operand. The result, though, is a full array of the broadcast shape. Pairwise computations make this large quickly. Subtracting a (n, 1) column from a (1, n) row creates n * n values. For n = 100_000 that is 10 billion float64 values, about 80 GB. An accidental (n,) versus (n, 1) mix on a large dataset can exhaust memory instead of raising a shape error. The pairwise-distance example with shape (n, n, d) is worse, since it also multiplies by d. Chapter on vectorization and memory cost covers mitigations such as chunking.
A debugging routine
When a broadcast result looks wrong or an error appears, work through the same sequence each time.
Practical habits that support this routine:
- Print
.shapeof every operand before the line that fails, not just the result. - Write the intended result shape in a comment next to the line, as the examples in this tutorial do.
- Use
keepdims=Truewhenever a reduction result is combined back with its source array. - Use small arrays with distinct axis lengths, such as
(2, 3, 4), so that mix-ups raise errors instead of hiding. - Add
assert result.shape == expectedat the boundaries of reusable functions.
Exercise
A model returns pred with shape (1000, 1), and the labels are y with shape (1000,). A colleague writes loss = ((pred - y) ** 2).mean() and gets no error. What shape does pred - y have, why does it not raise an error, and how do you fix the line?
Show answer
The result has shape (1000, 1000). Right-aligned, (1000, 1) and (1000,) compare as 1 versus 1000 on the last axis, which is allowed because one is 1, and 1000 versus a missing axis on the first, which is also allowed. Every prediction is compared with every label, so the mean is over a million values and is wrong. Fix it by making the shapes match: ((pred[:, 0] - y) ** 2).mean(), ((pred.ravel() - y) ** 2).mean(), or ((pred - y[:, np.newaxis]) ** 2).mean().
Exercise
You have x of shape (4, 4) and want to scale each row to sum to 1. You write x / x.sum(axis=1). It runs without error. Is it correct? What would happen for shape (4, 5), and what is the correct expression?
Show answer
It is not correct. x.sum(axis=1) has shape (4,), which broadcasts along the last axis, so column j is divided by the sum of row j. For shape (4, 5), the sum has shape (4,) and the last axis of x has length 5, so NumPy raises a ValueError. The correct expression is x / x.sum(axis=1, keepdims=True), where the sum has shape (4, 1).