Lesson 11 of 145 min
PyTorch tensors and their shapes
A tensor is PyTorch's array, and a layer for pictures reads it as four sides, (batch, channels, height, width), on the CPU or on the GPU.
After this lesson you can move data between NumPy, PyTorch and the GPU, read a shape such as (batch, channels, height, width), and fix a shape error.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
Why the float is there
A NumPy array of the digits holds 64-bit decimals, and a PyTorch layer keeps its own numbers in 32-bit ones. Leave out .float() and the layer stops, and its words say which two types don't match. .float() turns the batch into the layer's type.
import torch
from sklearn import datasets
imgs = datasets.load_digits().images
conv = torch.nn.Conv2d(1, 4, 3)
conv(torch.tensor(imgs[:32]).reshape(32, 1, 8, 8))RuntimeError: Input type (double) and bias type (float) should be the same
Let PyTorch count the pictures
In a shape, -1 means "work this side out from the rest". Real code uses it for the batch, so the same line works for 32 pictures, 8 or 1.
x = torch.tensor(imgs[:32]).float()
print(x.reshape(-1, 1, 8, 8).shape)torch.Size([32, 1, 8, 8])
Two more ways to add the side of 1
You will also see these in other people's code. unsqueeze(1) puts a side of size 1 at place 1, and x[:, None] does the same with a slice. All three give the same numbers the same new shape.
print(x.unsqueeze(1).shape)
print(x[:, None].shape)torch.Size([32, 1, 8, 8]) torch.Size([32, 1, 8, 8])
A tensor that shares the array
torch.tensor copies the array's numbers. torch.from_numpy doesn't: the tensor and the array read the same numbers, so a change to one shows in the other. It is faster for a big array, and a surprise if you didn't expect it.
a = imgs[:2].copy()
t = torch.from_numpy(a)
a[0, 0, 0] = 99
print(t[0, 0, 0])tensor(99., dtype=torch.float64)
A GPU if there is one, and the layer with it
Real code falls back to the CPU when there is no GPU, so one notebook runs everywhere. Then the batch and the layer both move. Move only the batch, and the layer stops: its numbers are still on the CPU. conv = conv.to(dev) is the fix. On an NVIDIA GPU the words say cuda.
acc = torch.accelerator
dev = acc.current_accelerator() if acc.is_available() else torch.device("cpu")
x = x.reshape(32, 1, 8, 8).to(dev)
conv = torch.nn.Conv2d(1, 4, 3)
conv(x)RuntimeError: Input type (MPSFloatType) and weight type (torch.FloatTensor) should be the same
Run on Python 3.13, PyTorch 2.15.0, NumPy 2.5.5 and scikit-learn 1.9.1, on a Mac (the GPU is `mps`). Checked on .
Quiz
Two questions on this lesson. Answer as often as you like.
1 of 2
A batch for a picture model has the shape (16, 3, 224, 224). What is the 3?
2 of 2
A batch of 8 digits, with a side for the channel. What does this print?
import torch
from sklearn import datasets
imgs = datasets.load_digits().images
x = torch.tensor(imgs[:8]).float()
x = x.reshape(8, 1, 8, 8)
conv = torch.nn.Conv2d(1, 4, 3)
out = conv(x)
print(out.shape)The ideas in this lesson
- A tensor
- A tensor is PyTorch's array: the same numbers and shape as NumPy's, and it can move to a GPU.
- Batch, channels, height, width
- A layer for pictures wants four sides: how many pictures, numbers per square, then height and width.
- Device
- A tensor lives on a device. .to moves it to the GPU, and .cpu brings it back for NumPy.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
What is the 3?
Here's a game. You'll meet shapes like this one in code that works with pictures. It has four numbers. The first one is how many pictures there are.
So what does the second number count?
A tensor
Keep your guess. First, the pictures. How does PyTorch hold them?
Line three loads scikit-learn's handwritten digits: almost eighteen hundred small pictures, in a NumPy array. The first one is a zero.
Line four takes the first 32 pictures with a slice. Pictures handed over together like this are called a batch.
Then PyTorch makes a tensor from the batch: the same numbers, and the same shape, 32 by 8 by 8. The float at the end of line four turns the numbers into the decimals PyTorch's layers use.
Why not keep the NumPy array? A tensor can move to a GPU, a chip that works on thousands of numbers at once. And a model can learn from it.
Channels
x is a batch of 32 handwritten digits, a tensor of shape 32 by 8 by 8. A model for pictures is built from layers, and line six makes one. It slides a small window, 3 by 3, over each picture, and makes 4 new pictures.
The layer's first number, on line six, is one. That's how many numbers the layer reads for each square of a picture. That count is called the channels. A grey picture has one.
So, back to the question.
A colour picture has three... red, green, and blue.
That's the 3.
If you said three dimensions, you're close. The 3 is one side of the shape, and what it counts is colours.
Four sides
So this layer reads four sides, in this order. How many pictures. How many channels. Then the height... and the width.
Thirty-two colour pictures, each with three channels, two hundred and twenty-four squares high and wide. Four sides, and each one has its place.
Three sides
Our batch of digits has three sides. Line five gives x the shape it already has: 32, 8, 8.
What will the layer take the 32 for? Thirty-two pictures?
It stops. The layer expected 1 channel... but got 32 channels. Read it. Given three sides, the layer reads them as one picture: channels, then height, then width. So it put a 1 in front, a batch of one picture, and took our 32 pictures for 32 channels.
If you said 32 pictures: the layer can't tell pictures from channels.
Only the place in the shape says.
A side of size 1
The fix is a side of size one. Reshape gives the same numbers a new shape: 32 by 1 by 8 by 8. The same numbers, with a side for the channel.
What shape will the layer's answer have?
32 by 4 by 6 by 6.
Thirty-two pictures. Four channels, one for each of the layer's 4 new pictures.
And 6 by 6, because a window of 3 fits in 6 places along 8 squares.
Where a tensor lives
A tensor has a shape, and it also has a place where its numbers live: a device.
x is a tensor of 32 pictures, and the layer on line six reads it. A new tensor lives on the CPU, the computer's main chip. This line finds the GPU, whichever company made it. On this Mac, the GPU is called mps. In Colab, it's called CUDA.
The next line moves the batch there... and the line after it moves the layer too. The layer has numbers of its own, and they live somewhere as well. PyTorch works only when the batch and the layer are in the same place.
Back to NumPy
And back to NumPy?
Asking for a NumPy array of a tensor on the GPU stops, and PyTorch's own words say why. NumPy can read only a tensor on the CPU.
So, cpu first, then numpy. A NumPy array, 32 by 1 by 8 by 8, with the same numbers.
Only where they live has changed.
Four sides
So here's what you saw. A tensor is PyTorch's array. A layer for pictures reads four sides: batch, channels, height, width. Give it three sides, and it reads one picture. Move a tensor to the GPU to work... and back to the CPU for NumPy.
Every side has its place
So a number's place in the shape tells you what it counts. Now try it on this lesson's page, and take the quiz. Take eight pictures, and make the layer take them.
You use this lesson in Lab 5: On your own computer, after Git and GitHub.
Facts last checked on .
