Skip to content

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.

Applied ~12 min6 steps

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

01

More than two axes

Read

A 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.

DataCommon shapeAxes
Tablen×dn \times drows, features
Batch of seriesB×T×CB \times T \times Cbatch, time steps, channels
Batch of imagesB×C×H×WB \times C \times H \times Wbatch, color channels, height, width
Audio clipsB×C×TB \times C \times Tbatch, microphones, samples
SpectrogramsB×F×TB \times F \times Tbatch, frequency bins, frames
VideoB×T×C×H×WB \times T \times C \times H \times Wbatch, frames, channels, height, width

These are conventions, not laws: some libraries put channels last (B×H×W×CB \times H \times W \times C).

02

The shape is a contract

Read

A model trained on B×3×224×224B \times 3 \times 224 \times 224 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 (float32\text{float32} or float64\text{float64}), the units or value range, and how variable lengths are handled. Checking these at the boundary catches bugs that no error message will.

03

Broadcasting

Read

BroadcastingBroadcastingStretching 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.

  • (n,d)−(d,)(n, d) - (d,): subtract a mean from every row. Intended.
  • (B,C,H,W)×(C,1,1)(B, C, H, W) \times (C, 1, 1): scale each color channel. Intended.
  • (n,1)+(n,)(n, 1) + (n,): becomes (n,n)(n, n). Almost never intended.

The last one is the classic silent bug: predictions shaped (n,1)(n, 1) minus targets shaped (n,)(n,) give an n×nn \times n table, and its mean is a meaningless "error".

Python
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,)    -- intended
R
pred <- 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 it

R 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.

04

Masks for ragged data

Read

Sentences, 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.

05

Check: tensors

Checkpoint

Check yourself

A batch tensor has shape (32,3,64,64)(32, 3, 64, 64) 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 (5,1)(5, 1) plus one of shape (4,)(4,)?

Show the answer

Answer: b

Lined up from the right: 11 against 44 stretches to 4, and the missing axis against 5 stretches to 5.

Check yourself

Your mean squared error is suspiciously large. Predictions have shape (n,1)(n, 1) and targets (n,)(n,). 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.

06

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 (n,1)(n,1) and (n,)(n,) never meet. Carry masks for padded data.

Concepts in this lesson