Vectorization & broadcasting
Step 2 of 18 in Foundations · Build · Easy
Replace Python loops with whole-array operations; NumPy runs the loop in C. Broadcasting stretches smaller arrays to match bigger ones so you can, for example, compute every pairwise distance in one line.
The lesson
A Python loop handles one number at a time, through the interpreter. An array expression such as (A ** 2).sum() hands the whole loop to compiled C. Same answer, often 50 to 100 times faster. If you are writing for i in range(len(a)) over an array, there is almost always an array expression that replaces it.
Broadcasting is what happens when two shapes differ. NumPy lines the shapes up from the right. Two axes are compatible when they are equal or one of them is 1, and the 1 is stretched to match. Missing leading axes count as 1.
- Line them up from the right:
(3, 1)and(1, 4). - Last axis: 1 against 4, so stretch to 4. First axis: 3 against 1, so stretch to 3.
- The result has shape
(3, 4): every pairing of the two inputs.
rows = np.arange(1, 4)[:, None] # shape (3, 1): a column
cols = np.arange(1, 5)[None, :] # shape (1, 4): a row
rows * cols # shape (3, 4): a multiplication table, no loop
X = np.random.rand(100, 3)
X - X.mean(axis=0) # (100, 3) - (3,): centre every columnIndexing with None adds an axis of length 1, which is how you set up a broadcast on purpose. The pairwise-distance problem uses the same move one dimension up.
Common mistake. Shapes (n,) and (n, 1) do not raise an error when combined. They broadcast to (n, n). Subtracting (n, 1) predictions from (n,) labels gives a loss over an n × n matrix, and nothing warns you.
Check yourself
What is the shape of an array of shape (4, 3) plus one of shape (3,)?
- Error: the shapes do not match
- (3, 4)
- (4, 3)
Show the answer
(4, 3). From the right: 3 matches 3. The missing leading axis counts as 1 and stretches to 4. Result (4, 3): the row is added to every row.
And shape (4, 3) plus shape (4,)?
- Error: the shapes do not match
- (4, 3)
- (4, 4)
Show the answer
Error: the shapes do not match. From the right: 3 against 4. They are not equal and neither is 1, so NumPy raises. You would need the second array as (4, 1).
y has shape (100,) and pred has shape (100, 1). How many elements are in y - pred?
Show the answer
10000. (100,) lines up as (1, 100) against (100, 1). Both stretch, giving (100, 100): 10,000 elements instead of the 100 you meant.
Build it
Loop vs vector race
Write sum_of_squares(A) for a 1000×1000 array with two for-loops and with one NumPy expression. Time both.
Done when: Same result (np.isclose) and the NumPy version is at least 50× faster.
Runs in your browser: write the code on the map and the tests mark it.
Pairwise distances
pairwise(X, Y) returns D[i,j] = distance between X[i] and Y[j] using X[:, None, :] - Y[None, :, :]. No loops.
Done when: Matches scipy.spatial.distance.cdist to 1e-6.
Runs in your browser: write the code on the map and the tests mark it.
Resources
- Wikipedia: Array programming Article
- NumPy: absolute beginners Article
- Kaggle Learn: Python Course
Earn this star
On the map, your answers are marked and you log what you built. Finish the step and its star lights.
Open this step on the map