Broadcasting in action
Change the second array's shape to (3,) and read the error message in the try block.
Vectorisation means writing one array expression instead of a Python loop. Broadcasting is the rule that lets arrays of different shapes combine, by stretching size-1 dimensions to match.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Given prices = np.array([[10.0, 20.0], [30.0, 40.0]]) and tax = np.array([1.05, 1.10]), apply a different tax to each column.
Make a 3-by-3 multiplication table from 1 to 3 using np.arange(1, 4) and broadcasting.
Normalise each row of m = np.array([[1.0, 3.0], [2.0, 2.0]]) so the row sums to 1, using keepdims=True.
Explain it without notes
What is vectorisation and why is it faster than a Python loop?
State the broadcasting rule. Walk through (3, 1) plus (4,).
Why does np.ones((2, 3)) + np.ones((2,)) fail, and how do you fix it?
Where does broadcasting appear in a neural network layer?
Expected output
m shape: (2, 3)
scale shape: (3,)
[[ 10. 200. 3000.]
[ 40. 500. 6000.]]
col shape: (2, 1)
[[2. 3. 4.]
[6. 7. 8.]]
[[11, 21], [12, 22], [13, 23]]
ValueError: operands could not be broadcast together with shapes (2,3) (2,)
fixed shape: (2, 3)