Tensors and shapes: axes, shape and broadcasting

Deep learning code is full of shapes like "(N, C, H, W)" that nobody explains. Here we follow, one axis at a time, what a tensor is, what a shape tells you, how shapes change, and how two tensors with different shapes are added.

Short answer. A tensor is numbers stacked along several axes (directions in which numbers line up), and its shape lists how many numbers there are along each axis. A scalar has 0 axes, a vector 1, a matrix 2. The element count is the product of the shape, and summing along one axis removes that axis from the shape. Two tensors with different shapes are combined by broadcasting: compare the shapes from the last axis, and an axis fits when the sizes are equal or one of them is 1, which then stretches.

The table at the top lines the two shapes up on their right ends, and the orange box is the axis being compared. The picture below draws only the last two axes as cells. A's cells hold made-up values 1, 2, 3 …, and B's hold 10, 20, 30 …. Dashed cells are copies made by stretching an axis of size 1. At most 6 cells are drawn per axis, and numbers are shown only when the results have two digits. You can also type shapes into the boxes (1 to 5 axes, sizes 1 to 999).

Try this. 1) As it starts, (3, 1) + (1, 4), press "Next" three times. The last axis is 1 and 4, so A stretches to 4. The axis before it is 3 and 1, so B stretches to 3. The result is (3, 4) with 12 elements, and the cells hold 11 to 43. 2) (8, 1, 6, 1) + (7, 1, 5) gives (8, 7, 6, 5) with 1,680 elements after four comparisons. B has no fourth axis, so it counts as 1. 3) (4, 3) + (4,) stops at the first comparison (3 and 4). 4) (4,) + (4, 1) gives (4, 4) with no error (section 6).

Definitions

On this page a tensor means what deep learning libraries mean: an array of numbers laid out along several axes (section 7). The definitions below use that meaning.

tensor
For a whole number n ≥ 0 and positive whole numbers d₀, …, dₙ₋₁, an array that holds one element for each index tuple (i₀, …, iₙ₋₁) with 0 ≤ iₖ < dₖ. If the elements are real numbers, it is written as below. n = 0 gives a scalar, n = 1 a vector, and n = 2 a matrix. All elements of one tensor have the same data type.

T∈ℝd0×d1×⋯×dn−1,T[i0,i1,…,in−1]∈ℝ

axis
One position in the index tuple (i₀, …, iₙ₋₁) of an element. From the front they are called axis 0, axis 1, …, axis n − 1. The number of values the index iₖ can take, dₖ, is called the size of axis k.
shape
The list of axis sizes, written in order from axis 0. The number of elements is the product of all axis sizes. A scalar has the empty shape () and 1 element.

(d0,d1,…,dn−1),number of elements=d0×d1×⋯×dn−1

number of dimensions
The number of axes, n (ndim in NumPy). Some documents call it the rank, but that is not the same as the rank of a matrix (the largest number of linearly independent columns).
broadcasting
The rule that lines up the shapes when you compute element by element with two tensors of different shapes. Line the two shapes up at the last axis, and fill the front of the shorter one with axes of size 1 so both have the same number of axes. Call them (a₀, …, aₙ₋₁) and (b₀, …, bₙ₋₁). The computation works only if the condition below holds for every k, and the result has shape (c₀, …, cₙ₋₁). Elements along an axis of size 1 are reused along that axis.

ck=max(ak,bk),ak=bk or ak=1 or bk=1

1. What a tensor is: numbers stacked along several axes

One number is a scalar. Numbers in a line make a vector, and numbers in rows and columns make a matrix. You can stack several matrices, and stack those stacks again. Each direction in which numbers line up is an axis, and whatever the number of axes, the whole thing is called a tensor. Axes are numbered 0, 1, 2 … from the front.

The shape lists how many numbers line up along each axis, starting from axis 0. A matrix with 2 rows and 3 columns has shape (2, 3). A vector with 4 elements is written (4,) (the comma marks a single axis), and a scalar has no axes, so its shape is ().

scalarvectormatrixtensor (3 axes) 7 3141 123 456 789 101112 axis 0 axis 0axis 1 axis 0axis 1axis 2 ()(4,)(2, 3)(2, 2, 3) 0 axes1 axis2 axes3 axes
The shape is written from axis 0. The tensor on the right stacks two 2 × 3 matrices (green 1 to 6 at the back, blue 7 to 12 in front), so axis 0 has size 2. It has 2 × 2 × 3 = 12 elements.

The number of axes is the number of dimensions (ndim in NumPy). Some documents call it the rank, which is not the same as the rank of a matrix (the number of independent columns). A matrix of shape (2, 3) always has 2 axes, but its matrix rank can be 1 or 2 depending on the values.

All elements of one tensor share one data type (dtype). The PyTorch documentation describes torch.Tensor as "a multi-dimensional matrix containing elements of a single data type", and says the data type is set when the tensor is made and changed with to().

2. Shapes of real data

DataShapeWhat the axes mean
One grayscale image(H, W)Height H (rows) and width W (columns). One brightness per cell
One color image(H, W, 3) or (3, H, W)Three values per cell: red, green, blue. This axis is called the channel axis
A batch of images(N, C, H, W)N images at once. C is the channel count (3 for color, 1 for grayscale)
Embeddings of a batch of sentences(B, T, D)B sentences, T tokens per sentence, an embedding vector of D numbers per token

For example, a batch of 64 grayscale images of 28 × 28 is (64, 1, 28, 28), with 64 × 1 × 28 × 28 = 50,176 elements. A convolution layer takes image batches like this, and attention works between tokens on (B, T, D).

Whether the channel axis comes first (channels-first, (C, H, W)) or last (channels-last, (H, W, C)) differs between libraries and data formats. Check the documentation of the library you use. Section 3 shows how to switch.

3. Element count, reshape and transpose

element count = d₀ × d₁ × … × dₙ₋₁

reshape keeps the elements in the order you get by reading them out in a line (the last axis index changes fastest) and only splits that line into new axes. So the element count must stay the same. (2, 3) can become (3, 2), (6,) or (1, 6), but not (4, 2) (6 ≠ 8).

Transpose reorders the axes. For a matrix, rows and columns swap. With three or more axes you write the new order yourself (transpose in NumPy, permute in PyTorch). From the same (2, 3), both can give shape (3, 2), but the elements end up in different places.

a  (2, 3)      a.reshape(3, 2)      a.T  (transpose, (3, 2))
1 2 3          1 2                  1 4
4 5 6          3 4                  2 5
               5 6                  3 6

reshape cut 1, 2, 3, 4, 5, 6 into pairs in reading order. Transpose stood the columns up as rows. To turn an image (H, W, 3) into (3, H, W), use transpose(2, 0, 1), which reorders the axes. reshape(3, H, W) gives the same shape but mixes up the red, green and blue values.

import numpy as np

a = np.arange(1, 7).reshape(2, 3)   # [[1 2 3] [4 5 6]]
print(a.shape, a.ndim, a.size)      # (2, 3) 2 6
print(a.reshape(3, 2))              # [[1 2] [3 4] [5 6]]
print(a.T)                          # [[1 4] [2 5] [3 6]]
img = np.zeros((32, 48, 3))         # (H, W, 3)
print(img.transpose(2, 0, 1).shape) # (3, 32, 48): reorders the axes

4. Reducing along an axis: sum and mean

When you take a sum or mean "along axis k", the elements that differ only in their axis k index collapse into one value. So axis k drops out of the shape. This kind of calculation is called a reduction.

shape (d₀, …, dₖ, …, dₙ₋₁)   ── sum along axis k ──▶   (d₀, …, dₖ₋₁, dₖ₊₁, …, dₙ₋₁)

The tensor is made up: 1 to 24 stacked into shape (2, 3, 4). Cells of the same color collapse into the one cell of that color in the result on the right. The orange ring marks the cells that go into the first result cell.

Try this. 1) Axis 0, sum: the same positions of the two sheets collapse, giving (3, 4), and the first cell is 1 + 13 = 14. 2) Axis 1, sum: each sheet's columns of 3 cells collapse, giving (2, 4), and the first cell is 1 + 5 + 9 = 15. 3) Axis 2, mean: each sheet's rows of 4 cells collapse, giving (2, 3), and the first cell is (1 + 2 + 3 + 4) ÷ 4 = 2.5. Whichever axis you sum along, the result cells add up to 300.

This is also what separates batch norm and layer norm. In (N, D), with one data item per row and one feature per column, batch norm averages along axis 0 (the batch), one mean per feature, giving shape (D,). Layer norm averages along axis 1 (the features), one mean per item, giving shape (N,).

5. Broadcasting: computing with two different shapes

To add or multiply two tensors with different shapes, the shapes have to be made to fit. The rule in the NumPy documentation is this.

  1. Compare the two shapes one axis at a time, starting from the last (rightmost) axis.
  2. Two sizes fit when they are equal, or one of them is 1. The side with size 1 stretches as if its values were repeated to match the other size.
  3. The shapes may have different numbers of axes. An axis missing from one side counts as size 1.
  4. Each axis of the result takes the larger of the two sizes. If any axis does not fit, you get ValueError: operands could not be broadcast together.
result axis size = max(a, b)     (when a = b, or a = 1, or b = 1. Otherwise an error)

Work it out by hand.

  1. (3, 1) + (1, 4). Last axis 1 and 4 → 4. The axis before, 3 and 1 → 3. Result (3, 4). A's column [1, 2, 3] is repeated four times to the right and B's row [10, 20, 30, 40] three times downward, and the sums are 11 to 43.
  2. (256, 256, 3) × (3,). The last axes are 3 and 3, equal. B has no first two axes, so they count as 1. Result (256, 256, 3). Each cell of a color image gets its red, green and blue multiplied by three different numbers.
  3. (4, 3) + (4,). The last axes, 3 and 4, are not equal and neither is 1. It fails at the first comparison.
print((np.ones((3, 1)) + np.ones((1, 4))).shape)     # (3, 4)
print((np.ones((256, 256, 3)) * np.ones(3)).shape)   # (256, 256, 3)
np.ones((4, 3)) + np.ones(4)                         # ValueError: operands could not be broadcast together ...

6. Common mistakes

  1. The shapes fit but the meaning is wrong. Adding (4,) and (4, 1) gives (4, 4) with no error. The last axes are 4 and 1, and the axis before is missing from (4,), so it counts as 1. If you wanted (4,), four elements added pairwise, you got a wrong answer with no error. The last button of experiment 1 shows the steps.
  2. A reduced axis disappears and things stop lining up. In (N, D) data, to subtract each item's mean (axis 1) you might write x - x.mean(axis=1). The mean has shape (N,), so the last axis compares D with N. If N ≠ D you get an error. If N = D, it runs with no error and subtracts the wrong values. Keep the mean as (N, 1) (keepdims=True, or reshape(N, 1)) and the axes line up.
  3. Mixing up the axis order. If you use reshape to reorder axes, the element count matches, so it passes with no error and only the values get scrambled. Reorder axes with transpose (transpose, permute), and write the shapes in your code as comments.

7. How this relates to tensors in math and physics

In math and physics, a tensor is a quantity whose components change by fixed rules when you change the coordinate system. Its components can be written as an array with several axes, but not every array is such a tensor. Deep learning libraries ignore those rules and use the word tensor to mean "an array of numbers stacked along several axes". This page uses only that meaning.

8. What to use when

OptionGoodBadUse it when
reshapeKeeps the element order and only splits it into new axesUsed to reorder axes, it makes the shape fit and scrambles the valuesFlattening or splitting axes: (N, C, H, W) → (N, C × H × W)
Transpose (transpose, permute)Reorders axes and keeps what each axis meansWith many axes it is easy to lose track of which index is whichMoving channels to the front or back, like (H, W, 3) ↔ (3, H, W)
Sum or mean along an axisSums up one axis into a single valueThat axis drops out of the shape, so later steps can stop lining up (section 6)Batch means, token means, the means in normalization
Adding a size-1 axis ((4,) → (4, 1), keepdims=True)Makes clear which way broadcasting will stretchEasy to forget, and forgetting may not raise an errorSubtracting or adding a different value per row or per column
BroadcastingComputes with tensors of different shapes without loops or copying code by handIf the shapes happen to fit, a wrong calculation runs with no errorMultiplying each channel by a different number, adding the same vector to every item

Where it is used

Questions people ask

Is a tensor different from a NumPy array?

In the sense used on this page (elements of one data type stacked along several axes), they are the same thing. Each library adds its own features and function names, so check rules like broadcasting in the documentation of the library you use. The rules on this page were checked against the NumPy documentation.

The word "dimension" confuses me.

A vector with 4 elements is called a "4-dimensional vector" and also a "1-dimensional array" of shape (4,). The first dimension is the number of elements (the dimension of the vector space). The second is the number of axes. Writing the shape removes the confusion.

Should I use (N, C, H, W) or (N, H, W, C)?

Use the order that your library and model expect, and check it in their documentation. If you need to switch, reorder the axes with transpose (permute). reshape only makes the shape fit and scrambles the values.

Words

Words used hereWhat books call it
numbers stacked along several axestensor, n-dimensional array
a direction in which numbers line upaxis
the list of sizes, one per axisshape
the number of axesnumber of dimensions (ndim), rank. Not the rank of a matrix
one number · a line · rows and columnsscalar · vector · matrix
the number in one cell · how many there areelement · size
the axis of color values per cellchannel, channels-first · channels-last
several data items fed at oncebatch
splitting into new axes · reordering axesreshape · transpose, permute
summing or averaging along an axisreduction
computing with tensors of different shapesbroadcasting
the kind of element (integer, float …)data type, dtype

Sources

← Singular value decompositionFunctions and graphs →