[concept]NumPy Foundations
Broadcasting
# theory
broadcasting
Broadcasting is the rule that lets arrays of different shapes line up. When the shapes match (or one is 1 in a dimension), NumPy stretches the smaller one to fit. No data is copied.
the rule
Two shapes are compatible if, working right-to-left, each pair of dimensions is either equal or one of them is 1.
(3, 4) and (4,) -> compatible, becomes (3, 4)
(3, 4) and (3, 1) -> compatible, becomes (3, 4)
(3, 4) and (3,) -> NOT compatible, ValueError
broadcasting gone wrong
If your shapes happen to be compatible but you didn't mean them to be, the math runs anyway. Always check shape on both operands before you trust the result.
# examples [3]
The simplest case: one number applied to a whole array.
Shape (3,) lines up with the last dimension of shape (4, 3). Each row gets the same vector added.
The most common bug: forgetting to reshape a vector. NumPy will tell you, but the error wording is dense.
# challenges [2]