Tensors: Shapes and Types

Everything a neural network reads, computes and learns is held as numbers in grids called tensors: an image, the answer it should give, the adjustable numbers inside the model. Before a network can be trained, you need to read three things about any tensor: how its numbers are arranged, what kind of numbers they are, and how to reach the ones you want. Most errors in deep learning code come down to one of these three.

A tensor is a grid of numbers

A Python list can hold a row of numbers, and a list of lists can hold a table. A tensor is the same idea made into one object that PyTorch can compute with quickly: a grid of numbers, all of one type, with any number of dimensions. A dimension is one direction you can move along in the grid.

  • A single number has 0 dimensions: there is nowhere to move.
  • A row of numbers has 1 dimension: you move along it.
  • A table has 2 dimensions: rows down, columns across.
  • A stack of tables has 3 dimensions: which table, then which row, then which column.

Nothing stops at three. A collection of colour images, for example, is a stack of stacks, and has four dimensions. The rules on this page work the same way for any number of them.

0 dimensions: one number
  1. 7
1 dimension: a row
  1. 3
  2. 1
  3. 4
  4. 1
2 dimensions: a table
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
3 dimensions: table 0 of a stack
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
table 1 of the same stack
  1. 7
  2. 8
  3. 9
  4. 10
  5. 11
  6. 12

You build a tensor from Python data with torch.tensor, which copies the numbers into a new tensor. Nested lists give the dimensions: one level of brackets for a row, two for a table, three for a stack of tables.

import torch

one_number = torch.tensor(7)
row = torch.tensor([3, 1, 4, 1])
table = torch.tensor([[1, 2, 3],
                      [4, 5, 6]])
stack = torch.tensor([[[1, 2, 3], [4, 5, 6]],
                      [[7, 8, 9], [10, 11, 12]]])

print(one_number)   # tensor(7)
print(row)          # tensor([3, 1, 4, 1])

Tensors are created in the computer's main memory and computed on by its CPU unless you move them elsewhere. A graphics card (GPU) can make large computations faster, but everything on this page runs on an ordinary laptop.

True or false?

One tensor can hold whole numbers in some positions and decimal numbers in others, like a Python list can.

False. Every element of a tensor has the same type. A list may mix types; a tensor never does.

A single number stored with torch.tensor(7) is a tensor with zero dimensions.

True. It has no direction to move along, so it has no dimensions, but it is still a tensor and prints as tensor(7).

Shape: the size along each dimension

The shape of a tensor lists how many positions it has along each dimension, read from left to right, the outermost dimension first. A table with 2 rows and 3 columns has shape (2, 3). The stack of two such tables above has shape (2, 2, 3): 2 tables, each with 2 rows, each row holding 3 numbers. The last number in a shape is always the length of the innermost rows.

PyTorch gives you the shape as .shape, and the method .size() returns exactly the same thing. The result is a torch.Size. It behaves like a Python tuple, so you can take its length or one of its entries.

Two more numbers follow from the shape. .ndim is the number of dimensions, which is how many sizes the shape lists. .numel() is the total count of numbers in the tensor, which is all the sizes in the shape multiplied together.

t = torch.tensor([[1, 2, 3],
                  [4, 5, 6]])

print(t.shape)      # torch.Size([2, 3])
print(t.shape[1])   # 3, the number of columns
print(t.ndim)       # 2
print(t.numel())    # 6, because 2 * 3 = 6
What it holdsShapendimnumel()
One number()01
A row of 4 numbers(4,)14
A table of 2 rows, 3 columns(2, 3)26
2 tables of 2 rows, 3 columns(2, 2, 3)312
100 greyscale images, 28 by 28 pixels(100, 28, 28)378400

The last row shows why shapes matter so much in practice. A greyscale image is a table of pixel brightnesses, so a collection of 100 images is a stack of 100 tables. Reading the shape (100, 28, 28) left to right tells you: 100 images, each 28 rows, each row 28 pixels. You learn the layout of the data without printing a single number.

When shapes do not fit

Operations that combine tensors need shapes that fit together. Adding a row of 3 numbers to a row of 2 has no sensible meaning, and PyTorch stops with a RuntimeError that names both sizes and the dimension where they clash:

>>> torch.tensor([1, 2, 3]) + torch.tensor([10, 20])
RuntimeError: The size of tensor a (3) must match the size of tensor b (2) at non-singleton dimension 0

A shape that does not fit is the most common error in tensor code, and the fix starts the same way every time: print the .shape of each tensor in the failing line and compare them dimension by dimension. The numbers in the message tell you which dimension to look at.

True or false?

A tensor of shape (3, 4) holds 7 numbers.

False. The sizes multiply: 3 rows of 4 numbers each are 12 numbers. numel() returns 12.

In a tensor of shape (5, 3, 4), the last size, 4, is the length of each innermost row.

True. Shapes are read from the outside in: 5 tables, each with 3 rows, each row holding 4 numbers.

t.shape and t.size() can give different answers for the same tensor.

False. shape is another name for size(). Both return the same torch.Size.

Data type: what kind of numbers

Every tensor has one data type, its dtype, shared by all of its elements. The two families you meet constantly are whole numbers (integers, such as a pixel brightness or a class label) and floating-point numbers, which can hold fractions such as 0.25 or -1.5. A model computes with floating-point numbers, because the small adjustments made during training are fractions.

Each type also has a size in bits, the amount of memory one number takes. More bits let a type hold a wider range of numbers, or more precise ones. These are the types that matter for now:

dtypeHoldsTypical use
torch.float32 (torch.float)32-bit floating pointThe default for decimals; what models compute with
torch.float64 (torch.double)64-bit floating pointExtra precision, rarely needed for training
torch.int64 (torch.long)64-bit signed integerThe default for whole numbers; class labels
torch.uint88-bit unsigned integer, 0 to 255Pixel brightnesses of stored images
torch.boolTrue or FalseThe result of a comparison

torch.tensor picks the type from the data you give it. Python whole numbers become torch.int64. Numbers with a decimal point become torch.float32, PyTorch's default floating-point type (not 64-bit, as Python's own floats are). If the data mixes the two, the whole tensor becomes floating point. One tensor cannot hold two types, so the whole numbers are stored as decimals too.

print(torch.tensor([1, 2, 3]).dtype)     # torch.int64
print(torch.tensor([1.5, 2.0]).dtype)    # torch.float32
print(torch.tensor([1.2, 3]))            # tensor([1.2000, 3.0000])

# Choose the type yourself, or convert an existing tensor
a = torch.tensor([1, 2, 3], dtype=torch.float32)
b = torch.tensor([1, 2, 3]).float()
print(b)                                 # tensor([1., 2., 3.])

The printout gives the type away: 1. with a dot is a floating-point number, 1 without one is an integer. .float() is short for converting to torch.float32. It returns a new tensor and leaves the original unchanged.

In old code you will also see the capitalised torch.Tensor([1, 2, 3]). It always makes floats, even from whole numbers, and the documentation recommends torch.tensor instead.

True or false?

torch.tensor([1, 2, 3]) holds floating-point numbers.

False. Python whole numbers become torch.int64. Add dtype=torch.float32, or call .float(), to get floating-point numbers.

torch.tensor([0.5, 2.5]) has the dtype torch.float32.

True. PyTorch's default floating-point type is 32-bit, even though a Python float is 64-bit.

Indexing: one element or one row

To pick numbers out of a tensor you use square brackets, as with Python lists, and positions count from 0. The difference is that a tensor takes one position per dimension, separated by commas, in the same left-to-right order as its shape. Take this table of shape (3, 4), where each number spells out its own row and column:

x = torch.tensor([[ 0,  1,  2,  3],
                  [10, 11, 12, 13],
                  [20, 21, 22, 23]])
x[1, 2]: one element
  1. 0
  2. 1
  3. 2
  4. 3
  5. 10
  6. 11
  7. 12
  8. 13
  9. 20
  10. 21
  11. 22
  12. 23
x[1]: one row
  1. 0
  2. 1
  3. 2
  4. 3
  5. 10
  6. 11
  7. 12
  8. 13
  9. 20
  10. 21
  11. 22
  12. 23
print(x[1, 2])          # tensor(12)
print(x[1, 2].item())   # 12, a plain Python number
print(x[1])             # tensor([10, 11, 12, 13])
print(x[-1])            # tensor([20, 21, 22, 23]), the last row

Three things in this output are worth reading closely.

  • x[1, 2] means row 1, column 2. Writing x[1][2] gives the same element in two steps, but the comma form is the usual one.
  • One element comes back as a tensor with zero dimensions, tensor(12), not as a Python number. .item() turns a one-element tensor into a plain Python number, which is what you want for printing a result or storing it in a list.
  • When you give fewer positions than the tensor has dimensions, every dimension you left out is taken whole: x[1] is the whole of row 1. A negative position counts from the end, so -1 is the last row.

Each position you give as a single number removes that dimension from the result. x has shape (3, 4), x[1] has shape (4,) and x[1, 2] has shape ().

True or false?

x[1, 2] on an integer tensor returns the Python int 12.

False. It returns tensor(12), a tensor with zero dimensions. Call .item() to get the Python number.

For a tensor of shape (100, 28, 28), x[0] is one whole table of shape (28, 28).

True. One position picks one entry of the first dimension and keeps the remaining two complete.

Slicing: a range, along one dimension or several

A slice picks a range of positions instead of one. It is written start:stop, as with Python lists: the start is included and the stop is not, so 1:3 means positions 1 and 2.

Leaving out the start means from the beginning, leaving out the stop means to the end, and a bare : means every position along that dimension. Inside the brackets you can mix single positions and slices, one per dimension.

x[:, 0]: one column
  1. 0
  2. 1
  3. 2
  4. 3
  5. 10
  6. 11
  7. 12
  8. 13
  9. 20
  10. 21
  11. 22
  12. 23
x[1:, :2]: a block
  1. 0
  2. 1
  3. 2
  4. 3
  5. 10
  6. 11
  7. 12
  8. 13
  9. 20
  10. 21
  11. 22
  12. 23
print(x[:, 0])            # tensor([ 0, 10, 20]), every row, column 0
print(x[0, 1:3])          # tensor([1, 2]), row 0, columns 1 and 2
print(x[1:, :2].shape)    # torch.Size([2, 2]), rows 1 to the end, columns 0 and 1
print(x[1:2].shape)       # torch.Size([1, 4])
print(x[1].shape)         # torch.Size([4])

The last two lines show the difference between a position and a slice. x[1] gives position 1 as a single number, so the row dimension disappears and the shape is (4,). x[1:2] asks for a range that happens to hold one row, so the row dimension stays, with size 1, and the shape is (1, 4). The numbers are the same; the shapes are not, and a later operation that expects one of them may fail with the other.

A useful habit is to predict the shape before you run the line. Go through the brackets dimension by dimension: a single position removes that dimension, a slice keeps it with the size of its range, and a dimension you leave out at the end keeps its full size.

A slice shares its numbers with the original

Indexing with single positions and slices does not copy the numbers. The result is a view: a new way of looking at the same numbers in memory, which makes it fast even on very large tensors. The consequence is that writing into a slice changes the original tensor too.

y = torch.tensor([[1, 2, 3],
                  [4, 5, 6]])
first_row = y[0]
first_row[0] = 100
print(y)              # the 1 in y has become 100 as well

y[:, 1] = 0           # assigning to a slice writes into y itself
copy = y[0].clone()   # .clone() makes an independent copy

Writing through a slice on purpose, as in y[:, 1] = 0, is a quick way to change a whole column at once. When you need to change a part without touching the original, take a copy first with .clone().

True or false?

For a tensor x of shape (3, 4), x[1] and x[1:2] have the same shape.

False. x[1] has shape (4,) because a single position removes the dimension; x[1:2] keeps it and has shape (1, 4).

x[0, 1:3] on a tensor of shape (3, 4) returns 2 numbers.

True. Row 0 is one position, and the slice 1:3 includes columns 1 and 2 but stops before 3.

Changing an element of a slice leaves the original tensor as it was.

False. A slice is a view that shares the numbers of the original, so the original changes too. Use .clone() for a separate copy.