Learn machine learning from scratch

Start at chapter 1 and build up: what a model is, how it measures its own mistakes, and how it learns. Everything is worked out in plain Python, with the maths shown rather than assumed. Two shorter tracks hold reference notes on the maths and on modern architectures.

Track Progress: 0 Completed
0%
Maths for MLLEVEL 2 · INTERMEDIATEModule 2 · Matrices

Tensors and broadcasting

A tensor is an array with any number of axes. Broadcasting combines arrays of different shapes by lining the shapes up from the right, and it is behind both neat code and silent bugs.

10 min Prerequisites: Lesson 11 (shapes)

1. The idea

A tensor, in ML code, is an array with any number of axes: a number has 0, a vector 1, a matrix 2, and a batch of colour images 4: (batch, channels, height, width). Its shape lists the size of each axis, and many bugs are a shape you didn't expect.

Broadcasting is how NumPy and PyTorch combine arrays of different shapes without copying anything. Line the two shapes up from the right. Going axis by axis, the sizes must be equal, or one of them must be 1 (it is stretched to match), or one array has run out of axes (it counts as size 1). If any pair breaks the rule, you get an error.

This is what lets X − mean work on a whole batch: a (32, 10) batch minus a (10,) vector of feature means subtracts the right mean from every row. It is also the source of silent bugs: a (32,) vector of targets minus a (32, 1) column of predictions broadcasts to (32, 32), and the loss is wrong without any error.

2. Try it: line the shapes up

Pick a pair of shapes. The table applies the rule axis by axis from the right; for small 2-D cases the picture shows which numbers are real and which are stretched copies.

Buttons choose a pair of array shapes, such as (3, 4) and (4,). A table lines the shapes up from the right and, for each axis, says whether the sizes are equal, whether one is stretched, or whether they clash, and gives the result. For small 2-D cases a grid shows B stretched to the result's shape, with its own entries solid and the copies faint.

3. The math

A batch of images is a 4-axis tensor
X∈RB×C×H×WX \in \mathbb{R}^{B \times C \times H \times W}
Batch, channels, height, width.
The rule, one axis at a time
(a,b) compatible  ⟺  a=b  or  a=1  or  b=1(a, b) \text{ compatible} \iff a = b \ \text{ or } \ a = 1 \ \text{ or } \ b = 1
Compared from the right; a missing axis counts as 1.
Centring a batch
xˉ=1n∑i=1nx(i)X−xˉ: (n×d)−(d)→(n×d)\bar{\mathbf{x}} = \frac{1}{n}\sum_{i=1}^{n}\mathbf{x}^{(i)} \qquad X - \bar{\mathbf{x}}:\ (n \times d) - (d) \to (n \times d)
The feature means are subtracted from every row.
A column plus a row
(3×1)+(1×4)→(3×4)(3 \times 1) + (1 \times 4) \to (3 \times 4)
Both are stretched: every entry of the column plus every entry of the row.

4. The code (python)

mm2_broadcast.py
import numpy as np

X = np.arange(12.0).reshape(3, 4)        # 3 examples, 4 features
mu = X.mean(axis=0)                      # one mean per feature, shape (4,)
print(mu.tolist())                       # [4.0, 5.0, 6.0, 7.0]
print((X - mu).shape)                    # (3, 4)
print((X - mu)[0].tolist())              # [-4.0, -4.0, -4.0, -4.0]

col = np.array([[0.0], [10.0], [20.0]])  # shape (3, 1)
row = np.array([1.0, 2.0, 3.0, 4.0])     # shape (4,)
print((col + row).shape)                 # (3, 4)

y = np.zeros(32)                         # targets, shape (32,)
y_hat = np.zeros((32, 1))                # predictions, shape (32, 1)
# a silent bug: no error, just the wrong shape
print((y - y_hat).shape)                 # (32, 32)

5. You’ll see this in

6. Check yourself

Answer all 4 questions correctly to complete the chapter · 0 / 4 done
Q1/4 What shape is (5, 3) + (3,)?
Q2/4 What happens with (4, 3) + (4,)?
Q3/4 What shape is (2, 1) + (1, 6)?
Q4/4 Why is y (shape (32,)) minus y_hat (shape (32, 1)) dangerous?

Finished this chapter?

Weekly newsletter

What changed in ML architectures this week

New models worth knowing, benchmark moves, and one architecture explained in plain words. Free, once a week, unsubscribe anytime.