Tensors, shapes and broadcasting
Images, audio, video and batches of series are arrays with more than two axes. Read a tensor's shape as a contract, know the common axis orders, and avoid the broadcasting bug that turns a column plus a row into a square table.
You will be able to
- Read a tensor shape and name what each axis means for tables, series, images, audio and video
- Apply the broadcasting rule and spot when it silently produces the wrong shape
- Explain why a shape, dtype and axis order are part of a data contract, and what masks are for
Read first
More than two axes
ReadA table is a matrix: rows × columns. Other data need more axes, and the array that holds them is a tensorTensorAn array with any number of axes, such as batch × channels × height × width. Its shape is part of the data contract.. Its shape lists the length of each axis.
| Data | Common shape | Axes |
|---|---|---|
| Table | rows, features | |
| Batch of series | batch, time steps, channels | |
| Batch of images | batch, color channels, height, width | |
| Audio clips | batch, microphones, samples | |
| Spectrograms | batch, frequency bins, frames | |
| Video | batch, frames, channels, height, width |
These are conventions, not laws: some libraries put channels last ().
The shape is a contract
ReadA model trained on images in the range 0 to 1 expects exactly that. Feed it channels-last arrays, or values from 0 to 255, and it will usually still run, and quietly produce nonsense.
So a data contract states more than column names: the shape, the axis order, the dtype ( or ), the units or value range, and how variable lengths are handled. Checking these at the boundary catches bugs that no error message will.
Broadcasting
ReadBroadcastingBroadcastingStretching a smaller array along missing or size-1 axes so element-wise math works, without copying it. lets arrays of different shapes meet in element-wise math. Line the shapes up from the right; each axis pair must be equal, or one of them must be 1 (or missing), and the 1 is stretched.
- : subtract a mean from every row. Intended.
- : scale each color channel. Intended.
- : becomes . Almost never intended.
The last one is the classic silent bug: predictions shaped minus targets shaped give an table, and its mean is a meaningless "error".
import numpy as np
pred = np.array([[1.0], [2.0], [3.0]]) # shape (3, 1)
y = np.array([1.0, 2.0, 4.0]) # shape (3,)
print((pred - y).shape) # (3, 3) -- the bug
print((pred.ravel() - y).shape) # (3,) -- intendedpred <- matrix(c(1, 2, 3), ncol = 1) # 3 x 1
y <- c(1, 2, 4)
dim(pred - y) # 3 x 1: R recycles by position instead
dim(outer(as.vector(pred), y, "-")) # 3 x 3 only if you ask for itR recycles shorter vectors along the existing shape rather than broadcasting new axes, so the same bug looks different in each language. Check shapes explicitly in both.
Masks for ragged data
ReadSentences, recordings and patient histories have different lengths, but a batch tensor needs one length. Pad the short ones to the longest, and carry a mask: a tensor of the same shape marking real entries 1 and padding 0.
Every later step must respect it: averages divide by the real count, attention ignores padded positions, and losses skip them. Forget the mask and padding counts as data.
Check: tensors
CheckpointCheck yourself
A batch tensor has shape in channels-first order. What is it?
Show the answer
Answer: a
Channels-first images are batch × channels × height × width.
Check yourself
In NumPy, what shape is an array of shape plus one of shape ?
Show the answer
Answer: b
Lined up from the right: against stretches to 4, and the missing axis against 5 stretches to 5.
Check yourself
Your mean squared error is suspiciously large. Predictions have shape and targets . What happened?
Show the answer
Answer: a
Flatten the predictions first, or assert both shapes match before subtracting.
Check yourself
You average a padded batch of sentence embeddings over the time axis without a mask. What goes wrong?
Show the answer
Answer: a
A mean over padded positions divides by the padded length, not the real one. Divide by the mask's sum instead.
Recap
Recap- A tensor's shape names its axes; tables, series, images, audio and video have common but not universal orders.
- Shape, axis order, dtype and value range belong in the data contract.
- Broadcasting stretches size-1 axes; check shapes so and never meet. Carry masks for padded data.
Concepts in this lesson