Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 14.3 — Vectorisation and Broadcasting
Python · Example 2 of 3

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.

01

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.

02

Make a 3-by-3 multiplication table from 1 to 3 using np.arange(1, 4) and broadcasting.

03

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

01

What is vectorisation and why is it faster than a Python loop?

02

State the broadcasting rule. Walk through (3, 1) plus (4,).

03

Why does np.ones((2, 3)) + np.ones((2,)) fail, and how do you fix it?

04

Where does broadcasting appear in a neural network layer?

Broadcasting in action
Sign in to run this example in your browser.

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)