Sub topic 9
Broadcasting rules
Broadcasting is how NumPy combines arrays of different shapes in one elementwise operation. This chapter covers the rules that decide whether two shapes are compatible and what shape the result has. It assumes you know what shape and ndim mean, and that you have used elementwise operators such as + and * on arrays of the same shape.
Why broadcasting exists
Elementwise operations pair up entries at the same position. That is simple when both arrays have the same shape. In practice you often want to combine arrays of different shapes: add one number to every entry, or subtract a per-column offset from every row.
You could write a loop, or build a tiled copy of the smaller array by hand. Broadcasting lets NumPy do the equivalent without either. The smaller array behaves as if it were repeated along the missing or size-1 dimensions, but no repeated copy is built in memory.
import numpy as np
a = np.ones((3, 4))
print((a + 5).shape) # (3, 4)
print((a * np.arange(4)).shape) # (3, 4)The scalar 5 and the shape (4,) array both stretch to (3, 4).
The two rules
NumPy compares the shapes of two operands one dimension at a time, starting from the last (rightmost) dimension and moving left.
- Pad on the left. If one shape has fewer dimensions, treat it as if it had extra dimensions of size 1 added on its left, until both have the same
ndim. - Compare each pair. For each dimension, the two sizes must be equal, or one of them must be 1. If neither holds, the shapes are incompatible and NumPy raises
ValueError.
When the shapes are compatible, each result dimension is the larger of the two sizes. A size-1 dimension is stretched to match its partner.
A worked example
Take col with shape (3, 1) and row with shape (4,).
rowhas fewer dimensions, so pad it on the left. Its shape becomes(1, 4).- Compare the last dimensions: 1 and 4. One is 1, so the result size is 4.
- Compare the first dimensions: 3 and 1. One is 1, so the result size is 3.
- The result shape is
(3, 4).
import numpy as np
col = np.arange(3).reshape(3, 1) # shape (3, 1)
row = np.arange(4) # shape (4,)
grid = col + row
print(grid.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 column is stretched across the columns, and the row is stretched down the rows.
Checking shapes without computing
np.broadcast_shapes applies the rules to shapes alone, so you can test a combination without allocating any data. It is available in NumPy 1.20 and later.
import numpy as np
print(np.broadcast_shapes((3, 1), (4,))) # (3, 4)
print(np.broadcast_shapes((2, 1, 4), (3, 1))) # (2, 3, 4)
try:
np.broadcast_shapes((3, 4), (3,))
except ValueError as err:
print("incompatible:", err)More cases
The padding rule is why (2, 1, 4) and (3, 1) work together. Padding (3, 1) gives (1, 3, 1). Comparing from the right gives 4 and 1, then 1 and 3, then 2 and 1, so the result is (2, 3, 4).
| Shape A | Shape B | After padding | Result |
|---|---|---|---|
| `(3, 4)` | `(4,)` | `(3, 4)` and `(1, 4)` | `(3, 4)` |
| `(3, 4)` | `()` (scalar) | `(3, 4)` and `(1, 1)` | `(3, 4)` |
| `(5, 1)` | `(1, 6)` | unchanged | `(5, 6)` |
| `(2, 1, 4)` | `(3, 1)` | `(2, 1, 4)` and `(1, 3, 1)` | `(2, 3, 4)` |
| `(3, 4)` | `(3,)` | `(3, 4)` and `(1, 3)` | error: 4 vs 3 |
| `(3,)` | `(4,)` | unchanged | error: 3 vs 4 |
The error cases show the rule that surprises people most. Padding happens only on the left, so a vector of length 3 never lines up with the rows of a (3, 4) array. Its only possible partner is the last axis, which has length 4. How to repair that mismatch is the subject of the next chapter.
Broadcasting stretches without copying
A broadcast operand is not materialized as a bigger array. NumPy iterates over the small array with a stride of 0 along each stretched dimension, so it reads the same memory again and again. You can see this with np.broadcast_to, which returns the stretched array as a view.
import numpy as np
row = np.arange(4)
b = np.broadcast_to(row, (3, 4))
print(b.shape) # (3, 4)
print(b.strides[0]) # 0, moving down a row does not advance in memory
print(b.flags.writeable) # FalseThe view is read-only because many positions share one memory cell. Writing to one would change all of them. Call b.copy() if you need a real, writable (3, 4) array.
The result of col + row is a new array of the full result shape. The saving applies to the inputs, not the output.
Where the rules apply
Broadcasting is a property of universal functions, so it works across all of the following.
- Arithmetic operators:
+,-,*,/,**. - Comparison operators:
==,<,>=and the rest. - Functions such as
np.maximum,np.hypotandnp.where, which accept more than two operands.
With more than two operands, NumPy applies the same rules across all the shapes at once. np.broadcast_shapes accepts any number of shapes.
import numpy as np
print(np.broadcast_shapes((5, 1, 1), (1, 6, 1), (7,))) # (5, 6, 7)Edge cases
Size 0 and size 1
A dimension of size 1 stretches to match any partner, including 0. A dimension of size 0 only matches another 0 or a 1. This gives empty results rather than errors.
import numpy as np
print(np.broadcast_shapes((3, 0), (3, 1))) # (3, 0)
print(np.broadcast_shapes((1,), (0,))) # (0,)By contrast, (3,) with (0,) fails, because neither 3 nor 0 is 1.
In-place operators
The result shape is the broadcast shape of the inputs. For an in-place operation such as a += b, that result has to be stored back into a, so it must fit a's shape. In-place operations can broadcast b up to a, but they cannot grow a.
import numpy as np
a = np.ones((3, 4))
a += np.arange(4) # fine: the (4,) operand stretches to (3, 4)
small = np.ones(4)
try:
small += np.ones((3, 4)) # result would need shape (3, 4)
except ValueError:
print("in-place add failed")Scalars and zero-dimensional arrays
A Python number, or an array with shape (), has no dimensions. Padding gives it a 1 in every position, so it is compatible with any shape.
Equal sizes are not required to mean the same thing
The rules check only sizes. A (3, 3) array and a (3,) array broadcast without complaint, even if the 3 in the vector was meant to line up with the first axis. The rule pairs it with the last axis. The code runs and the result is wrong, and no error warns you. The pitfalls chapter covers how to catch these cases.
Summary of the procedure
- Write both shapes as tuples.
- Pad the shorter tuple with 1s on the left.
- Compare from the right. Each pair must be equal, or contain a 1.
- The result takes the larger size in each position.
- If any pair fails, expect a
ValueError.
Exercise
Without running code, give the result shape of broadcasting (8, 1, 6, 1) with (7, 1, 5). Then say whether (4, 3) and (4,) are compatible, and why.
Show answer
Pad (7, 1, 5) to (1, 7, 1, 5). Comparing from the right gives 1 and 5 → 5, then 6 and 1 → 6, then 1 and 7 → 7, then 8 and 1 → 8. The result shape is (8, 7, 6, 5). (4, 3) and (4,) are not compatible. The shape (4,) is padded to (1, 4), so its 4 is compared with the last axis of the other shape, which is 3. Neither is 1, so NumPy raises a ValueError.
Exercise
An image array img has shape (256, 256, 3), and gain has shape (3,), one value per color channel. Does img * gain work? What shape does it return? What about img * np.arange(256)?
Show answer
img * gain works. gain is padded to (1, 1, 3), the last axes match at 3, and the result shape is (256, 256, 3). img * np.arange(256) fails. The vector's length 256 is compared with the last axis of img, which is 3, and neither size is 1, so NumPy raises a ValueError. To scale along the first axis, give the vector shape (256, 1, 1).