Command Palette

Search for a command to run...

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

Standardise features: the broadcasting step every ML pipeline has

Age and monthly spend sit on very different scales. Subtracting each column's mean and dividing by its standard deviation puts both on the same footing (a z-score). Both mean and std have shape (2,), so they broadcast over all rows. In a real project compute them on the training rows only.

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?

Standardise features: the broadcasting step every ML pipeline has
Sign in to run this example in your browser.

Expected output

mean per column: [  38.75 4425.  ]
std per column : [  10.6 2958.4]
[[-1.29 -1.09]
 [-0.63  0.33]
 [ 0.78 -0.72]
 [ 1.15  1.48]]
column means ~0: True
column stds   =1: True
shapes: (4, 2) (2,) (4, 2)