If you read machine-learning code, you'll see arrays of different shapes being added and multiplied without a single loop. That's broadcasting, and once you know its one rule, a lot of ML code becomes readable.
The rule
NumPy compares shapes from the right. Two dimensions are compatible if they are equal, or if one of them is 1. A dimension of size 1 is stretched to match the other.
import numpy as np
a = np.ones((4, 3)) # 4 rows, 3 columns
b = np.array([10, 20, 30]) # shape (3,)
print((a + b).shape) # (4, 3): b is added to every rowShapes (4, 3) and (3,) line up on the right as 3 and 3; the missing dimension on the left is treated as 1.
Example 1: normalising features
X = np.random.rand(1000, 5) # 1000 samples, 5 features
mean = X.mean(axis=0) # shape (5,)
std = X.std(axis=0) # shape (5,)
X_norm = (X - mean) / std # (1000, 5) - (5,) -> works per featureExample 2: per-sample operations need keepdims
logits = np.random.randn(32, 10) # batch of 32, 10 classes
m = logits.max(axis=1, keepdims=True) # shape (32, 1), not (32,)
probs = np.exp(logits - m)
probs /= probs.sum(axis=1, keepdims=True)Without keepdims=True, m would have shape (32,), which lines up against the 10 classes on the right — an error, or worse, a silent bug when the sizes happen to match.
Example 3: all pairwise distances, no loop
points = np.random.rand(100, 2)
diff = points[:, None, :] - points[None, :, :] # (100,1,2) - (1,100,2) -> (100,100,2)
dist = np.sqrt((diff ** 2).sum(axis=-1)) # (100, 100)Inserting axes with None is how you ask broadcasting to build every combination.
Debugging tips
- Print
.shapeat every step until it becomes a habit. - Use
keepdims=Truewhenever you reduce and then combine with the original array. - If a result has an unexpected extra dimension, you probably broadcast a
(n,)against an(n, 1).
The same rules apply in PyTorch and JAX, so this knowledge transfers directly.
Takeaways
- Compare shapes from the right; sizes must match or be 1.
keepdims=TrueandNoneare your two main tools.- Most shape bugs are broadcasting doing exactly what you asked.