Broadcasting
Quick answer
Broadcasting lets elementwise operations work with arrays whose shapes differ in compatible ways. Compare dimensions from the right: equal lengths or a length of one are compatible; missing leading dimensions act like one. An axis of length one expands logically. For a feature matrix (n, d), a vector (d,) adjusts each feature across all samples.
Apply a calibration offset per feature
Each row contains two measurements. Subtract a length-two vector of feature offsets from every row. No manual Python loop is needed.
import numpy as npx = np.array([[10, 3], [12, 5], [14, 7]])offsets = np.array([10, 3])print((x - offsets).tolist())print((x - offsets).shape)Expected output (local NumPy 2.3.5):
[[0, 0], [2, 2], [4, 4]](3, 2)The trailing dimensions match at two; the offset has an implicit leading dimension of one. The result has three rows and two columns.
Distinguish row and column adjustments
Use [:, None] to insert an axis of length one so three sample offsets align with rows. Broadcasting also supports outer operations, such as adding a column of three values to a row of two values.
import numpy as npx = np.array([[10, 20], [30, 40], [50, 60]])row_offsets = np.array([1, 2, 3])[:, None]print((x - row_offsets).tolist())try: x - np.array([1, 2, 3])except ValueError: print('incompatible shapes')Expected output (local NumPy 2.3.5):
[[9, 19], [28, 38], [47, 57]]incompatible shapesThe column-shaped offsets subtract the same amount from each feature of a sample. The bare length-three vector conflicts with the trailing feature dimension of two.
Common mistakes
If the number of samples equals the number of features, a wrong axis can silently produce plausible values. Always check shapes and semantic meaning. Broadcasting does not require copying each input value, but the output can still be huge: (n, 1) plus (1, m) creates n*m elements. For a zero-length axis paired with length one, the output axis remains zero; using max blindly is incorrect.
Practice and next steps
For a (4, 3) feature matrix, predict the output when adding shapes (3,), (4, 1) and (4,). Explain why one is invalid. Next, summarize features with reductions.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Broadcasting — knowledge check
Apply array reasoning to new synthetic feature tables.
Which vector can subtract feature offsets from a (7, 3) matrix?
What is the result shape of (4, 1) + (1, 3)?
What happens when shapes (4, 3) and (4,) are added?
Why is adding shape (3,) to a square (3, 3) table risky for row offsets?
What is the output shape of (0, 3) + (1, 3)?